EasyUI Forum

General Category => EasyUI for jQuery => Topic started by: jega on May 10, 2022, 03:34:57 PM



Title: [SOLVED]Datagrid dynamic columns from json with formatter
Post by: jega on May 10, 2022, 03:34:57 PM
Hi.

Can't find a solution for this.

Having some column data with a formatter. The formatter is not always in the same column
[{
   "ID": 1,
   "field": "col1",
   "formatter": "formatNumber"
}, {
   "ID": 2,
   "field": "col2"
}, {
   "ID": 3,
   "field": "col3"
}]


Putting the column data in the grid

var dg = $('#dgList').datagrid({
   columns:[data]
});



Then i have this function

    function formatNumber(value,row){
        if (value < 0){
            return 'background-color:#ffee00;color:red;';
        }
    }


But i get this error:

TypeError: col.formatter is not a function

Any help

Regards Jesper


Title: Re: Datagrid dynamic column with formatter
Post by: jarry on May 11, 2022, 06:19:42 AM
Please call this code instead.

Code:
[{
   "ID": 1,
   "field": "col1",
   "formatter": function(value,row){
    return value + 'formatted';
   }
}, {
   "ID": 2,
   "field": "col2"
}, {
   "ID": 3,
   "field": "col3"
}]


Title: Re: Datagrid dynamic column with formatter
Post by: jega on May 11, 2022, 01:23:14 PM
Hi Jarry.

I already have tried this, but it's not a valid json string. Try put it in jsonlint.com


I do an ajax request to my DB and create the json response like this.


jsonData = jsonData & chr(34) & "field" & chr(34) & ":" & chr(34) & rsData("COLUMN_NAME") & chr(34) & ","
jsonData = jsonData & chr(34) & "title" & chr(34) & ":" & chr(34) & rsData("COLUMN_TITLE") & chr(34) & ","
jsonData = jsonData & chr(34) & "sortable" & chr(34) & ":" & chr(34) & "true" & chr(34) & ","

and then, how to do the rest

jsonData = jsonData & chr(34) & "formatter" & chr(34) & ":" & ????


Jesper


Title: Re: Datagrid dynamic column with formatter
Post by: jarry on May 11, 2022, 06:58:03 PM
Convert the 'formatNumber' string to a function before using it.
Code:
var data = [{
   "ID": 1,
   "field": "itemid",
   "formatter": "formatNumber"
}, {
   "ID": 2,
   "field": "col2"
}, {
   "ID": 3,
   "field": "col3"
}];
data.forEach(col => {
  if (col.formatter){
    col.formatter = eval(col.formatter)
  }
})
var dg = $('#dgList').datagrid({
   columns:[data]
});


Title: Re: Datagrid dynamic column with formatter
Post by: jega on May 12, 2022, 01:04:29 AM
Hi Jarry

Thanks.

Now it works.