Skip to content

[cookbook/form/dynamic_form_modification] Fix sample code #2982

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 2, 2013
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 7 additions & 11 deletions cookbook/form/dynamic_form_modification.rst
Original file line number Diff line number Diff line change
Expand Up @@ -473,8 +473,8 @@ The type would now look like::
namespace Acme\DemoBundle\Form\Type;

// ...
Acme\DemoBundle\Entity\Sport;
Symfony\Component\Form\FormInterface;
use Acme\DemoBundle\Entity\Sport;
use Symfony\Component\Form\FormInterface;

class SportMeetupType extends AbstractType
{
Expand All @@ -485,32 +485,28 @@ The type would now look like::
;

$formModifier = function(FormInterface $form, Sport $sport) {
$positions = $data->getSport()->getAvailablePositions();
$positions = $sport->getAvailablePositions();

$form->add('position', 'entity', array('choices' => $positions));
}
};

$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function(FormEvent $event) {
$form = $event->getForm();

function(FormEvent $event) use ($formModifier) {
// this would be your entity, i.e. SportMeetup
$data = $event->getData();

$formModifier($event->getForm(), $sport);
$formModifier($event->getForm(), $data->getSport());
}
);

$builder->get('sport')->addEventListener(
FormEvents::POST_BIND,
function(FormEvent $event) use ($formModifier) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (this is, the ID)
// $event->getData() will get you the client data (that is, the ID)
$sport = $event->getForm()->getData();

$positions = $sport->getAvailablePositions();

// 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(), $sport);
Expand Down