Answer the question
In order to leave comments, you need to log in
Symfony 2, how can validation be used inside a QueryBuilder?
The repository can receive two variables, the search text ( $search ) and an additional condition ( $country ).
Required: If there is a variable, add an additional condition, if not, QueryBuilder uses only the standard query.
public function findByPersonAction($search, $country)
{
$query = $this->getEntityManager()
->createQueryBuilder('p')
->select('p')
->from('DroidUserBundle:Person', 'pi')
->leftJoin('DroidUserBundle:PersonaAddress', 'c', 'WITH', 'p.person_id = c.person_id')
->where('lower(p.firstname) LIKE lower(:search)')
if($country != NULL)
{ $query->andWhere('c.country_id = :country')
->setParameter('country', $country)
}
->setParameter('search', '%'.$search.'%')
->getQuery();
$result = $query->getResult();
return $result;
}
Answer the question
In order to leave comments, you need to log in
you have a syntax error.
No ; after ->where('lower(p.firstname) LIKE lower(:search)')
and it's not clear what this line is for ->setParameter('search', '%'.$search.'%')
You don't have ; before the parenthesis; and line feed before -> superfluous.
And all the same - there will be a Fatal Error. Need top instead
public function findByPersonAction($search, $country)
substitutepublic function findByPersonAction($search, $country=null)
. With this we set the default value. Without this, there will be an error: incorrect number of function parameters
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question