We plant trees with jqGrid

    Recently, for the first time I had the opportunity to "feel" such a plug-in for jQuery as jqGrid. I think this plugin is familiar to many. But in RuNet there are not many materials on its use. Well ... we will fix it!

    So, jqGrid is a pretty powerful plugin for creating various kinds of tables in their web applications. It allows you to create not only ordinary two-dimensional tables, but also tables with nested tables (something like the Excel pivot table), as well as trees. But first things first and in this article, we consider the basic properties of grids and the process of "planting trees."


    Basic properties


    Here are the useful links:
    Wikis offsite developers
    and documentation
    Quite a complete and useful demo

    The plugin has a huge number of parameters for almost complete customization of any grid. Here are the main ones that we need for example.

    url - the property determines the source that provides data for our tables and trees. It is necessary in all cases except when the elements of a table or tree are pre-created as a hardcode directly in the script. I think that hardly anyone will use this option)) By default, the address of the server function returning data in one of the established formats is indicated in it.

    datatype- the property just indicates in what format the data is returned from the server. It has many use cases (this is material for a separate article). But most often it takes the value “xml” or “json”. Explain why this is probably unnecessary.

    mType - determines which GET or POST method will send requests to the server. Possible values ​​“GET” (default) and “POST”

    treeGrid - determines whether our grid is a table or a tree (tree). true-tree, false-defaults

    caption - header of the table

    colNames - column names displayed directly in the interface. Array of strings. In what order you enter in the array, the columns will be named in that way.

    ExpandColumn- (only with treeGrid: true) defines the column name (colModel -> name, see below) the contents of which will be displayed in the interface. Those. in our colModel several columns can be defined, but in the tree naturally only one will be displayed, which we define.

    ExpandColClick - (only with treeGrid: true). By default, you can expand a node only by clicking on the triangle to the left of the node name. But, setting this property to true, this can be done by clicking on the label itself. Very convenient, I advise everyone to use.

    colModel is the most important attribute in the whole plugin. Defines properties for each column. I will list the most necessary for creating a tree :
    name- the name by which you can access a specific column or cell of the selected row. It may not match the interface name of the column.
    key is a boolean value. Required if the id for the rows of your table or tree is not returned from the server. If set to true then the id attribute for the string will take the value of this field.
    hidden - a boolean property that determines whether this column is displayed or hidden.
    resizable - a boolean property that determines whether it is possible to change the column width.
    Next, I’ll separately discuss treeGridModel, the knowledge and understanding of which is necessary for the most effective use of the plugin.

    TreeGridModel Property


    A tree is by definition designed to display information that has a hierarchical structure. So this property just defines one of two methods by which this information can be provided to the plugin.
    Here it should be noted that there is another property - treeReader , closely related to the treeGridModel property. TreeReader extends the colModel property, i.e. automatically adds additional utility columns to the end of the table hidden. And the data transmitted from the server should contain information for these columns. So for each value of treeGridModel its own treeReader is created. Generally defined forms of data representation are described in database theory and will be familiar to many.
    Consider each of the treeGridModel values ​​individually:

    adjacency- allows you to use the most simple and understandable form of presentation of hierarchical data. Its essence is that for each row the level of its nesting and the identifier of the parent element are indicated. This is what treeReader looks like:
    treeReader = {
      level_field: "level", //уровень вложенности элемента, для корневого элемента обычно 0
      parent_id_field: "parent", //идентификатор родительского элемента, для корневого элемента null
      leaf_field: "isLeaf", //является ли элемент раскрываемым
      expanded_field: "expanded" //является ли элемент раскрытым сразу после загрузки данных
    }

    * This source code was highlighted with Source Code Highlighter.

    As you can see, everything is pretty simple here. The main thing is to transfer this data correctly and everything will work fine.

    nested is the default value. The data presentation form is more complex, but has several advantages compared to adjacency when working with trees with a high level of nesting. Its essence is that not the parent element is specified for the element, but the left and right keys are specified, which determine the reference point of the beginning of the branch and the breakpoint of the end of the branch, respectively.
    treeReader : {
      level_field: "level",
      left_field:"lft", //левый ключ, определяет точку отсчета начала ветки
      right_field: "rgt", //правый ключ, определяет точку останова конца ветки
      leaf_field: "isLeaf",
      expanded_field: "expanded"
    }

    * This source code was highlighted with Source Code Highlighter.

    The first and last two properties are similar to the corresponding properties for adjacency treeGridModel.
    For more information, I advise you to refer to the following resources on the nested set and adjacency list

    EXAMPLES


    Now, with specific examples, consider the operation of the plugin. Let's say that we are big lovers of cars and we need to create some kind of tree containing car brands and different models for one brand. In general, we want to get something like this
    An example of creating a tree with jqGrid

    • 1) We need to insert the following html markup





      * This source code was highlighted with Source Code Highlighter.

      div here is completely optional, it only limits the width of our grid. The main element is an empty table element.
    • 2) Add the following jQuery code, which is responsible for creating our grid
      $('#treeGrid').jqGrid({
              url: "cars_tree.xml",
              datatype: "xml",
              height: "auto",
              mType: 'GET',       
              treeGridModel: 'adjacency',
              colNames: ["my_id", "my_name"],
              colModel: [ 
               { name: "id", width: 1, hidden: true, key:true },
               { name: "name" }
              ],
              treeGrid: true,
              caption: "Меню",
              ExpandColumn: "name",
              ExpandColClick:true,
              autowidth: true
            });

      * This source code was highlighted with Source Code Highlighter.

      As we see, we must provide the plugin with xml data from the cars_tree.xml file, where the tree structure is presented as an adjacency list .
    • 3) This is how our xml file looks like


      0
      Авто
      0

      false
      false


      1
      Honda
      1
      0
      false
      false


      2
      Civic
      2
      1
      true
      true


      3
      Cr-v
      2
      1
      true
      true


      4
      Hummer
      1
      0
      false
      false


      5
      H2
      2
      4
      true
      true


      6
      Lada
      1
      0
      true
      false



      * This source code was highlighted with Source Code Highlighter.


      Consider what is passed to our grid ... In each row, the first two cells correspond to the two columns that we registered in colModel, i.e. id and name. The remaining four correspond to treeReader for treeColModel: 'adjacency', i.e. 3rd cell — nesting level, 4th cell — id of the parent element, 5th cell — whether this cell is expanded, 6th — whether it is opened immediately after loading the grid.
    • 4) If we need to build our tree on the basis of xml-data presented in the form of a nested set , then we need to change only one line of code in the script:
      treeGridModel: 'adjacency',

      * This source code was highlighted with Source Code Highlighter.

      replaced by
      treeGridModel: 'nested',

      * This source code was highlighted with Source Code Highlighter.

      or just delete, because nested for treeGridModel is the default value.
      And the xml file will now look like:


      0
      Авто
      0
      1
      14
      false
      false


      1
      Honda
      1
      2
      7
      false
      false


      2
      Civic
      2
      3
      4
      true
      true


      3
      Cr-v
      2
      5
      6
      true
      true


      4
      Hummer
      1
      8
      11
      false
      false


      5
      H2
      2
      9
      10
      true
      true


      6
      Lada
      1
      12
      13
      true
      false



      * This source code was highlighted with Source Code Highlighter.


      As you can see, the number of cells in each row increased by one. This is due to a change in treeReader .
      The first two cells in the row are the same as they were - the values ​​for colModel. The 3rd cell - the nesting level, the 4th and 5th - determine the beginning and end of the branch (I repeat that you can read more about this at the above links), the 6th and 7th - also determine whether to open node and whether it was opened at the time of loading the tree.


    Conclusion


    In this article, we examined the simplest way to use the jqGrid plugin to create a tree view of a hierarchical data structure. This is one of many uses for the plugin. In future publications, I will continue to describe this powerful web spreadsheet tool.

    Also popular now: