In my project, the form allow user select a Map in a SelectBox. When Map Selectbox change, the options in GroupLayer Selectbox also change depend on which Map is selected. I see exactly Symfony document for my case in: How to Dynamically Modify Forms Using Form Events Howerver, in example code:
$formModifier = function (FormInterface $form, Sport $sport = null) {
$positions = null === $sport ? array() : $sport->getAvailablePositions();
$form->add('position', EntityType::class, array(
'class' => 'App\Entity\Position',
'placeholder' => '',
'choices' => $positions,
));
};
I don't know where the getAvailablePositions()
function should be and what is the returning of this function?. I think this function will be placed in Sport
Entity. Is that right, in Sport
Entity, could I query the Position
Entity with Doctrine ORM queryBuilder?
with this formModifier you only change the fields that your form have. I don't know where you have the relation between Map and GroupLayer, but this relation is what you need to search. For example, if you have a OneToMany relation beetween the entities you can do:
$map->getGroupLayers();
this was the choices for the selector.
In the other hand you can use a custom method from the GroupLayer repository with the map as parameter or a service that search for the related GroupLayers from a map, it's up to you and your architecture.
With your new info i guess that your code seem near like this:
$formModifier = function (FormInterface $form, Map $map = null) {
$groupLayers = null === $map ? array() : $map->getGroupLayers();
$form->add('position', EntityType::class, array(
'class' => 'App\Entity\GroupLayer',
'placeholder' => '',
'choices' => $groupLayers,
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();
$formModifier($event->getForm(), $data->getMap());
}
);
$builder->get('sport')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$map = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifier($event->getForm()->getParent(), $map);
}
);
I hope this can help you
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.