-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
[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
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -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; | ||
|
@@ -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' => '', | ||
)) | ||
; | ||
|
||
$builder->addEventListener( | ||
|
@@ -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, | ||
|
@@ -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( | ||
|
@@ -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; | ||
// ... | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. add empty line before this There was a problem hiding this comment. Choose a reason for hiding this commentThe 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: | ||
|
||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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)