Search in Pagination

Posted Almost 3 years ago. Visible to the public.

When there are input elements for search criteria in frontend grid with pagination block 'page/html_pager', the search params will be lost when the user click on page n. This is because the URL links in the pager do not contain the search params. There are 3 solutions:

Do not Use POST in form

<form class="form-list" id="search_form">

Simple JS Solution

This can be fixed easily with js URLSearchParams.append() Show archive.org snapshot by appending the search params to the links:

$$('div.pager .pages ol li a').each(function(el){
    let url = new URL(el.href);
    $$('#search_form .field.left input, #search_form .field.left select').each(function(ele){
         if(ele.value) {
           url.searchParams.append(ele.name, ele.value);
           el.href = url.href;
         }
    });
});

Complicated Server Side Solution if POST form

        $searches = [];
        foreach (['gender', 'criteria'] as $k) {
            if ($v = $this->getRequest()->getParam($k)) {
                $searches[$k] = $v;
            }
        }

        /**
         * Store search strings in session var to persist the searched collection for different pages.
         */
        if ($this->getRequest()->getParam('p')) {
            if (empty($searches)) {
                /**
                 * Because reset has empty $searches, how do we know this is not a reset?
                 * We cannot, so the reset button must use $_SERVER['REDIRECT_URL'] to strip URL of param p.
                 */
                $searches = Mage::getSingleton('customer/session')->getMedSearches();
            } elseif ($searches !== Mage::getSingleton('customer/session')->getMedSearches()) {
                // Search has changed, so replace session var.
                Mage::getSingleton('customer/session')->setMedSearches($searches);
            }
        } else {
            // Store the search string. If reset, $searches is empty.
            Mage::getSingleton('customer/session')->setMedSearches($searches);
        }

        if (isset($searches['gender'])) {
            $collection->addFieldToFilter('gender, $searches['gender']);
        }

The value of the search input element needs to be set:

<input 
    id="gender"
    name="gender" 
    type="text" placeholder="Gender" 
    class="input-text" 
    value="<?php echo $this->getRequest()->getParam('gender', Mage::getSingleton('customer/session')->getMedSearches()['gender'] ?? '' ?>"
>
kiatng
Last edit
Almost 3 years ago
kiatng
Tags
Posted by kiatng to OpenMage (2021-08-10 01:48)