A
A
Anton Natarov2015-10-07 14:17:46
symfony
Anton Natarov, 2015-10-07 14:17:46

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;
    }

I implemented it in this way. Gives Fatal error a syntax error if or swears at { }
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Romanenko, 2015-10-07
@HanDroid

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.'%')

I
Ivanq, 2015-10-07
@Ivanq

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)
substitute
public 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 question

Ask a Question

731 491 924 answers to any question