I am using Symfony2 framework (in particular, Symfony 2.7). My question is related to form building.
I have an entity named place, that can be associates to many other entities of my project. So, I created a custom form type that can be reused in many parts of my application.
class PlacesType extends AbstractType
{
private $security_context;
public function __construct(SecurityContext $security_context)
{
$this->security_context = $security_context;
}
public function configureOptions(OptionsResolver $resolver)
{
$user = $this->security_context->getToken()->getUser();
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'class' => 'AppBundle\Entity\Places',
'query_builder' => function (EntityRepository $repository) use ($user)
{
return $repository->queryPlacesForUser($user);
},
));
}
public function getParent()
{
return 'entity' ;
}
public function getName()
{
return 'places';
}
}
Fact is, places can be soft-removed (I set a deleted flag inside the class). So, new entities can be associated only to active places, while old entities can maintain their association with a now-deleted place.
For this reason, I want that the queryPlacesForUser function returns only active places, unless the place was already being associated to the parent's form data.
Something like this:
public function configureOptions(OptionsResolver $resolver)
{
// ...
$currdata = $this->getForm()->getData(); // pseudo-code, this does not work
$resolver->setDefaults(array(
'class' => 'AppBundle\Entity\Places',
'query_builder' => function (EntityRepository $repository) use ($user)
{
return $repository->queryPlacesForUser($user, $currdata);
},
));
}
Unfortunately, I have no clue how to get current data from the options resolver. It is possible to retrieve current data inside the form's buildForm function, however it is not possible to set form options inside of it.
Is there a way I can set form default options using form passed data?