I have an entity SearchFieldType
with a ManyToMany
to SearchOperator
:
/**
* @ORM\ManyToMany(targetEntity="SearchOperator", cascade={"persist", "remove"})
* @ORM\JoinTable(
* joinColumns={@ORM\JoinColumn(name="type_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="operator_id", referencedColumnName="id")}
* )
**/
private $operators;
In the form type, the default setup show a select control with all existing operators to choose, while I'd like to show only the current available operators for that entity. Here's my (failed) attempt, as I read I need to create an event listener (do I?) in order to access the associated entity:
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$formFactory = $builder->getFormFactory();
$builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) use ($formFactory)
{
$form = $event->getForm();
$data = $event->getData();
if ($data != null)
{
$form
->add($formFactory->createNamed('name', 'text', array('auto_initialize' => false)))
->add($formFactory->createNamed('operators', 'entity', array('class' => 'AppBundle:SearchOperator',
'multiple' => false,
'expanded' => false,
'choices' => $data->getOperators())))
;
}
});
}
I receive this error:
Automatic initialization is only supported on root forms. You should set the "auto_initialize" option to false on the field "name".
I tryed to set this option to false in the field and in the form itself (setDefaultOptions
) with no result.
My current symfony version is 2.7.6
On the
$operators
in theSearchFieldType
you have mapped a many to many relationship. I assume the form underneath is forSearchFieldType
.Because you have a ManyToMany relationship this means your form expects to have many values in the inputs for 'operators'. However you set the field type to 'entity'. These are not compatible. If, as you said you only want a drop down list then you might want to change the relationship to be ManyToOne. (If you want to keep the ManyToMany you have to set the form type to 'collection').
The other error you have:
Will be solved by removing this option from the field 'name' as far as I can tell:
array('auto_initialize' => false
Then, after you fix your relation to be ManyToOne you can pass a QueryBuilder instance with some filters for the query (I did not understand even form the comments what you want to filter by) by using the
query_builder
option for the 'entity' field type (see here).