terrid25
terrid25

Reputation: 1946

autocomplete, search multiple database tables/fields - Symfony

I have 3 models:

article [name, title]

photo [name, description]

video [name, description, transcription]

Now, I want to create an autocomplete search that will search each of those models and db fields for matching string in the input field.

Is it possible to do a search over these 3 tables?

If so, how would I go about it?

Upvotes: 0

Views: 1386

Answers (2)

guiman
guiman

Reputation: 1334

I guess your using propel.

Its absolutetly possible to do this, but if these table are not related to anything that could result in some messy code when saving. But if you absolutely need to search in those tables, my approach would be to create an action like:

public function executeAutocomplete(sfWebRequest $request)
{
  $q = $request->getParameter('q');//The value to be searched
  $limit = $request->getParameter('limit');//Not completly necessary but recommendable
  if(count($q) == 0)
  {
    return sfView::NONE;//With no input, no search
  }

  $results = array( 'article' => array(), 'photo' => array(), 'video' => array());

  $article_search = ArticlePeer::search($q,$limit);
  $photo_search = PhotoPeer::search($q,$limit);
  $video_search = VideoPeer::search($q,$limit);

   $this->process_search($results,$article_search,$photo_search,$video_search);
  //Process those three arrays to fit your need

  return $this->renderText(json_encode($result));
}

Now, the search function on the Peer classes could look like this:

ArticlePeer>>

public static function search($q,$limit = null)
{
 $c = new Criteria();
 $c->add(self::NAME,'%'.$q.'%',Criteria::LIKE);
 if(!is_null($limit))
 {
  $c->addLimit($limit);
 }
 return self::doSelect($c);
}

Finally as for the widget, i have used and adapted sfWidgetJQueryAutocomplete and it work pretty good so you should check it out.

EDIT: The short way to an embbed search field si creating sfForm wit the jQuery widget i mentioned before and leave configuration and js to the widget. You'll have to find a way to handle search resutls. Well i hope this helped you!

Upvotes: 0

Jakub Zalas
Jakub Zalas

Reputation: 36201

UNION operator is what you're looking for.

Upvotes: 1

Related Questions