Dynamically Create Data Grid

Hello,

How to create dynamically Data Grid  in Vue.? I want to create common component in my project
1) Create columns & rows
2) pagination, searchbox for datagrid 
Please share with example.. 

<template>
    <div class="oo_tablesale">
        <div class="oo_responsivetable">
            <div class="oo_tableset fixed-table-body">
                <div class="panel filterable">
                    <div class="panel-body">
                        <div id='container'>
                            <div id="Grid"></div>
                        </div>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import Vue from "vue";
import localizeConstants from "../../../localization/localization-constants.js";

import { GridPluginPageSortFilter } from "@syncfusion/ej2-vue-grids";
Vue.use(GridPlugin);

export default {
  props: ["displayFields""pkey""recList""recclass"],
  components: {},
  data() {
    return {
      localizedArray: localizeConstants,
      selectedRow: 0,
      grid: ""
    };
  },
  provide: {
    grid: [PageSortFilter]
  },
  mounted() {
    this.createDataGrid();
  },
  methods: {
    select: function(rec) {
      this.selectedRow = rec[this.pkey];
      this.$emit("select"rec);
    },
    createDataGrid: function() {
      debugger;
      Grid.Inject(Page);
      Grid.Inject(Sort);
      this.grid = new Grid({
        allowSorting: true,
        allowPaging: true,
        pageSettings: { pageSize: 15 },
        selectionSettings: { persistSelection: true }
      });
      this.grid.appendTo("#Grid");
      let query = this.$refs.grid.ej2Instances.renderModule.data.generateQuery(
        true
      );
      this.grid.dataSource = recList;
      for (var i = 0i < this.displayFields.lengthi++) {
        this.grid.columns.field = this.displayFields[i].DtlCol;
        this.grid.columns.headerText = this.displayFields[i].HdrLbl;
      }
      this.grid.columns = this.$refs.grid.ej2Instances.getVisibleColumns();
    }
  }
};
</script>


13 Replies 1 reply marked as answer

RS Rajapandiyan Settu Syncfusion Team June 29, 2020 09:06 AM UTC

 
Thanks for contacting Syncfusion support. 
 
Based on your query you need to create the Data Grid dynamically in Vue sample. We checked your code example and found that you have try to render the columns dynamically in the Grid. To render the columns dynamically you have added the columns in columns API using grid instance and you also called getVisibleColumns() method to render the columns. 
 
The getVisibleColumns() method is used to get the visible columns which is rendered in the Grid. To render the columns dynamically, we suggest you to call the refreshColumns method to refresh the columns in the grid. 
 
