Searching in Zend

From mi-linux
Jump to navigationJump to search

Apologies for this being posted very late into the assessment but I've only just figured it out.

This is an addition to the GuestBook example and assumes you have a basic working site with some articles and the GuestBook functions like fetchEntries. You WILL get errors the first time you run this code, because the variables are all given generic names. You will need to change them to match either the GuestBook example or your own site.


Part 1 - Making a search action

Your search action should probably be included in your crud controller. So you would get to it through the path "...../crud/search". The comments in the code describe what is going on.


  //Search Action
  function searchAction(){
  
    //Gets the model.
    $model = $this->_getModel();
    
    //Checks if the request is a POST or not. E.g. if the form is submitted or not.
    if($this->_request->isPost()){
      
      //If it is a POST you need to get the search keywords that were posted.
      //This line gets the value posted from a form item called 'searchBox'
      $search = $this->_request->getPost('searchBox');
      
      //Set a variable in the view. This is mainly so I can show what term they searched for.
      $this->view->searchterm = $search;
      
      //Run the searchArticle function in the model.
      //Passing it the keywords as a parameter.
		  $this->view->entries = $model->searchArticle($search);
      
    }else{ //Else no keywords were posted.
      
      //So get the form and display it.
      $form = $this->_getSearchForm();
      $form->submit->setLabel('Search');
      $this->view->form = $form;
      
      //Shows all articles if a search has not yet been made.
      //You can probably take this out if you don't want it to behave that way.
      $this->view->entries = $model->fetchEntries();
        
    }
  }

You will also need this little function to get your search form:

	//Gets the form for searching for articles.
        //The form has a default action of /search/ when it is posted.
	protected function _getSearchForm($action='search'){

                //Make sure your search form is in the /forms/ folder.
		require_once APPLICATION_PATH . '/forms/SearchForm.php';
		$form = new Form_SearchForm();
		$form->setAction($this->_helper->url($action));
		return $form;
	}


Part 2 - Writing the searchArticle function

This goes in your model file. It constructs an SQL LIKE query and uses that to return any matching entries.


  //Search.
  public function searchArticle($search){
  
    //Get Table... see guestbook example if you are missing this function.
    $table = $this->getTable();
    
    //Construct the select query based on your search keywords.
    //This query uses wildcards to display anything containing whatever $search is set to.
    $select = $table->select()->where("article LIKE ?", '%'.$search.'%');
    
    //Fetches all your entries that match the query.
    return $table->fetchAll($select)->toArray();
    
  }


Part 3 - Constructing your Search Form

A very simple form with one text input called 'searchBox' and a submit button. Goes in your 'application/forms' directory.

<?php
//application/forms/SearchForm.php

class Form_SearchForm extends Zend_Form{

	public function __construct($options = null){

		parent::__construct($options);
		$this->setName('search');

		$searchBox = new Zend_Form_Element_Text('searchBox');
		$searchBox->setLabel('Type Keywords Here:')
			->setRequired(true)
			->addFilter('StripTags')
			->addFilter('StringTrim')
			->addValidator('NotEmpty');

		$submit = new Zend_Form_Element_Submit('submit');
		$submit->setAttrib('id', 'submitbutton');
		
		$this->addElements(array($searchBox, $submit));
	}

}


Part 4 - The search view

Every action needs a view. This is the one for the search action I created. You'll notice it's quite similar to the index action of the guestbook, just looping through and displaying entries. The only difference is the form, before the search keywords are posted the view will display a form and all the articles.


<? // application/views/scipts/codesnippets/search.phtml ?>

<? // Outputs the search form ?> 
<?= $this->form ?>


<?PHP
if(isset($this->searchterm)){
?>
<H2>Search Results for: <?= $this->searchterm ?></H2>
<?PHP
}else{
?>
<H2>All Articles</H2>
<?PHP
}
?>


<? foreach ($this->entries as $entry): ?>
<DIV style="background-color: #F5F5F5; padding: 1em; border: 1px solid; color: #333333; margin: 1em;">

	<H3><?= $this->escape($entry['articletitle']) ?></H3>
	<P><?= $this->escape($entry['articlebody']) ?></P>
	<P><?= $this->escape($entry['articledate']) ?></P>
	
	<A href="<?php echo $this->url(array('controller'=>'crud', 'action'=>'edit', 'id'=>$entry['id']));?>">Edit</A>
  <BR />
  <A href="<?php echo $this->url(array('controller'=>'crud', 'action'=>'delete', 'id'=>$entry['id']));?>">Delete</A>


</DIV>
<? endforeach ?>



I hope this helps you...

I typed this out pretty fast so there are bound to be some mistakes. If you find any please let me know, or if you feel confident enough just go ahead and edit the wiki.

Nick