grails paginate doesn't work

2019-06-03 10:26发布

问题:

I'm trying to use the paginate tag in grails but it isn't working.

in controller:

def show(Integer max) {
    params.max = Math.min(max ?: 10, 100)
    def etpse
    def total

    if (params.data == 'all') {

        etpse = Enterprise.findAll()
        total = Enterprise.count()
    }

    else {
        def paramsLike = "%" + params.data + "%"
        etpse = Enterprise.findAllByKeywordLike(paramsLike)
        total = Enterprise.countByKeywordLike(paramsLike)
    }

    [etpseList: etpse, instanceTotal: total]
}

in gsp:

<div id='pagination'>
    <g:paginate total="${instanceTotal}" />
</div>

回答1:

The paginate tag doesn't filter the results in your page, nor does it render the list of items. It merely creates links for the next/previous pages based on your request's parameters.

Your controller is responsible for fetching the correct page of data and your gsp is responsible for rendering the actual list of items.

The paginate tag parameters are designed to match the parameters to the GORM-injected list method and almost always go hand-in-hand:

class ItemController {
    def list() {
        [items: Item.list(params), itemCount: Item.count()]
    }
}

view:

<g:each var="item" in="${items}">
    <!-- render items here -->
</g:each>

<g:paginate controller="item" action="list" total="${itemCount}"/>

In the above code, the params list (including things like max and offset) is passed to the list method of the Item domain class, and this will grab a single page of data.

The paginate tag examines the request parameters for the same entries, determines which page of data you're viewing and creates the necessary links to the next and previous pages by using the correct values for max and offset.



回答2:

Here you go.

def show(Integer max) {

    Integer offset = params.int("offset")
    Integer max = Math.min(params.int("max") ?: 10, 100)

    if (params.data == 'all') {
        params.data = '%';
    }

    def c = Enterprise.createCriteria()
    def results = c.list(max: max, offset: offset) {
      ilike('keyword', "%" + params.data + "%")
    }


    [etpseList: results, instanceTotal: results.totalCount]
}


回答3:

You have to pass your params max and offset into your findAll, otherwise Grails does not know how to paginate your resultset.

For example,

Book.findAll(query, [max: 10, offset: 5])