Find the code example:  
 
 
export default { 
  components: {}, 
  data() { 
    return { 
      selectedRow: 0, 
      grid: "", 
      displayFields: [ 
        { field: "OrderID", headerText: "Order ID" }, 
        { field: "CustomerID", headerText: "Customer ID" } 
      ] 
    }; 
  }, 
--------------------------------------------------------- 
createDataGrid: function() { 
      Grid.Inject(Page, Sort); 
      this.grid = new Grid({ 
        allowSorting: true, 
        allowPaging: true, 
        pageSettings: { pageSize: 15 }, 
        selectionSettings: { persistSelection: true } 
      }); 
      this.grid.appendTo("#Grid"); 
      this.grid.dataSource = [ 
        { OrderID: "10248", CustomerID: "SDFDS", EmployeeID: 1 }, 
        { OrderID: "10249", CustomerID: "BAFGE", EmployeeID: 2 } 
      ]; 
      this.grid.columns = this.displayFields; 
      this.grid.refreshColumns(); 
    } 
 
For your convenience we have attached the sample and please refer the sample from the following link 
 
 
For more information please refer the below help document, 
 
 
Regards, 
Rajapandiyan S 


Marked as answer

SH Shivani June 30, 2020 07:03 AM UTC

Hello...

Yes, it works great.

I have another query on how to add rowselected event in that, then select row gets value. 
Even how to add event like, actionBegin, actionComplete?
Also how to add function in dynamic Data Grid?

createDataGrid: function() {
      Grid.Inject(PageSortSearchToolbar);
      var dgrid = new Grid({
        //allowSorting: true,
        allowPaging: true,
        pageSettings: { pageSize: 15 },
        toolbar: ["Search"],
        selectionSettings: { persistSelection: true },
        rowSelected:"select"
      });

      dgrid.appendTo("#contentGrid");
      dgrid.columns = this.displayFields;
      dgrid.refreshColumns();
      dgrid.dataSource = this.recList;
    }


RS Rajapandiyan Settu Syncfusion Team July 1, 2020 11:49 AM UTC

Hi Shivani, 

We are glad that the provided solution resolved your requirement. 

Query : how to add function in dynamic Data Grid 
 
Based on your query we could see that you need to bind Vue function to the grid events while creating a grid by javascript way. Please refer the following code example to achieve your requirement. 
 
methods: { 
    select: function(rec) { 
      this.selectedRow = rec[this.pkey]; 
      this.$emit("select", rec); 
    }, 
    createDataGrid: function() { 
      Grid.Inject(Page, Sort, Search, Toolbar); 
      this.grid = new Grid({ 
        allowSorting: true, 
        allowPaging: true, 
        pageSettings: { pageSize: 15 }, 
        toolbar: ["Search"], 
        actionBegin: this.actionBegin,  // bind the vue methods here 
        actionComplete: this.actionComplete
        rowSelected: this.rowSelected
        selectionSettings: { persistSelection: true } 
      }); 
      this.grid.appendTo("#Grid"); 
      this.grid.dataSource = [ 
        { OrderID: "10248", CustomerID: "SDFDS", EmployeeID: 1 }, 
        { OrderID: "10249", CustomerID: "BAFGE", EmployeeID: 2 } 
      ]; 
      this.grid.columns = this.displayFields; 
      this.grid.refreshColumns(); 
    }, 
    actionBegin: function(args) { 
      console.log(args); 
    }, 
    actionComplete: function(args) { 
      console.log(args); 
    }, 
    rowSelected: function(args) { 
      console.log(args); 
    } 
  } 
   


Please get back to us if you need further assistance on this. 

Regards, 
Rajapandiyan S 



SH Shivani July 2, 2020 07:45 AM UTC

Hello, 

Yes, It works great.

I want to create dynamic empty Datagrid and then I want to assign data source.. is this possible?  
Like I want to open a pop up for display list in that I am using Datagrid to show display list. In my project there are so many pop up for display lists and for all data source are different.

So for that reason, I am creating dynamic Datagrid.





RS Rajapandiyan Settu Syncfusion Team July 3, 2020 07:47 AM UTC

Hi Shivani, 

We are glad that the provided solution resolved your requirement. 

Query : I want to create dynamic empty Datagrid and then I want to assign data source.. is this possible?   
 
Based on your query we could see that you need to bind different datasource to the same grid when opening different popups. We have prepared a sample with this requirement, in that we rendered a EJ2 Grid inside EJ2 Dialog.  

When opening the dialog triggers beforeOpen event of dialog control. In which we get the dialog element from its arguments. Now we can get the grid element instances from its args and bind the grid datasource. Please refer the below code example and sample for more information. 


<ejs-dialog 
        id="dialog" 
        ref="templateDialog" 
        :target="target" 
        :height="height" 
        :width="width" 
        :visible="false" 
        :showCloseIcon="true" 
        :content="contentTemplate" 
        :beforeOpen="beforeOpen" 
        :open="dlgOpen" 
        :close="dlgClose" 
      ></ejs-dialog> 



beforeOpen: function(args){ 
      console.log(args); 
// get the grid element instances from using its id 
      var gridObj = args.element.querySelector('#Grid').ej2_instances[0]; 
// bind the datasource to the grid 
      gridObj.dataSource = [ 
        { OrderID: 10248, CustomerID: "SDFDS", EmployeeID: 1 }, 
        { OrderID: 10249, CustomerID: "BAFGE", EmployeeID: 2 } 
      ]; 
    } 





Please get back to us if you need further assistance on this. 
   
Regards, 
Rajapandiyan S


CL Claude November 24, 2021 02:40 AM UTC

These are very useful posts to create a dynamic grid from different data sources.

How would we add a Command Column in the example with the grid.columns assigned to diplayFields above?

I have tried adding an entry in the displayFields array with key ":commands" and value "commands" and then provide the commands function in my component but the grid does not render the buttons.

My displayFields array looks like this:


[
{ field: "authorized", headerText: "Authorized", displayAsCheckBox:true },
{ field: "description", headerText: "Description" },
{ field: "model_name", headerText: "Model Name" },
{ headerText: "Actions", ":commands":"commands" }
]

Update: ​OK I figured it out. We need to supply and array for the commands in the column. It can be done this way:

[
{ field: "authorized", headerText: "Authorized", displayAsCheckBox:true },
{ field: "description", headerText: "Description" },
{ field: "model_name", headerText: "Model Name" },
{ headerText: "Actions", "commands":[{ buttonOption: { content: "MoreDetails", cssClass: "e-flat" } }] }
]


RS Rajapandiyan Settu Syncfusion Team November 24, 2021 02:16 PM UTC

Hi Claude, 

Thanks for contacting Syncfusion support. 
 
Yes, you need to bind the command column in below format. 
 
 
{ headerText: 'Commands', width: 120, commands: [{ buttonOption: { content: 'Details', cssClass: 'e-flat' } }]}, 
 
 
Find the below documentation for more information. 
 
 
 
Please get back to us if you need further assistance. 
   
Regards, 
Rajapandiyan S 



CL Claude March 16, 2022 10:55 PM UTC

Hello  Rajapandiyan,

Here is another question for dynamically building grid columns. We are able to specify the column type using the editType parameter but how do we specify the choices if using a dropdownedit as type. We tried specifying the dataSource using a json object but it does now work.  Here is our example for one of the column we are trying to implement:
 

{ field: "unit_id", headerText: "Unit" , editType:"dropdownedit", dataSource: "{json: {\"52\":\"$\\/ln-km\",\"53\":\"$\\/ln-mi\",\"54\":\"$\\/cl-km\",\"55\":\"$\\/cl-mi\",\"56\":\"$\\/sq-m\",\"57\":\"$\\/sq-ft\"}}" }


We are only seeing "request failed" in the grid when using the above.


Thank you,

Claude



RS Rajapandiyan Settu Syncfusion Team March 17, 2022 01:12 PM UTC

Hi Claude,  
  
Thanks for contacting Syncfusion support. 

Query: We are able to specify the column type using the editType parameter but how do we specify the choices if using a dropdownedit as type. 

Based on your requirement, you want to bind custom dataSource to the dropdown edit component. 
 
You can provide data source to the DropDownList by using the columns.edit.params property. While setting new data source using edit params, you must specify a new query property too for the dropdownlist as follows, 


[App.vue] 

      var columns = [ 
        ---- 
        { 
          field: "ShipCountry", 
          headerText: "Ship Country", 
          editType: "dropdownedit", 
          width: 150, 
          edit: { params: { query: new Query(), dataSource: gridData } }, 
        }, 
      ] 



Please get back to us if you need further assistance with this. 

Regards,  
Rajapandiyan S 



CL Claude replied to Rajapandiyan Settu March 17, 2022 09:49 PM UTC

Hello  Rajapandiyan ,

Thanks for your reply. Very helpful. Is there a way to populate the grid with the country_id and provide a dropdownedit configuration that will show the dropdown labels instead of the id's in the table. This is what we were initially trying to do.  We tried playing with the fields property inside the params object but have not been able to  quite make it work. When the grid display, you can see the id's but when the drop down shows up, the country name shows up. We would like to have the name shown initially but the id's used for transactions. Is this possible?

Here is our sandbox: https://codesandbox.io/s/281713-requirements-forked-v6tyqh?file=/src/App.vue

regards,

Claude



RS Rajapandiyan Settu Syncfusion Team March 18, 2022 05:31 AM UTC

Hi Claude, 
 
Thanks for your update. 

Based on your requirement, we suspect that you want to perform grid actions on one field and display another field in Grid. If so, you can achieve this by using to use foreignKey column feature. 

To bind a foreign key column in the grid’s column, we have to set foreignKeyValue, ForeignKeyField and dataSource to that column. Refer the below documentation for more information. 



Note: The data-mapping is performed based on the column field name and  foreignKeyField. So, the foreignKeyField should contains the column field values in its dataSource. Then the correspond foeignKeyValue will be shown in the Gird. 


If you want to provide custom dataSource for dropdown edit component, you can achieve this by using editparams of column. 

Please let us know you have any concerns. 

Regards, 
Rajapandiyan S 



CL Claude replied to Rajapandiyan Settu August 25, 2022 07:23 PM UTC

Hello Rajandiyan,

This time, I would like to use a custom column template in my dynamic grid. I tried specifying the custom template from the field object definition like this: 

{ headerText: "CustomButton", "template":"cTemplate" }

Where cTemplate is defined as data in the grid definition:

cTemplate: function () {  
        return { template : Vue.component('columnTemplate',{
             template: "<div>test</div>",
                data: function() {
                    return {
                        data: {}
                    }
                },
                method: {
                }
          })}
    }

But it does not render the grid when I use the above.

If I use the same cTemplate but with a static grid e-column, then it works:

<e-column headerText='Logs' width='150' textAlign='Center' :template='cTemplate'></e-column>

Can you help? Utlimately, I would like to pass a view component as the custom column.



RS Rajapandiyan Settu Syncfusion Team August 26, 2022 07:07 AM UTC

Hi Claude,


Thanks for your update.

Query: I would like to use a custom column template in my dynamic grid


By analyzing your code example, we found that you are defining the ColumnTemplate value ({ headerText: "CustomButton", template:"cTemplate" }) as string. This is the cause of reported problem.


While defining the columns in a typescript way, you have to bind the template value directly like the below code.


 

[App.vue]

export default {

  components: {},

  data() {

    return {

      grid: "",

      cTemplate: function () {

        return {

          template: Vue.component("columnTemplate", {

            template: `<div class="template_ele">

                    Hi {{cellValue}} !!!

                </div>`,

            data: function () {

              return {

                data: {},

              };

            },

            computed: {

              cellValue: function () {

                return this.data.CustomerID;

              },

            },

          }),

        };

      },

    };

  },

  methods: {

    createDataGrid: function () {

      var columns = [

        {

          field: "CustomerID",

          headerText: "Customer ID",

          template: this.cTemplate,  // define the template

          width: 120,

        },

      ];

    },

  },

};

</script>

 


Sample: https://codesandbox.io/s/281713-requirements-forked-ip9ft8?file=/src/App.vue


Please get back to us if you need further assistance.


Regards,

Rajapandiyan S
If this post is helpful, please consider Accepting it as the solution so that other members can locate it more quickly.


Loader.
Up arrow icon