We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Add column and dropdownedit dynamically with Id

Hello

I have a request who looks very similar to that thread : 

https://www.syncfusion.com/forums/167798/add-column-and-dropdownedit-dynamically?reply=SEKT1a

But I want to add a drop-down edit with an ID. Everything needs to be dynamic.   The problem with adding a drop-down edit with an ID it's I am not able to see the value ( text ) in the grid. (In the edit window of the grid, I see the text of the dropdown edit. When I save, that saves the ID in the col0.  And after that, I just see the Id in my grid. )

( i also need to build the field of the column dynamicaly )

<button  (click)="CreateColumn()">Add Column</button>

  <ejs-grid #grid [dataSource]='data' [editSettings]='editSettings' [toolbar]='toolbar' height='272px' [allowSorting]="true" [sortSettings]='sortOptions'

                  (actionBegin)='actionBegin($event)' (actionComplete)='actionComplete($event)' (rowSelected)='rowSelected($event)' [columns]="columns">

        </ejs-grid>



  public columns = [];

CreateColumn(){

let datasource = [ { id: 'aaa' : name: 'hello'} ];

   let col = {field: "col"+ this.columns.length, width: 150, headerText: 'header};

   col["editType"] = "dropdownedit";

   col["edit"] = { params: { query: new Query(), dataSource: datasource, fields: { text: 'name', value: 'id' } } }

   this.columns.push(col);

   

}


I tried also with a foreign key in the column,  but that does not seem to work when we add the column dynamically like that.


7 Replies 1 reply marked as answer

JC Joseph Christ Nithin Issack Syncfusion Team August 10, 2021 06:02 PM UTC

Hi Frédéric, 

  Greetings from Syncfusion support. 

   Query 1: I want to add column and a drop-down edit with an ID. Everything needs to be dynamic. 

    Based on your query and the attached code example you are trying to add a column having the dropdown edit option. On the click event of an external button. 

  On inspecting the code example provided we could see that you have pushed the new column to a public variable `columns` which is set bound to the `Columns` property of the EJ2 Grid. But you have not refreshed the columns using the `refreshColumns` method of the EJ2 Grid. We suggest you to add the code line `this.grid.refreshColumns();` in your `CreateColumn` method after pushing the newly created columns to the `columns` variable. This will help the grid to refresh the columns and will add the new column to the grid. 

Please refer the below code example. 


 
export class AppComponent { 
  @ViewChild('grid') 
  public grid: GridComponent; 
  public data: Object[]; 
  public editSettings: Object; 
  public toolbar: string[]; 
  public orderidrules: Object; 
  public customeridrules: Object; 
  public freightrules: Object; 
  public pageSettings: Object; 
  public editparams: Object; 
  public columns; 
 
  public ngOnInit(): void { 
    orderDetails.forEach(dat => (dat['Currency'] = 'USD')); 
    this.data = orderDetails; 
    this.editSettings = { 
      allowEditing: true, 
      allowAdding: true, 
      allowDeleting: true, 
      mode: 'Dialog' 
    }; 
    this.toolbar = ['Add', 'Edit', 'Delete']; 
    this.orderidrules = { required: true, number: true }; 
    this.customeridrules = { required: true }; 
    this.freightrules = { required: true }; 
    this.editparams = { params: { popupHeight: '300px' } }; 
    this.pageSettings = { pageCount: 5 }; 
    this.columns = [ 
      { 
        field: 'OrderID', 
        headerText: 'Order ID', 
        isPrimaryKey: true 
      }, 
      { 
        field: 'CustomerID', 
        headerText: 'Customer ID' 
      }, 
      { 
        field: 'Freight', 
        format: 'N2', 
        editType: 'numericedit' 
      }, 
      { 
        field: 'Currency', 
        editType: 'dropdownedit', 
        edit: { 
          params: { 
            query: new Query(), 
            dataSource: [{ text: 'USD' }, { text: 'GBP' }, { text: 'EUR' }], 
            fields: { text: 'text', value: 'text' } 
          } 
        } 
      } 
    ]; 
  } 
 
  CreateColumn() { 
    let datasource = [{ id: 'aaa', name: 'hello' }]; 
 
    let col = { 
      field: 'col' + this.columns.length, 
      width: 150, 
      headerText: 'header' 
    }; 
 
    col['editType'] = 'dropdownedit'; 
 
    col['edit'] = { 
      params: { 
        query: new Query(), 
        dataSource: datasource, 
        fields: { text: 'name', value: 'id' } 
      } 
    }; 
    this.columns.push(col as any); 
    this.grid.refreshColumns();// refreshes the grid's columns 
  } 
} 






Query 2: I am not able to see the value ( text ) in the grid. (In the edit window of the grid, I see the text of the dropdown edit. When I save, that saves the ID in the col0.  And after that, I just see the Id in my grid. ) 
 
     Based on your query you have added the a dropdown edit for a dynamically added column. When you edit you are able to see the text value provided in the dataSource of the dropdown edit and when you save you are seeing the Id value provided in the dataSource of the dropdown in your grid.  
    
     On further validating the code example provided we could find that you have set the `text` as name and `value` as id in the `fields` property of the dropdown. By default in a dropdown when you select an option the display text will be the value of the `fields.text` property and the dropdown’s value will be the value of the `fields.value` property. Hence when you save the edit the particular column’s value will be set as the value of the dropdown which is the `fields.value` property. Since you have set the ` fields.value ` as id, the grid automatically displays the id value. 

    If you want to display the same value as display text of the dropdown, we suggest you to set both the `fields.text ` property and the `fields.value` property as `name`.  

Please refer the below code example. 

CreateColumn() { 
    let datasource = [{ id: 'aaa', name: 'hello' }]; 
 
    let col = { 
      field: 'col' + this.columns.length, 
      width: 150, 
      headerText: 'header' 
    }; 
 
    col['editType'] = 'dropdownedit'; 
 
    col['edit'] = { 
      params: { 
        query: new Query(), 
        dataSource: datasource, 
        fields: { text: 'name', value: 'name' } 
      } 
    }; 
    this.columns.push(col as any); 
    this.grid.refreshColumns();// refreshes the grid's columns 
  } 






Please refer the attached sample and revert for more queries. 

Regards, 
Joseph I. 



FR Frédéric replied to Joseph Christ Nithin Issack August 11, 2021 01:04 AM UTC

Maybe I do not understand well.. but I've said that I need the ID of the dropdown edit.

Now I see my text value everywhere.  but how I will save the ID of the value of the drop-down edit after I save all my rows in the database?

I just have the text value in my grid.


Maybe it's store somewhere that I didn't find?



JC Joseph Christ Nithin Issack Syncfusion Team August 11, 2021 06:23 PM UTC

Hi Frédéric, 

  Thanks for your update. 

  Based on your requirement you are able to see the text value in the grid but you need to save the id value of the dropdown edit in your database. For example in your dropdowns database you are having two fields `id` and `text`, you want to use the `text` value to be displayed on the grid and the `id` value should be saved to the dataSource of the grid. 

   If this is your requirement, you can achieve this using the `foreignKey Column` feature of the EJ2 Grid. The foreignKey feature can be enabled using the `column.dataSource`, `column.foreignKeyField` and `column.foreignKeyValue` properties. Where the `column.dataSource` will have the foreign data (external dataSource), `column.foreignKeyField` will have the mapping column name of the foreign data and the `column.foreignKeyValue` will have the display field from the foreign data. 


  If we have misunderstood your query, then please share the following information so that we will be able to provide the exact solution for your query ASAP. 

  • Explain the requirement in detail.
  • Share the complete grid rendering code.
  • If possible please provide a screenshot or video demonstration of your requirement.

Regards, 
Joseph I.  



FR Frédéric August 12, 2021 05:02 AM UTC

Hello, I think you should try it because if it's supposed to work, there is a bug in your grid component.

I used the stackblitz that you gave here in the previous message.  I changed the function CreateColumn And when I add a column, the grid stays in the refresh mode and it's stuck there.


If it's not a bug, maybe you can help me and show me where is my mistake ?

import {  employeeData } from './data';

  CreateColumn() {
     let col = {
      field: 'col' + this.columns.length,
      width: 150,
      headerText: 'header'
    };

      col['editType'] = 'dropdownedit',
      col['foreignKeyValue'] = 'FirstName',
      col['foreignKeyField'] = 'col0',
      col['dataSource'] = employeeData,
        
  
    this.columns.push(col as any);
    this.grid.refreshColumns(); // refreshes the grid's columns
  }

export let employeeDataObject[] = [{
    'col0': 1,
    'LastName': 'Davolio',
    'FirstName': 'Nancy',
    'Title': 'Sales Representative',
    'TitleOfCourtesy': 'Ms.',
    'BirthDate': new Date(-664743600000),
    'HireDate': new Date(704692800000),
    'Address': '507 - 20th Ave. E.\r\nApt. 2A',
    'City': 'Seattle',
    'Region': 'WA',
    'PostalCode': '98122',
    'Country': 'USA',
    'HomePhone': '(206) 555-9857',
    'Extension': '5467',
    'Photo': { 'Length': 21626 },
    'Notes': 'Education includes a BA in psychology from Colorado State University in 1970.  She also completed\
    \'The Art of the Cold Call.\'  Nancy is a member of Toastmasters International.',
    'ReportsTo': 2,
    'PhotoPath': 'http://accweb/emmployees/davolio.bmp'
}, {
    'col0': 2,
    'LastName': 'Fuller',
    'FirstName': 'Andrew',
    'Title': 'Vice President, Sales',
    'TitleOfCourtesy': 'Dr.',
    'BirthDate': new Date(-563828400000),
    'HireDate': new Date(713764800000),
    'Address': '908 W. Capital Way',
    'City': 'Tacoma',
    'Region': 'WA',
    'PostalCode': '98401',
    'Country': 'USA',
    'HomePhone': '(206) 555-9482',
    'Extension': '3457',
    'Photo': { 'Length': 21626 },
    'Notes': 'Andrew received his BTS commercial in 1974 and a Ph.D. in international marketing from the University of \
    Dallas in 1981.  He is fluent in French and Italian and reads German.  He joined the company as a sales representative, \
    was promoted to sales manager in January 1992 and to vice president of sales in March 1993.  Andrew is a member of the \
    Sales Management Roundtable, the Seattle Chamber of Commerce, and the Pacific Rim Importers Association.',
    'ReportsTo': 7,
    'PhotoPath': 'http://accweb/emmployees/fuller.bmp'
}];



JC Joseph Christ Nithin Issack Syncfusion Team August 13, 2021 04:41 PM UTC

Hi Frédéric, 

  Thanks for your update. 

  Based on your query you have tried to add a new `forignKey Column` dynamically on a button click, but the Grid remains in the refresh mode and the spinner is not removed. 
   
   On inspecting the code example provided we could find that you have defined the grid with a set of columns which has no `foreignKey` column, so the `foreignKeyModule` of the grid’s instance will be empty. And, when you try to add new `foreignKey column` and call the ` refreshColumns` method of EJ2 Grid,  the grid throws an exception and remains in the refresh mode.  

  So we suggest you to use the `freeseRefresh` method of the EJ2 Grid, which refreshes the grid and the modules injected to the grid. 

Please refer the below code example:  


 
  CreateColumn() { 
    let datasource = [ 
      { orderid: 10268, id: 'aaa', name: 'hi' }, 
      { orderid: 10269, id: 'bbb', name: 'hello' } 
    ]; 
 
    let col = { 
      field: 'OrderID', 
      width: 150, 
      headerText: 'header', 
      foreignKeyValue: 'name', 
      foreignKeyField: 'orderid', 
      dataSource: datasource 
    }; 
 
    col['editType'] = 'dropdownedit'; 
 
    col['edit'] = { 
      params: { 
        query: new Query(), 
        dataSource: datasource, 
        fields: { text: 'name', value: 'name' } 
      } 
    }; 
    this.columns.push(col as any); 
    this.grid.freezeRefresh(); // refreshes the grid and the modules injected to the grid. 
  } 






Please find the attached sample and revert for more queries regarding this. 

Regards, 
Joseph I. 


Marked as answer

FR Frédéric replied to Joseph Christ Nithin Issack August 16, 2021 09:42 AM UTC

Awesome.. that's working


We need to add GridAllModule.. and not just GridModule.. Took me a while to find out



MS Manivel Sellamuthu Syncfusion Team August 17, 2021 04:18 PM UTC

Hi Frédéric, 

Thanks for your update. 

We are glad to hear that the provided suggestion helped you. 

Please let us know if you need further assistance. 

Regards, 
Manivel 


Loader.
Up arrow icon