custom database paging listbox

From Documentation
DocumentationSmall Talks2015Decembercustom database paging listbox
custom database paging listbox

Author
Cossaer Filip
Date
December 01, 2015
Version
ZK 6.5 and above


Foreword

This small talk shows how you can create your own custom component for real database pagination with a listbox and what is simple to use.
As I'm writing this small talk I will write about the problems and choices I encountered and explain why I did it this way.
Like all code, it is still a work in progress and I'm open to suggestions/refactoring's/improvements.

You can leave a comment below or create a discussion on ZK forum.

Introduction: Database Paging Listbox

While ZK has a lot of good components that are easy to use, one of the most important and simplest ones is the database paging listbox.
You can do automatic paging but then your whole list will be in your model.
If you wanted to do database paging you need to set a <paging> and bind it to your viewmodel.
The viewmodel is needed, as well as methods for activePage, totalSize, pageSize. When I work with Spring, this is already contained in the page I get from the repository.
I made some attempts in creating this with custom implementations of ListModel and the use of the autopaging of the listbox.
I failed here because the listbox inner paging doesn't make a difference between totalSize and pageSize.
If I used pageSize, I wasn't able to page to other pages.
If I used totalSize, everything worked BUT underlying the listbox generated totalsize minus pagesize empty objects.
For small queries, it isn't so bad, but I had queries which had results of over 1000000 while page was size 20.
The query was fast enough, but still the listbox takes a long time to load because it was creating the empty objects.
It's here that I decided to go for a custom listbox, where I added my own paging and handled it myself.

Requirements

Now it is time to think about the requirements of the listbox.
What should it do and how to make it easy for usage.
The first thing that popped in my head is MVVM. We all like it and let's be honest, it's ZK's strongest point.
Then I was looking at the listbox and paging component.
The following attributes are important for me when I work with zul :

  • pageSize
  • model
  • selectedItem
  • selectedItems
  • pagingPosition
  • checkmark
  • multiple
  • detailed

Then it's up to me how I want to code it in the zul.
The first idea was to use it like this :

<paginglistbox>
      <auxhead>
        <auxheader/>
      </auxhead>
      <listhead>
        <listheader  />
        <listheader  />
      </listhead>
      <template name="model">
        <listitem>
          <listcell>
            <label value="${each.id}" />
          </listcell>
         </listitem>
      </template>
  </paginglistbox>

But then we have a problem because paginglistbox isn't a listbox, but it's my own component who has a listbox inside.
In a zul page, the paginglistbox should look like this :

  <paging/>
  <listbox/>
  <paging/>

Luckily there are templates in ZK. With the templates, I could retrieve them and inject them in the listbox.
The usage of the paginglistbox would change to this :

<paginglistbox>
    <template>
      <auxhead>
       ...
      </template>
    </template>
  </paginglistbox>

Now we have 2 possible solutions of what we could do :

  • Define a constant name to the template you would like to use <template name="model"> for your model.
  • Don't define a name but add the name of the template in the attribute of paginglistbox.

As I'm pretty lazy, I don't want to add the name of the template in the attributes.
But let's think ahead: if I add the name in attribute I can even use @load for that.
This means I can change the template name in runtime, witch means that if I create multiple templates I can easily switch between them.
This behavior is more attractive to me more than my laziness in not writing an extra attribute.

Creating the PagingListbox Class

Here I am writing my PagingListbox and everything is going great.
At this point I realize I'm forgetting one big thing- namely sorting.
If we use sort="auto(property)" in the listheader we don't get database sorting but we sort only the page.
After some investigation of the Listheader class, I saw that if we use sort="client(property)" the sorting is enabled in the columns.
The next problem was getting that value back from the listheader. There is a setter but no suitable getter for it.
At this point I'm left with one very dangerous solution called reflection.
I don't like to use reflection because if ZK decided to change the variable name the effect would be, at best, sorting doesn't work anymore and in worst case, we will get errors.
The solution provides that with sort="client(id;name)" the pagerequest will receive the sortField as id;name

PagingListbox.java :

@ComponentAnnotation({"selectedItems:@ZKBIND(ACCESS=both,SAVE_EVENT=onSelect)",
    "selectedItem:@ZKBIND(ACCESS=both,SAVE_EVENT=onSelect)"})
public class PagingListbox extends Idspace implements AfterCompose {
        // implementation found on github link below.
   }

One of the things you will notice is the extension of IdSpace.
This is done so you can use in the paginglistbox scope some ids and if you set a second one, the ids are in a different idspace so they wouldn't clash.


The PagingModel

What's the role of the model?
Well, it should actually contain the page request to the database, but the request actually contains active page, pagesize, sortfield(s) and sortdirection
I'm again at a crossroad :

  • Do I make an abstract class where you could just need to implement 1 method- the query to the database.
  • Do I make a model, which needs an implementation of an interface for implementing the query to the database.

At first I'm leaning towards first solution but then I attended Venkat Subramaniam talk of Core Design Principles for Software Developers.
So I'm like yes you are right but it's so easy to make and use the abstract class.
But like a good student, I'm thinking of the advantages of going the other way.
And I noticed that if I work with the interface, I can create 2 implementations of the interface and switch them easy in the model without making a new instance of the model.
Reasons of doing this include multiple databases and query with different filters when you use multiple templates,...

The interface is actually quite simple; we only need 2 methods. The first one is getting the data and the second one is getting the totalsize, similar to this small talk.

PagingModelRequest.java

public interface PagingModelRequest<T> {
    Collection<T> getContent(int activePage, int pageSize, String sortField, SortDirection sortDirection);
    long getTotalSize();
}

And the code of the model

PagingModel.java

public class PagingModel<T> {

