8. Search and filter
You will build a search form for a list of products: a name, some categories, a stock filter and a sort order. It is sent with GET, so every search has its own address.
Try it: Mezzio · laminas-mvc
Assumes you have done chapter 0 and chapter 4.
<?php
declare(strict_types=1);
namespace App\Forms\Search;
use Laminas\Filter\StringTrim;
use Laminas\Form\Element\Checkbox;
use Laminas\Form\Element\MultiCheckbox;
use Laminas\Form\Element\Search;
use Laminas\Form\Element\Select;
use Laminas\Form\Form;
use Laminas\InputFilter\InputFilterProviderInterface;
use Laminas\Validator\StringLength;
use Override;
use Traversable;
use function array_filter;
use function array_values;
use function is_array;
use function is_string;
use function iterator_to_array;
use function preg_match;
/**
* Searches and filters a list of products
*
* It is sent with GET, so a search can be bookmarked and shared, and it needs no CSRF token. Every
* field is optional: setData() fills in whatever the query string leaves out, so any request,
* including one with no query, can be validated.
*
* @api
*
* @extends Form<array{q: string, categories: list<string>, in_stock: string, sort: string}>
*/
final class ProductSearchForm extends Form implements InputFilterProviderInterface
{
public const array CATEGORIES = [
'furniture' => 'Furniture',
'lighting' => 'Lighting',
'stationery' => 'Stationery',
];
public const array ORDERS = [
'name' => 'Name, A to Z',
'price' => 'Price, lowest first',
];
private const array DEFAULTS = ['q' => '', 'in_stock' => '0', 'sort' => 'name'];
#[Override]
public function getInputFilterSpecification(): array
{
// Elements with choices are required unless told otherwise
return [
'q' => [
'required' => false,
'filters' => [['name' => StringTrim::class]],
'validators' => [
[
'name' => StringLength::class,
'options' => [
'max' => 100,
'messages' => [StringLength::TOO_LONG => 'Search for 100 characters or fewer'],
],
],
],
],
'categories' => ['required' => false, 'error_message' => 'Choose categories from the list'],
'in_stock' => ['required' => false, 'error_message' => 'Tick or untick the stock filter'],
'sort' => ['required' => false, 'error_message' => 'Choose a sort order from the list'],
];
}
#[Override]
public function init(): void
{
$this->setAttribute('method', 'get');
$this->add([
'name' => 'q',
'type' => Search::class,
'options' => ['label' => 'Product name'],
'attributes' => ['id' => 'q', 'maxlength' => 100, 'enterkeyhint' => 'search'],
]);
$this->add([
'name' => 'categories',
'type' => MultiCheckbox::class,
'options' => ['label' => 'Categories', 'value_options' => self::CATEGORIES],
'attributes' => ['id' => 'categories'],
]);
$this->add([
'name' => 'in_stock',
'type' => Checkbox::class,
// Without the hidden field, an unticked box adds nothing to the address
'options' => ['label' => 'Only show products in stock', 'use_hidden_element' => false],
'attributes' => ['id' => 'in_stock'],
]);
$this->add([
'name' => 'sort',
'type' => Select::class,
'options' => ['label' => 'Sort by', 'value_options' => self::ORDERS],
'attributes' => ['id' => 'sort'],
]);
}
/** @param iterable<mixed, mixed> $data The query string, which can hold anything */
#[Override]
public function setData(iterable $data): static
{
$data = $data instanceof Traversable ? iterator_to_array($data) : $data;
/** @var mixed $categories */
$categories = $data['categories'] ?? [];
parent::setData([
...self::DEFAULTS,
// A list where one value belongs is ignored, as is text that is not UTF-8
...array_filter(
$data,
static fn(mixed $value): bool => is_string($value) && preg_match('//u', $value) === 1,
),
// One category can arrive without the brackets that make it a list
'categories' => is_array($categories) ? array_values($categories) : [$categories],
]);
return $this;
}
}
The handler or controller searches through a one-method interface:
<?php
declare(strict_types=1);
namespace App\Forms\Search;
/** @api */
interface ProductCatalogueInterface
{
/**
* @param array{q: string, categories: list<string>, in_stock: string, sort: string} $criteria The
* validated data of ProductSearchForm
* @return list<Product>
*/
public function search(array $criteria): array;
}
<?php
declare(strict_types=1);
namespace App\Forms\Search;
use function intdiv;
use function sprintf;
/** @api */
final readonly class Product
{
public function __construct(
public string $name,
public string $category,
public int $cents,
public bool $inStock,
) {}
public function price(): string
{
return sprintf('%d.%02d', intdiv($this->cents, num2: 100), $this->cents % 100);
}
}
<?php
declare(strict_types=1);
namespace App\Forms\Search;
use Override;
use function array_filter;
use function in_array;
use function str_contains;
use function strtolower;
use function usort;
/**
* Stands in for a database query in the running examples
*
* @api
*/
final class DemoProductCatalogue implements ProductCatalogueInterface
{
#[Override]
public function search(array $criteria): array
{
$term = strtolower($criteria['q']);
$categories = $criteria['categories'];
$found = array_filter(
$this->products(),
static fn(Product $product): bool => (
('' === $term || str_contains(strtolower($product->name), $term))
&& ([] === $categories || in_array($product->category, $categories, strict: true))
&& ('1' !== $criteria['in_stock'] || $product->inStock)
),
);
usort($found, static fn(Product $a, Product $b): int => 'price' === $criteria['sort']
? $a->cents <=> $b->cents
: $a->name <=> $b->name);
return $found;
}
/** @return list<Product> */
private function products(): array
{
return [
new Product('Desk lamp', 'lighting', 3900, true),
new Product('Floor lamp', 'lighting', 8900, false),
new Product('Fountain pen', 'stationery', 2400, true),
new Product('Notebook', 'stationery', 450, true),
new Product('Oak desk', 'furniture', 24_900, false),
new Product('Office chair', 'furniture', 12_900, true),
];
}
}
The form needs no factory. FormElementManager creates it and calls init().
Mezzio
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Forms\Search\ProductCatalogueInterface;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
/** @api */
final class SearchHandlerFactory
{
public function __invoke(ContainerInterface $container): SearchHandler
{
return new SearchHandler(
$container->get(FormElementManager::class),
$container->get(TemplateRendererInterface::class),
$container->get(ProductCatalogueInterface::class),
);
}
}
<?php
declare(strict_types=1);
namespace App;
use App\Forms\Search\DemoProductCatalogue;
use App\Forms\Search\ProductCatalogueInterface;
use App\Handler\SearchHandler;
use App\Handler\SearchHandlerFactory;
use Laminas\ServiceManager\Factory\InvokableFactory;
/** @api */
final class SearchConfigProvider
{
/** @return array<string, mixed> */
public function __invoke(): array
{
return [
'dependencies' => [
'aliases' => [
ProductCatalogueInterface::class => DemoProductCatalogue::class,
],
'factories' => [
DemoProductCatalogue::class => InvokableFactory::class,
SearchHandler::class => SearchHandlerFactory::class,
],
],
];
}
}
Add the provider to config/config.php, and register the route:
<?php
declare(strict_types=1);
use App\Handler\SearchHandler;
use Mezzio\Application;
return static function (Application $app): void {
$app->route('/search', SearchHandler::class, ['GET'], 'search');
};
The route allows only GET. ImplicitHeadMiddleware answers HEAD for it, and MethodNotAllowedMiddleware answers anything else with a 405. The Mezzio skeleton already pipes both.
<?php
declare(strict_types=1);
use Laminas\Stratigility\Middleware\ErrorHandler;
use Mezzio\Application;
use Mezzio\Csrf\CsrfMiddleware;
use Mezzio\Flash\FlashMessageMiddleware;
use Mezzio\Handler\NotFoundHandler;
use Mezzio\Router\Middleware\DispatchMiddleware;
use Mezzio\Router\Middleware\ImplicitHeadMiddleware;
use Mezzio\Router\Middleware\MethodNotAllowedMiddleware;
use Mezzio\Router\Middleware\RouteMiddleware;
use Mezzio\Session\SessionMiddleware;
return static function (Application $app): void {
$app->pipe(ErrorHandler::class);
$app->pipe(SessionMiddleware::class);
$app->pipe(FlashMessageMiddleware::class);
$app->pipe(CsrfMiddleware::class);
$app->pipe(RouteMiddleware::class);
// Answers HEAD for GET routes, and 405 when a path exists but not for this method
$app->pipe(ImplicitHeadMiddleware::class);
$app->pipe(MethodNotAllowedMiddleware::class);
$app->pipe(DispatchMiddleware::class);
$app->pipe(NotFoundHandler::class);
};
laminas-mvc
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Search\ProductCatalogueInterface;
use Laminas\Form\FormElementManager;
use Psr\Container\ContainerInterface;
/** @api */
final class SearchControllerFactory
{
public function __invoke(ContainerInterface $container): SearchController
{
return new SearchController(
$container->get(FormElementManager::class),
$container->get(ProductCatalogueInterface::class),
);
}
}
Merge this file into your module configuration, as Module does in chapter 0:
<?php
declare(strict_types=1);
namespace Application;
use App\Forms\Search\DemoProductCatalogue;
use App\Forms\Search\ProductCatalogueInterface;
use Laminas\Router\Http\Literal;
use Laminas\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'search' => [
'type' => Literal::class,
'options' => [
'route' => '/search',
'defaults' => ['controller' => Controller\SearchController::class, 'action' => 'form'],
],
],
],
],
'controllers' => [
'factories' => [
Controller\SearchController::class => Controller\SearchControllerFactory::class,
],
],
'service_manager' => [
'aliases' => [
ProductCatalogueInterface::class => DemoProductCatalogue::class,
],
'factories' => [
DemoProductCatalogue::class => InvokableFactory::class,
],
],
'view_manager' => [
'template_map' => [
'forms::search' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/search.phtml',
'forms::checkbox' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/checkbox.phtml',
'forms::checkboxes' => __DIR__ . '/../../../vendor/laminas-howto/forms-shared/templates/checkboxes.phtml',
],
],
];
<?php
declare(strict_types=1);
use App\Forms\Search\ProductSearchForm;
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var ProductSearchForm $form
* @var list<App\Forms\Search\Product>|null $products Null when the search was not valid
* @var string $term The term that was searched for
*/
$form->prepare();
$summary = 'Search products';
if ($products !== null) {
$count = count($products);
$summary = match ($count) {
0 => 'No products found',
1 => '1 product found',
default => $count . ' products found',
};
if ($term !== '') {
$summary .= ' for “' . $term . '”';
}
}
// The title is the first thing read after a search, so it carries the result
$this->headTitle($products === null ? 'Error: Search products' : $summary . ' - Search products', 'SET');
?>
<?= $this->partial('forms::error-summary', ['form' => $form]) ?>
<h1>Search products</h1>
<search>
<?= $this->form()->openTag($form) ?>
<?= $this->partial('forms::field', ['element' => $form->get('q')]) ?>
<?= $this->partial('forms::checkboxes', ['element' => $form->get('categories')]) ?>
<?= $this->partial('forms::checkbox', ['element' => $form->get('in_stock')]) ?>
<?= $this->partial('forms::field', ['element' => $form->get('sort')]) ?>
<?php // A named button would add itself to the address ?>
<input type="submit" value="Search">
<?= $this->form()->closeTag() ?>
</search>
<p><a href="/search">Clear the search</a></p>
<?php if ($products !== null): ?>
<h2><?= $this->escapeHtml($summary) ?></h2>
<?php if ($products === []): ?>
<p>Try a shorter name, or remove some filters.</p>
<?php else: ?>
<ul class="results">
<?php foreach ($products as $product): ?>
<li>
<?= $this->escapeHtml($product->name) ?>,
<?= $this->escapeHtml(ProductSearchForm::CATEGORIES[$product->category] ?? $product->category) ?>,
<?= $this->escapeHtml($product->price()) ?>,
<?= $product->inStock ? 'in stock' : 'out of stock' ?>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<?php endif; ?>
A group of checkboxes needs a fieldset and a legend:
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\Element\MultiCheckbox $element
*/
$id = (string) $element->getAttribute('id');
$hasErrors = $element->getMessages() !== [];
if ($hasErrors) {
$element->setAttribute('aria-invalid', 'true');
}
?>
<fieldset class="field checkboxes"<?= $hasErrors ? ' aria-describedby="' . $this->escapeHtmlAttr($id) . '-error"' : '' ?>>
<legend><?= $this->escapeHtml($element->getLabel()) ?></legend>
<?= $this->formElementErrors($element, ['class' => 'error', 'id' => $id . '-error']) ?>
<?= $this->formMultiCheckbox($element) ?>
</fieldset>
The single checkbox uses the partial from chapter 2:
<?php
declare(strict_types=1);
/**
* @var Laminas\View\Renderer\PhpRenderer $this
* @var Laminas\Form\Element\Checkbox $element
*/
$id = (string) $element->getAttribute('id');
if ($element->getMessages() !== []) {
$element->setAttribute('aria-invalid', 'true');
$element->setAttribute('aria-describedby', $id . '-error');
}
?>
<div class="field checkbox">
<?= $this->formElementErrors($element, ['class' => 'error', 'id' => $id . '-error']) ?>
<?= $this->formElement($element) ?>
<?= $this->formLabel($element) ?>
</div>
<?php
declare(strict_types=1);
namespace App\Handler;
use App\Forms\Search\ProductCatalogueInterface;
use App\Forms\Search\ProductSearchForm;
use Laminas\Diactoros\Response\HtmlResponse;
use Laminas\Form\FormElementManager;
use Mezzio\Template\TemplateRendererInterface;
use Override;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
/** @api */
final readonly class SearchHandler implements RequestHandlerInterface
{
public function __construct(
private FormElementManager $forms,
private TemplateRendererInterface $renderer,
private ProductCatalogueInterface $catalogue,
) {}
#[Override]
public function handle(ServerRequestInterface $request): ResponseInterface
{
$form = $this->forms->get(ProductSearchForm::class);
// No need to ask whether the form was sent: an empty search finds everything
$form->setData($request->getQueryParams());
$products = null;
$term = '';
if ($form->isValid()) {
/** @var array{q: string, categories: list<string>, in_stock: string, sort: string} $criteria */
$criteria = $form->getData();
$products = $this->catalogue->search($criteria);
$term = $criteria['q'];
}
return new HtmlResponse($this->renderer->render('forms::search', [
'form' => $form,
'products' => $products,
'term' => $term,
]));
}
}
<?php
declare(strict_types=1);
namespace Application\Controller;
use App\Forms\Search\ProductCatalogueInterface;
use App\Forms\Search\ProductSearchForm;
use Laminas\Form\FormElementManager;
use Laminas\Http\Request;
use Laminas\Http\Response;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Stdlib\Parameters;
use Laminas\View\Model\ViewModel;
/** @api */
final class SearchController extends AbstractActionController
{
public function __construct(
private readonly FormElementManager $forms,
private readonly ProductCatalogueInterface $catalogue,
) {}
public function formAction(): Response|ViewModel
{
/** @var Request $request */
$request = $this->getRequest();
if (! $request->isGet() && ! $request->isHead()) {
/** @var Response $response */
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Allow', 'GET, HEAD');
return $response->setStatusCode(405);
}
/** @var Parameters $query */
$query = $request->getQuery();
$form = $this->forms->get(ProductSearchForm::class);
// No need to ask whether the form was sent: an empty search finds everything
$form->setData($query->toArray());
$products = null;
$term = '';
if ($form->isValid()) {
/** @var array{q: string, categories: list<string>, in_stock: string, sort: string} $criteria */
$criteria = $form->getData();
$products = $this->catalogue->search($criteria);
$term = $criteria['q'];
}
$view = new ViewModel(['form' => $form, 'products' => $products, 'term' => $term]);
return $view->setTemplate('forms::search');
}
}
How it works
A search is a GET. The fields go into the address, so results can be bookmarked, shared and reached with the back button. Searching changes nothing, so the form needs no CSRF token and does not extend the base form from chapter 0.
There is no "was it sent?" check. The query string is always given to the form. With every field optional, an empty one is a valid search for everything.
Say that fields are optional. A select, a checkbox and a group of checkboxes are all required unless the input filter says otherwise.
Defaults live in setData(). A link may carry only ?q=lamp. Filling in the rest means the data you get back always has every field.
The query string can hold anything. Without the base form, this one tidies its own input. A list sent where one value belongs is ignored. So is text that is not valid UTF-8, which StringTrim would otherwise turn into null. A single category sent without brackets becomes a list, so your code always gets one.
Unknown choices are errors. A category that does not exist gets a message in plain words, and no results, rather than a silently different search.
Keep the address clean. The button has no name, and use_hidden_element is off for the single checkbox, so only real filters appear.
Tell people what happened. The page title and a heading give the number of results and repeat the term. Finding nothing is not an error. The form sits in a search element, which screen reader users can jump to.
Before you use this for real
- Pass the values to your database as bound parameters. Never build SQL from them.
- Escape
%and_if you use the term in aLIKEpattern. - Take column names for sorting from your own list, as the demo does, never from the request.
- Show only what the person is allowed to see.
- Remember that addresses are logged and shared. Do not search by anything private with
GET. - Limit the number of results, and how often one client can search.
Further opportunities
None of these are built or tested here. Add the ones your site needs.
| Opportunity | Where | How |
|---|---|---|
| Page through results | Handler and template | Add laminas-paginator. Keep the filters in each link, mark the current page with aria-current, and start at page one after a new search |
| Show categories from a database | Factory | Fill value_options the way chapter 4 injects a service |
| Remove one filter at a time | Template | Show each active filter as a link to the same search without it |
| Suggest names while typing | A small script | Follow the WAI-ARIA combobox pattern, and keep the button |
| Update results in place | A small script | Replace the results, update the address and announce the new count |
| Help search engines | Layout | Decide which result pages should be indexed, and add noindex to the rest |
Common mistakes
- Using
POST, so a search cannot be bookmarked and the back button warns about resending. - Adding a CSRF token to a search, which then ends up in addresses and logs.
- Leaving a select or checkbox required, so a bare link shows errors.
- Assuming a group of checkboxes always arrives as a list.
- Putting the term into the page without escaping it.