How to save request parameters in page URLs in ZF2?

I use Zend \ Paginator to build a result set of results. This works great, however, adding a search form, I can not get them to play together.

URL generated by the search form on the page:

user/index/?searchTerm=hello 

How do I change the paginator Zend configuration so that it saves searchTerm in the resulting URLs?

I was hoping for something like:

 user/index/page/4/?searchTerm=hello 

What am I missing?


The module configuration route is defined as follows:

 'user' => array( 'type' => 'Zend\Mvc\Router\Http\Segment', 'options' => array( 'route' => '/user[/[:action[/]]][[id/:id]][/[page/:page]]', 'defaults' => array( 'controller' => 'Application\Controller\User', 'action' => 'index', 'id' => null, ), // the below was added to try and get the searchTerm query to be retained 'may_terminate' => true, 'child_routes' => array( 'searchTerm' => array( 'type' => 'Query', ), ), ), ), 

Page breaks are built using this in a view:

 echo $this->paginationControl( $this->users, 'sliding', array('paginator', 'User'), array('route' => 'user', 'action' => 'index') ); 

A fragment of the pagination template:

  <li> <a href="<?php echo $this->url($this->route, array('action' => $this->action, 'page' => $this->next), true); ?>"> Next &raquo; </a> </li> 

(I had the impression that passing true as the third url() parameter would save the request parameters .)

+6
source share
1 answer

Now I see what the third url() parameter does. I can simplify the links to the pages and remove the key "action" as follows:

 <a href="<?php echo $this->url($this->route, array('page' => $this->next), true); ?>"> 

The page action was mapped as part of the URL (due to the third parameter being true), so this works. In the same way, I can change the route to this:

 'route' => '/user[/[:action[/]]][[id/:id]][/[page/:page]][/[search/:search]]', 

And then the search will be saved in page links.

If I change the search form to submit via JavaScript, I can create a search URL and send it to the user.

A simple jQuery example for this approach:

 $(".search-form").submit(function() { var baseUrl = $(this).attr('action'), search = $(this).find('.search').val(); window.location = baseUrl + '/search/' + search; return false; }); 

Another option would be to redirect to the current/route/search/term in the controller if it receives a searchTerm request.

I am posting this as an answer, but I am open to better solutions.

+2
source

Source: https://habr.com/ru/post/950234/


All Articles