Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paginate a search result in CakePHP

I've set a simple search engine on my CakePHP project which looks like that :

<?php 
    echo $this->Form->create("Post", array(
        "action" => "search", 
        "id" => "searchForm"
    ));
    echo $this->Form->input("keyword", array(
        "label" => "",
        "type" => "search",
        "placeholder" => "Recherche..."
    ));
    echo $this->Form->end(); 
?>

Here is the controller :

function search() {
    $keyword = $this->request->data;
    $keyword = $keyword["Post"]["keyword"];
    $cond = array("OR" => array(
        "Post.title LIKE '%$keyword%'",
        "Post.description LIKE '%$keyword%'"
    ));
    $posts = $this->Post->find("all", array("conditions" => $cond));
    $this->set(compact("posts", "keyword"));
}

And it works great. The only problem is when I want to paginate the results. I simply add :

$posts = $this->paginate();

And here is the problem. When I add this, CakePHP give me all the posts and not only the ones that match the keyword.

So, if you would have a solution, it would be nice :)

like image 241
Axiol Avatar asked Dec 13 '12 14:12

Axiol


1 Answers

According to the CakePHP book you should be able to do

$this->paginate('Post', array(
    'OR' => array(
        'Post.title LIKE' => "%$keyword%",
        'Post.description LIKE' => "%$keyword%"
    )

));

Or you can do it like this ( from the cakephp site ).

public function list_recipes() {
    $this->paginate = array(
        'conditions' => array('Recipe.title LIKE' => 'a%'),
        'limit' => 10
    );
    $data = $this->paginate('Recipe');
    $this->set(compact('data'));
);

Source: http://book.cakephp.org/2.0/en/core-libraries/components/pagination.html

like image 164
Eoin Murphy Avatar answered Nov 11 '22 22:11

Eoin Murphy