CakePHP - Search bar

less than 1 minute read

This code snippet will create a search box that uses can use to search for text in the database. The control creates a query to search certain fields of published stories

View or layout: <?php echo $form->create('Stories', array('url' => array('action' => 'index'))); echo $form->input('search_text', array('label' => false)); echo $form->end('Search'); ?>

Controler: <?php function admin_index( ) { $conditions = array( 'Story.terms !=' => '0' ) ; if( isset( $this->data['Stories']['search_text'] ) ) { $this->set('title', ' Search "'. $this->data['Stories']['search_text'] .'"' ); $conditions = array( 'Story.published' => '1', 'or' => array( 'Story.title LIKE' => '%' . $this->data['Stories']['search_text'] . '%', 'Author.name LIKE' => '%' . $this->data['Stories']['search_text'] . '%' )); }

$data = $this->paginate( 'Story', $conditions); $this->set('data', $data ); } ?>

Leave a comment