My Symfony2 app has a Person
entity, it has $firstName
and $lastName
as its properties. It's got a method getFullName()
which returns the full name of Person
.
// Vendor/Bundle/Entity/Person.php
public function getFullName()
{
return $this->firstName . ' ' . $this->lastName;
}
Now, I want to allow users to search Person
. There is only one search field which users can enter some value. The value can be the full name, first name, or last name of the person they look for.
Here is some code from controller which will do the filtering:
// Vendor/Bundle/Controller/PersonController.php
public function listAction(Request $request)
{
// ...
$people = $this->get('doctrine')
->getRepository('SomeBundle:Person')
->createQueryBuilder('p')
->where('p.fullName = :fullName')
->setParameter('fullName', $request->query->get('fullName'))
->getQuery()
->getResult();
// ...
}
However, it doesn't work. Apparently, it is because fullName
is not one of Person
's fields.
Is there a way to filter results using QueryBuilder, i.e. I do not want to iterate over all results and compare their names?
Although Victor's answer shows the correct result, I am still looking for a more 'elegant' way to do this. Please post your suggestion as answer if you have one!