views:

301

answers:

1

I am trying to implement a very simple search function with PHP in symfony.

Basically I have a form that posts a query and I want to retrieve the items in the database that match the query.

If I have a User table with columns first_name and last_name, I want to be able to retrieve all items that contain a query. For example, if I submit 'a', I will get all names that have an 'a' in them:

  • Bat Man
  • Black Beard
  • Adam West
  • Mister A

So I know I can get all objects in the table whose first names contain 'a' by specifying criteria:

$c = new Criteria();  
$c->add(UserPeer::FIRST_NAME, '%a%', Criteria::LIKE);  
$users = UserPeer::doSelect($c);  

Is there a way I can pass a variable like $query in the add() function? Can I acquire $query via a form and then pass it as a variable in the add function and get all the objects that contain it? Am I even going about this the right way?

+3  A: 

On your form create an input with the id 'query'

<label for="query">Query:</label>
<?php echo input_tag('query') ?>

In the action get the parameter IF the form has been submitted then pass it into your criteria

if($this->getRequest()->getMethod() == sfRequest::POST)
{
    $query = $this->getRequestParameter('query');

    $c = new Criteria();
    $c->add(UserPeer::FIRST_NAME, '%'.$query.'%', Criteria::LIKE);
    $users = UserPeer::doSelect($c); 

}
Jon Winstanley
This method works for symfony 1.0; symfony 1.1 to 1.3 supports this method using the sf10CompatPlugin, and 1.4 deprecates this method in full support of the sfForm sub-framework.
Raise
Thanks for your note Raise
Jon Winstanley