Search code examples
phpjquery-easyui

EasyUI Datagrid, how can I auto generate columns?


I have a set of predefined MySQL queries whose results I want to present on an EasyUI datagrid (jQuery).

The problem is that each query returns different result columns, so I cannot use something similar to the jQuery tutorial section Dynamically change datagrid columns, as the column titles are not known before executing the query in the PHP file.


Solution

  • You can add columns dinamically to easyui datagrid.

    Let's say you have a php array that contains column you want to add to the datagrid. Assume that $dwSyntax = your query result from php code. Then build datagrid using javascript like :

    $('#datagrid').datagrid ({  
                url:<php url>
                queryParams: <query parameter>,
                height : 350, pagination : true, singleSelect : true, rownumbers : true, fitColumns: false,
                columns : [[
                                <?php
                                    $i = 0;
                                    while ($i < count($dwSyntax)) {
                                        $row = $dwSyntax[$i];
                                        echo "{ field: '".$row['field']."', title: '".$row['title']."', width: ".$row['width'].", sortable: true, align: '".$row['align']."', rowspan: 1, hidden: false },";
                                        $i++;
                                    }
                                ?>
                            ]]
            });
    


    Then insert html like

    <div id="datagrid"></div>
    

    make sure you have those keys in $dwsyntax array (field,title,width,align).
    I hope you understand what i mean. And if not, then share your query, php and javascript code.
    Goodluck.