Making a beautiful list with GroupingStore / View and ExtJS

    Today we’ll talk about how to make ExtJS a beautiful (and functional) list of any data, for example, a list of users or groups. I use this list in one of the current projects (although it’s not so beautiful and convenient there anymore). Such a widget can be used to display any data that is characterized not only by a test line, but also by extended data, and it’s also necessary to map some actions to each recruitment. You can dynamically update data (via the Store), as well as sorting and grouping - in general, all the features provided by the Grid component from ExtJS. I must say right away that I will use the version of ExtJS 3.0, but in the previous release, 2.3.x the example should also be workable. The given component is an example and by no means ready for use by the code, but only a demonstration of the possibilities, in your projects you can change and modify as you wish according to your capabilities. For the same reason, there is intentionally no source code for the article.

    The main point that I took into account in this component is to minimize the distance between actions, that is, looking at the list, the user should immediately get the maximum of the information he needs (in the context of the list, of course), and if that cannot be displayed, that information about the action itself ( opportunities) should also be immediately visible. That is why I refused the context menu, or rather, duplicated the actions of the icons directly in the list. Thus, I eliminate the need for an additional action (opening the menu only in order to find out the answer to the question “what else can I do from here”), immediately showing possible actions. Proceeding from the same principle, tooltips are handed out only reference information,

    Okay, let's get down to development. As a data source for the list, we will use the data array (reading it through ArrayReader ), and as the data store - Ext.data.GroupingStore . This side allows you to use data grouping by one of the fields, although I came across an interesting situation with the rendering of groups, but more on that later. And so, we transfer our data to the store, and he sorts and groups them according to the specified criterion, for which we use one of the fields. Array as the information store was chosen based on the fact that I did not need to directly update data from the server, we have a separate mechanism for this, so for simplicity we believe that we already have all the data locally.

    The source data has the following structure:
    • group id unique
    • default group icon (file name)
    • group name
    • number of users in a group
    • group code, this is to get extended information from an additional array of group data
    • group description


    1. var _user_groups = [
    2.    [0,'user_home.png','Модераторы системы',2,
    3. 'system','Служебная группа для модераторов и администраторов системы'],
    4.   [10,'user_home.png','Бизнес на играх',10,'profy',''],
    5.   [20,'user_home.png','Игры под iPhone/iTouch',22,'profy',''],
    6.   [30,'user_home.png','Разработка под FreeBSD',11,'profy',''],
    7.   [40,'user_home.png','Первый филиал',20,
    8. 'filials','Приватная группа московского филиала нашей компании'],
    9.   [50,'user_home.png','О политике и не только',120,'publicusers',''],
    10.   [60,'user_home.png','Приколы на работе',99,
    11. 'publicusers','Общая группа для развлечений, юмора и просто отдыха']
    12. ];
    * This source code was highlighted with Source Code Highlighter.


    And this is how the Store preparation code looks. We set the group code as a field for grouping, then we will get the rest of the data from the service array. Unfortunately, there are some difficulties in working with the grouping field - when rendering each line, the script will rewrite the group header and therefore we need to rewrite it every time. Although there is a mechanism for template header grouping, but despite the examples, nothing worked for me, so I redefined the header rendering function manually. Keep in mind that grouping is possible only for the same field that we sort.

    1. var _usergroup_store = new Ext.data.GroupingStore({
    2.   reader: new Ext.data.ArrayReader({},
    3.      [{
    4.     name: 'id',
    5.     type: 'int'
    6.    }, {
    7.      name: 'group_icon',
    8.     type: 'string'
    9.    }, {
    10.     name: 'group_name',
    11.     type: 'string'
    12.    }, {
    13.     name: 'count_users',
    14.     type: 'string'
    15.    }, {
    16.     id:'group_type',
    17.     name: 'group_type',
    18.     type: 'string'
    19.    }, {
    20.     name: 'group_desc',
    21.     type: 'string'
    22.    }]),
    23.    data: _user_groups,
    24.    sortInfo: {
    25.       field: 'group_type',
    26.       direction: "ASC"
    27.    },
    28.    groupField: 'group_type',
    29.    groupOnSort: true
    30. });
    * This source code was highlighted with Source Code Highlighter.


    We will also need an additional source of group data. I implemented it as an object, where you can get its description, icon and other data by the group code. This, of course, could all be included in the original data array, however, the same data will be used in other places, therefore they are taken out separately.

    1. var _user_groups_cats = {
    2.    system:{
    3.     icon:'user_home.png',
    4.     title:'Системные группы',
    5.     desc:'Служебная группа только для сотрудников Wheemplay Ltd.',
    6.     isClosed:true,
    7.     isPrivate:false
    8.   },
    9.   profy:{
    10.     icon:'user_star.png',
    11.     title:'Профессиональные группы',
    12.     desc:'Группы по интересам',
    13.     isClosed:false,
    14.     isPrivate:false
    15.   },
    16.   filials:{
    17.     icon:'user_earth.png',
    18.     title:'Группы филиалов',
    19.     desc:'Частные группы филиалов',
    20.     isClosed:false,
    21.     isPrivate:true
    22.   },
    23.   publicusers:{
    24.     icon:'group.png',
    25.     title:'Общие пользовательские',
    26.     desc:'Общедоступные группы, куда может войти любой желающий',
    27.     isClosed:false,
    28.     isPrivate:false
    29.   },
    30.   my:{
    31.     icon:'user_comment.png',
    32.     title:'Мои группы',
    33.     desc:'Мои группы (в которых вы состоите)',
    34.     isClosed:true,
    35.     isPrivate:true
    36.   }
    37. }
    * This source code was highlighted with Source Code Highlighter.


    In addition to the usual group settings, I have two additional options - whether the group is private and private. You can have any other arbitrary parameters. They are used to display the necessary icons and actions for each group based on the parameters. That is, if the group is closed, then there is no need to display an icon with the action "join the group", etc.

    Additionally, I store in the array the codes of the groups the current user is a member of:
    var _i_in_group = [0, 30, 60];

    Now we have all the data to render our list. For this, we use the Ext.grid.GridPanel component, although its functionality, of course, is a bit redundant for such an example. It would be better to use something like ListView, perhaps in the next article I will try to remake everything for it, but for now we will try through the Grid. Otherwise, one would have to come up with an independent implementation of the grouping, and the future expansion would be in question. So you have to consider your case personally - if you do not need all the features of the grid, try using the lightweight and fast ListView , but there will be much more manual work.

    And so, we create the component Ext.grid.GridPanel , as the data source we use the previously created by usExt.data.GroupingStore (_usergroup_store). The main functionality is concentrated in the description of the columns and their renderings, which we will talk about in more detail now. First, I will show you a description of columns without renderers (a renderer or renderer is a special method that returns arbitrary text or html code that is displayed as a value in a cell).

    1. columns: [{
    2.     id: 'group_name',
    3.     header: "Группы",
    4.     sortable: false,
    5.     width: 150,
    6.     dataIndex: 'group_name'
    7.      }, {
    8.     header: "Участников",
    9.     width: 35,
    10.     hidden:false,
    11.     sortable: true,
    12.     dataIndex: 'count_users'
    13.        },{
    14.     header: "действия",
    15.     width: 60,
    16.     hidden:false,
    17.     sortable: false,
    18.     dataIndex: 'count_users'
    19.      }, {
    20.     id: 'group_type',
    21.     dataIndex: 'group_type',
    22.     hidden: true,
    23.     groupable: true
    24. }]
    * This source code was highlighted with Source Code Highlighter.


    As you can see, grouping occurs according to the last field - the group_type column, which uses data from the same column in the store (I usually use the same column names, because the column id matches the dataIndex). But we don’t need to display this column, it is purely utility, for grouping, so we set the hidden: true parameter, and also indicate that we want to group by this field - groupable: true.

    There are two types of renderers for each column - renderer and groupRenderer. The first is responsible for displaying data in cells, the second is used to display the group header. Here lies one significant difficulty (although, apparently, this is just a strange architectural decision by the developers). The group header is used as the style name of this element, and if we redefine the render of the group, for example, by adding an html code, then all this text will go to the group style identifier. Below is a screenshot from Firebug to illustrate this point. I also fully admit that I did not fully understand the grouping mechanism, so if you can add or correct me, I will be grateful.



    We proceed to describe the output of each column. Before the name of the group, we can have one or two icons. The green dot indicates whether the group is open - if there is one, then the group is publicly available, or is it private or closed, another icon is displayed. You can use your own group attributes and display other information. Each icon has its own tooltip, added through the markup (often more convenient).

    1. renderer:function(obj, x, y)
    2. {
    3. var src = '';
    4. //для упрощения
    5. var tmp = _user_groups_cats[y.data.group_type];
    6.  
    7. if (tmp.isClosed == true)
    8. {
    9.  src = src +
    10. ' ';
    11. }
    12.  
    13. if (tmp.isPrivate == true)
    14. {
    15.  src = src +
    16. ' ';
    17. }
    18.  
    19. if ((tmp.isClosed == false) && (tmp.isPrivate == false)  )
    20. {
    21.  src = src +
    22.  ' ';
    23. }
    24.  
    25. // обязательно вернуть результат
    26. return src + ' ' + obj + '';
    27. }
    * This source code was highlighted with Source Code Highlighter.


    Read more about the renderer and how to set it in the official documentation . Various data are transferred to the method, we are only interested in the initial value (the first parameter), the mat data about the html object where the value is rendered, and also the object of the current record (third parameter).

    The second column is the number of participants in each group. But if the group is private, it is necessary to hide this data, so in the render we check the type of group and display the necessary value.

    1. renderer:function(obj, x, y)
    2. {
    3.  if (_user_groups_cats[y.data.group_type].isPrivate == false)
    4. {
    5.    return obj + ' учасн.';
    6. }
    7. else
    8.   return 'скрыто';
    9. }
    * This source code was highlighted with Source Code Highlighter.


    The most interesting will be the third and last column, where we will display the button icons for user actions, while their set will depend on the parameters of the group. True, there are user extensions, RowActions and CellActions , but today we will do the same manually (honestly, I just did it first and then found these extensions, so I didn’t redo the finished code).

    1. renderer:function(obj, x, y)
    2. {
    3. var src = '';
    4. var tmp = _user_groups_cats[y.data.group_type];
    5.  
    6. src = src + '
    7.   'src="/images/icons/vcard.png" alt="" align="absmiddle" /> ';
    8.  
    9. // если группа не приватная и юзер в ней не состоит
    10. if ((tmp.isPrivate == false) && (_i_in_group.indexOf(y.data.id) == -1))
    11. {
    12.  src = src + '
    13.  'src="/images/icons/user_add.png" alt="" align="absmiddle" /> ';
    14. }
    15.  
    16. if ((tmp.isPrivate == false) && (tmp.isClosed == false))
    17. {
    18. src = src + '
    19. 'src="/images/icons/group.png" alt="" align="absmiddle" /> ';
    20. }
    21.  
    22. // проверю, состоит ли юзер в группе
    23. if (_i_in_group.indexOf(y.data.id) != -1)
    24. {
    25. src = src + '
    26. 'src="/images/icons/user_delete.png" alt="" align="absmiddle" /> ' +
    27. ' ';
    28. }
    29.  
    30.   return src;
    31. }
    * This source code was highlighted with Source Code Highlighter.


    Next, we have a hidden column for grouping. For her, we will redefine the render of the group to display a beautiful title. The render gets one value, the field that is declared as a condition for grouping, in our case, is the group code, by which we will get all the rest of the information.

    1. groupRenderer:function(group)
    2. {
    3.  return ' ' + _user_groups_cats[group].title +
    4.      '';
    5. }
    * This source code was highlighted with Source Code Highlighter.


    There is the final touch, it is necessary to specify the necessary View in our table, in our case - GroupingView .

    1. view: new Ext.grid.GroupingView({
    2.     forceFit: true,
    3.     enableNoGroups: false,
    4.     autoFill: true,
    5.     scrollOffset:0,
    6.     showGroupName: false,
    7.     groupTextTpl: '{text}'
    8. })
    * This source code was highlighted with Source Code Highlighter.


    We pointed out that there can be no lines without groups, and also banned the display of the name of the group, since we redefined the render of the group. groupTextTpl - here you specify a template for displaying the name of the group, but there are difficulties with it, since it is rather difficult to describe conditions and processing of global values ​​inside the template. Therefore, we simply output what our render function returned and that’s all, without any processing.

    That's all, as a result we get a beautiful grouped list. To implement custom actions, you need to hang handlers on the icons, but I think you can handle this yourself. I also note that in the example the table header is intentionally hidden, but if it is enabled (via the grid config), it will be possible to sort the data (by those columns that are declared sortable) by clicking on the header. In this case, the grouping will be saved, that is, the data within each group will be sorted individually.

    In conclusion, I will show another screenshot, the second list, which displays all users and additional data like the name of the company and links to its website. It is obtained by a little refinement of the example described above, so you can experiment yourself.



    Also popular now: