phpcakephpcakephp-1.3

How to only display search results when needed in cakephp?


I have the following situation where I want to only display the search results when user search for something. Currrently, as I access my search page, all the search results is being displayed and if user search for a particular thing, it displays that accordingly. The following is the code in my search controller. I added a pagination for it to paginate. function simple_search() {

        $this->User->recursive = 1; 
        $this->Passion->recursive = 1; 
        $this->User->unBindModel(array('hasMany' => array('Topic','Post')),false); 

        $conditions = array(); 
        $options; 

        $or_conditions = array(); 
        $final_conditions = array(); 
        $search_fields = array('User.firstName', 'User.lastName', 'User.email', 'User.displayName'); //fields to search 'Video.tags','Video.desc' 
        $this->layout = "mainLayout"; 

        $value=''; 

         if(!empty($this->params["url"]["value"])){ 
            $value = $this->params["url"]["value"]; 
        } 

        $searches = explode(" ", $value); 
        foreach ($search_fields as $f) { 
            array_push($conditions, array("$f Like" => "$value%")); 
            for ($i = 0; $i < count($searches); $i++) { 
                if ($searches[$i] != "") { 
                    array_push($conditions, array("$f Like" => "$searches[$i]%")); 
                } 
            } 

            array_push($or_conditions, array('OR' => $conditions)); 
            $conditions = array(); 
        } 
        $final_conditions = array('OR' => $or_conditions); 
       $users = $this->User->find('all', $final_conditions); 
       $this->paginate = array( 
            'conditions' => $final_conditions, 
            'limit' => 10 
        ); 
        $users = $this->paginate('User'); 
        $this->set('search_fields', $users); 
    } 

Solution

  • Why are you doing the find('all')? A few lines later paginate() overrides the result.

    empty($this->params['url']['value'] check this and set your results to the view only in the case its not empty.

    Follow the coding standard for CakePHP and use camelCased variable names instead of underscores. http://book.cakephp.org/2.0/en/contributing/cakephp-coding-conventions.html

    Also you might want to take a look at this. https://github.com/CakeDC/search

    And at this (showing a custum find using search plugin) https://github.com/CakeDC/users/blob/master/controllers/users_controller.php#L316 https://github.com/CakeDC/users/blob/master/models/user.php#L557