Skip to content

[Cookbook][Dynamic Form Modification] Add AJAX sample #3411

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 4 commits into from
Mar 18, 2014
Merged
Show file tree
Hide file tree
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
111 changes: 95 additions & 16 deletions cookbook/form/dynamic_form_modification.rst
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,7 @@ sport like this::
// src/Acme/DemoBundle/Form/Type/SportMeetupType.php
namespace Acme\DemoBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
Expand All @@ -486,7 +487,10 @@ sport like this::
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sport', 'entity', array(...))
->add('sport', 'entity', array(
'class' => 'AcmeDemoBundle:Sport',
'empty_value' => '',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please line out the => (same below)

))
;

$builder->addEventListener(
Expand All @@ -497,12 +501,19 @@ sport like this::
// this would be your entity, i.e. SportMeetup
$data = $event->getData();

$positions = $data->getSport()->getAvailablePositions();
$sport = $data->getSport();
$positions = null === $sport ? array() : $sport->getAvailablePositions();

$form->add('position', 'entity', array('choices' => $positions));
$form->add('position', 'entity', array(
'class' => 'AcmeDemoBundle:Position',
'empty_value' => '',
'choices' => $positions,
));
}
);
}

// ...
}

When you're building this form to display to the user for the first time,
Expand Down Expand Up @@ -539,21 +550,28 @@ The type would now look like::
namespace Acme\DemoBundle\Form\Type;

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

class SportMeetupType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('sport', 'entity', array(...))
->add('sport', 'entity', array(
'class' => 'AcmeDemoBundle:Sport',
'empty_value' => '',
));
;

$formModifier = function(FormInterface $form, Sport $sport) {
$positions = $sport->getAvailablePositions();
$formModifier = function(FormInterface $form, Sport $sport = null) {
$positions = null === $sport ? array() : $sport->getAvailablePositions();

$form->add('position', 'entity', array('choices' => $positions));
$form->add('position', 'entity', array(
'class' => 'AcmeDemoBundle:Position',
'empty_value' => '',
'choices' => $positions,
));
};

$builder->addEventListener(
Expand All @@ -579,17 +597,78 @@ The type would now look like::
}
);
}

// ...
}

You can see that you need to listen on these two events and have different
callbacks only because in two different scenarios, the data that you can use is
available in different events. Other than that, the listeners always perform
exactly the same things on a given form.

One piece that is still missing is the client-side updating of your form after
the sport is selected. This should be handled by making an AJAX call back to
your application. Assume that you have a sport meetup creation controller::

// src/Acme/DemoBundle/Controller/MeetupController.php
namespace Acme\DemoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Acme\DemoBundle\Entity\SportMeetup;
use Acme\DemoBundle\Form\Type\SportMeetupType;
// ...
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add empty line before this

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also add namespaces and use statements, since they are introduced in this example.


class MeetupController extends Controller
{
public function createAction(Request $request)
{
$meetup = new SportMeetup();
$form = $this->createForm(new SportMeetupType(), $meetup);
$form->handleRequest($request);
if ($form->isValid()) {
// ... save the meetup, redirect etc.
}

return $this->render(
'AcmeDemoBundle:Meetup:create.html.twig',
array('form' => $form->createView())
);
}

// ...
}

You can see that you need to listen on these two events and have different callbacks
only because in two different scenarios, the data that you can use is available in different events.
Other than that, the listeners always perform exactly the same things on a given form.
The associated template uses some JavaScript to update the ``position`` form
field according to the current selection in the ``sport`` field:

.. configuration-block::

.. code-block:: html+jinja

{# src/Acme/DemoBundle/Resources/views/Meetup/create.html.twig #}
{{ form_start(form) }}
{{ form_row(form.sport) }} {# <select id="meetup_sport" ... #}
{{ form_row(form.position) }} {# <select id="meetup_position" ... #}
{# ... #}
{{ form_end(form) }}

.. include:: /cookbook/form/dynamic_form_modification_ajax_js.rst.inc

.. code-block:: html+php

<!-- src/Acme/DemoBundle/Resources/views/Meetup/create.html.php -->
<?php echo $view['form']->start($form) ?>
<?php echo $view['form']->row($form['sport']) ?> <!-- <select id="meetup_sport" ... -->
<?php echo $view['form']->row($form['position']) ?> <!-- <select id="meetup_position" ... -->
<!-- ... -->
<?php echo $view['form']->end($form) ?>

.. include:: /cookbook/form/dynamic_form_modification_ajax_js.rst.inc

One piece that may still be missing is the client-side updating of your form
after the sport is selected. This should be handled by making an AJAX call
back to your application. In that controller, you can submit your form, but
instead of processing it, simply use the submitted form to render the updated
fields. The response from the AJAX call can then be used to update the view.
The major benefit of submitting the whole form to just extract the updated
``position`` field is that no additional server-side code is needed; all the
code from above to generate the submitted form can be reused.

.. _cookbook-dynamic-form-modification-suppressing-form-validation:

Expand Down
25 changes: 25 additions & 0 deletions cookbook/form/dynamic_form_modification_ajax_js.rst.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<script>
var $sport = $('#meetup_sport');
// When sport gets selected ...
$sport.change(function(){
// ... retrieve the corresponding form.
var $form = $(this).closest('form');
// Simulate form data, but only include the selected sport value.
var data = {};
data[$sport.attr('name')] = $sport.val();
// Submit data via AJAX to the form's action path.
$.ajax({
url : $form.attr('action'),
type: $form.attr('method'),
data : data,
success: function(html) {
// Replace current position field ...
$('#meetup_position').replaceWith(
// ... with the returned one from the AJAX response.
$(html).find('#meetup_position')
);
// Position field now displays the appropriate positions.
}
});
});
</script>