    private String sortField;
    private PagingModelRequest pagingModelRequest;
    private SortDirection sortDirection;

    public PagingModel(PagingModelRequest request) {
        this(request, null, null);
    }

    public PagingModel(PagingModelRequest request, String sortField) {
        this(request, sortField, null);
    }

    public PagingModel(PagingModelRequest request, String sortField, SortDirection sortDirection) {
        Objects.requireNonNull(request, "PageModelRequest can't be null.");
        this.pagingModelRequest = request;
        this.sortField = sortField;
        this.sortDirection = sortDirection == null ? SortDirection.ASCENDING : sortDirection;
    }

    public Collection<T> getContent(int activePage, int pageSize) {
        return pagingModelRequest.getContent(activePage, pageSize, sortField, sortDirection);
    }

    public long getTotalSize() {
        return pagingModelRequest.getTotalSize();
    }
    
    //getters and setters

    public void setPagingModelRequest(PagingModelRequest request) {
        Objects.requireNonNull(request, "PageModelRequest can't be null.");
        this.pagingModelRequest = request;
    }
}

You will notice that you can't instantiate the model without a real instance of PagingModelRequest or use the setter with null object. There was also the problem with sortDirection. Because I wanted to create a component what could be used by any implementation on the back-end, I needed to create a sortDirection with no reference to other frameworks, but make sure that it is still easy to change according to your needs.

I came up with the following enum: you can change the enum yourself by adding more properties to it.
It is already configured for usage with Spring Data.

SortDirection.java

public enum SortDirection {

    ASCENDING("ASC","ASCENDING"),
    DESCENDING("DESC","DESCENDING");
    
    private final String shortName;
    private final String longName;

    private SortDirection(String shortName, String longName) {
        this.shortName = shortName;
        this.longName = longName;
    }
    
   // getters 
}

Declare your component

Under the folder WEB-INF there is the lang-addon.xml file.
Now it's time to add our component to this file.

<language-addon>
     <component>
        <component-name>paginglistbox</component-name>
        <extends>idspace</extends>
        <component-class>my.choosen.path.PagingListbox</component-class>
    </component>
</language-addon>

We can use this in our component in the zul like this without declaring any other stuff:

  <paginglistbox/>

Spring Data Paging

Because a lot of people use spring paging, I have created an abstract class for Spring usage : SpringPagingModelRequest.java
You can find the implementation in the github repository below this small talk.

Advantages of this class :

  • Implementation of sorting multiple fields, separated by semicolon, comma or space.
  • Implementation of ignore case if desired.
  • Implementation of fix direction or opposite direction sorting.

Example :

    <listheader sort="client(id;lower(name);asc(birthdate))/>

Explication :

  • First sort field is 'id'.
  • Second sort field is 'name' with ignoring case.
  • Third sort field is 'birthdate' but always sorted in ascending order.

Usage

I have explained everything about coming to this component but still the most important thing is how to use it.
There are both required and optional attributes:

  • template : required
  • model : required
  • pageSize : optional, default 20.
  • selectedItem : optional
  • selectedItems : optional
  • pagingPosition : optional, default "top" and possible values : "top","bottom","both". Any other value will shown no paging element.
  • checkmark : optional default false
  • multiple : optional default false
  • detailed : optional default true
  • emptyMessage : optional default empty string.


I'm going to show an example of the zul usage with multiple templates, one for edit and one for readOnly.

<paginglistbox model="@load(vm.pageModel)" pagingPosition="bottom" template="@load(vm.templateName)">
    <template name="readOnly">
      <listhead>
        <listheader label="id" sort="client(id)" />
        <listheader label="name" vflex="min" />
      </listhead>
      <template name="model">
        <listitem value="${each}" item="@ref(self.value)">
          <listcell>
            <label value="${each.id}" />
          </listcell>
          <listcell>
            <label value="@load(item.name)" />
          </listcell>
        </listitem>
      </template>
    </template>
    <template name="edit">
      <listhead>
        <listheader label="id" sort="client(id)" />
        <listheader label="name" vflex="min" />
      </listhead>
      <template name="model">
        <listitem value="${each}" xxx="@ref(self.value)">
          <listcell>
            <label value="@load(xxx.id)" />
          </listcell>
          <listcell>
            <textbox value="@bind(xxx.name)" />
          </listcell>
        </listitem>
      </template>
    </template>
    </template>
  </paginglistbox>

The viewmodel does require these methods :

public PagingModel getPageModel() {
        return new PagingModel(new PagingModelRequest(){
            private long totalSize;

            @Override
            public Collection getContent(int activePage, int pageSize, String sortField, SortDirection sortDirection) {
                Sort.Direction direction = Sort.Direction.fromString(sortDirection.getShortName());
                Page page = mySpringDataRepo.findAll(new PageRequest(activePage, pageSize, direction, sortField));
                totalSize = page.getTotalElements();
                return page.getContent();
            }

            @Override
            public long getTotalSize() {
                return totalSize;
            }
        }, "id");
    }
    
    public String getTemplateName() {
        return readOnly?"readOnly":"edit";
    }
}

Important note

 <template name="model">
        <listitem value="${each}" item="@ref(self.value)">

As you can see, under the model template, I have filled the listitem's value with each, and I need to set a reference.
The binding doesn't work directly to the each object cause it's in a different lifecycle and by some strange behavior the each object is already gone before we can do the binding.
So a (hopefully temporarily) workaround is adding a reference : xxx="@ref(self.value)".
Like this we can do the binding to the xxx. You can choose the name for xxx.

Github Link

Github repository

This article is contributed by Cossaer Filip for the community. Please feel free to leave him a comment below or create a discussion on ZK forum.


Comments



Copyright © Potix Corporation. This article is licensed under GNU Free Documentation License.