How to create a search form in CakePHP?

Member

by ryleigh , in category: PHP Frameworks , 2 years ago

How to create a search form in CakePHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by muriel.schmidt , 2 years ago

@ryleigh 

To create a search form in CakePHP, follow these steps:


Step 1: Create a Form in your View Create a form in your view with the input field for your search query. For example:

1
2
3
4
<?= $this->Form->create(null, ['type' => 'get', 'url' => ['controller' => 'Articles', 'action' => 'search']]) ?>
<?= $this->Form->input('q', ['label' => 'Search']) ?>
<?= $this->Form->button(__('Search')) ?>
<?= $this->Form->end() ?>


The form is created with Form->create(), and the input field for the search query is created using Form->input(). The form's method is set to GET, and the form action is set to the search action in the ArticlesController.


Step 2: Create the Search Action in your Controller Create a search action in your controller to handle the search query. For example:

1
2
3
4
5
6
7
8
9
public function search()
{
    $query = $this->request->getQuery('q');

    $articles = $this->Articles->find()
        ->where(['title LIKE' => '%' . $query . '%']);

    $this->set(compact('articles', 'query'));
}


This action retrieves the search query from the URL parameters, performs a search using the LIKE SQL operator, and passes the resulting articles and query back to the view using set().


Step 3: Display the Search Results in your View Display the search results in your view. For example:

1
2
3
4
5
6
7
8
9
<h2>Search Results for <?= h($query) ?></h2>

<ul>
    <?php foreach ($articles as $article): ?>
    <li>
        <?= $this->Html->link($article->title, ['action' => 'view', $article->slug]) ?>
    </li>
    <?php endforeach; ?>
</ul>


This view displays the search query at the top, and then iterates over the resulting articles and displays them as links.


That's it! You now have a search form in CakePHP that searches for articles by title.