I have this scenario: a entity Person, a repository for Person and a select form type.
I should take in my select form only active person.
In the entity there is a public method "isActive" that check if a Person have the permission to access in my private area. This method return true or false and is not a column in the db table, it is calculated.
I need to access this flag from my querybuilder in the Person repository. Is it possible? below the code of my querybuilder in the repository.
public function getQueryBuilderForEventRegistration()
{
$queryBuilder = $this->createQueryBuilder('e')->orderBy('e.surname', 'asc')->addOrderBy('e.name', 'asc');
return $queryBuilder;
}
and the public method in the entity Person tha t i have to access:
public function getIsActive()
{
if (empty($this->getUser()))
{
return false;
}
if (!$this->getUser()->isEnabled())
{
return false;
}
/* @var $service \Siderweb\SubscriptionBundle\Entity\UserService */
foreach ($this->getUser()->getServices() as $service)
{
if (!$service->getIsExpired())
{
return true;
}
}
return false;
}
and my type:
$builder->add('personExist', 'entity', array(
'class' => 'MyAppUserBundle:Person',
'property' => 'name',
'required' => false,
'multiple' => false,
'mapped' => false,
'empty_value' => '-- New person --',
'query_builder' => function(PersonRepository $repo) use ($options) {
return $repo->getQueryBuilderForEventRegistration();
}
))
as suggested I edit my repository like this:
public function getQueryBuilderForEventRegistration(Company $company = null, Event $event = null, $emailFilter = null)
{
$queryBuilder = $this->createQueryBuilder('e')->orderBy('e.surname', 'asc')->addOrderBy('e.name', 'asc');
$people = $queryBuilder->getQuery()->execute();
$peopleToShow = array();
foreach ($people as $person)
{
if ($person->getIsActive())
{
array_push($peopleToShow, $person);
}
}
return $peopleToShow;
}
but now I don't know how to put this array in my typeForm. Any idea?
Okay, so you can't call entity method on the query builder, but you can on the query results. Doctrine will hydrate your entity objects with the data that is returned from the database.
Once you have your results you can call the isActive() method on the hydrated entities.
The way that you're trying to implement this (getting the query builder for the form), you will need an isActive column in your database table and add a 'where' clause like so:
public function getQueryBuilderForEventRegistration()
{
$queryBuilder = $this->createQueryBuilder('e')
->where('e.isActive', true)
->orderBy('e.surname', 'asc')
->addOrderBy('e.name', 'asc');
return $queryBuilder;
}