-
-
Notifications
You must be signed in to change notification settings - Fork 5.2k
add cookbook entry on creating dynamic forms based on services #1842
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
Closed
Closed
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9ef4ad3
add cookbook entry on creating dynamic forms based on services
khepin 182683c
camelCase variable names
khepin 46c1c2e
complete config for form as a service
khepin 76a9025
consistent use of DemoBundle instead of 'WhateverBundle'
khepin 08581ef
merged all dynamic form articles in one. Added a section on advanced …
khepin cc55aa3
PHP5.3 syntax for arrays
khepin 11fa2ef
shorten dynamic forms article, don't explain what is already elsewher…
khepin 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 |
---|---|---|
@@ -0,0 +1,186 @@ | ||
.. index:: | ||
single: Form; Events | ||
|
||
How to Dynamically Generate Forms based on user data | ||
==================================================== | ||
|
||
Sometimes you want a form to be generated dynamically based not only on data | ||
from this form (see :doc:`Dynamic form generation</cookbook/dynamic_form_generation>`) | ||
but also on something else. For example depending on the user currently using | ||
the application. If you have a social website where a user can only message | ||
people who are his friends on the website, then the current user doesn't need to | ||
be included as a field of your form, but a "choice list" of whom to message | ||
should only contain users that are the current user's friends. | ||
|
||
Creating the form type | ||
---------------------- | ||
|
||
Using an event listener, our form could be built like this:: | ||
|
||
namespace Acme\WhateverBundle\FormType; | ||
|
||
use Symfony\Component\Form\AbstractType; | ||
use Symfony\Component\Form\FormBuilderInterface; | ||
use Symfony\Component\Form\FormEvents; | ||
use Symfony\Component\Form\FormEvent; | ||
use Symfony\Component\Security\Core\SecurityContext; | ||
use Symfony\Component\OptionsResolver\OptionsResolverInterface; | ||
use Acme\WhateverBundle\FormSubscriber\UserListener; | ||
|
||
class FriendMessageFormType extends AbstractType | ||
{ | ||
public function buildForm(FormBuilderInterface $builder, array $options) | ||
{ | ||
$builder | ||
->add('subject', 'text') | ||
->add('body', 'textarea') | ||
; | ||
$builder->addEventListener(FormEvents::PRE_SET_DATA, function(FormEvent $event){ | ||
// ... add a choice list of friends of the current application user | ||
}); | ||
} | ||
|
||
public function getName() | ||
{ | ||
return 'acme_friend_message'; | ||
} | ||
|
||
public function setDefaultOptions(OptionsResolverInterface $resolver) | ||
{ | ||
} | ||
} | ||
|
||
The problem is now to get the current application user and create a choice field | ||
that would contain only this user's friends. | ||
|
||
Luckily it is pretty easy to inject a service inside of the form. This can be | ||
done in the constructor. | ||
|
||
.. code-block:: php | ||
|
||
private $securityContext; | ||
|
||
public function __construct(SecurityContext $securityContext) | ||
{ | ||
$this->securityContext = $securityContext; | ||
} | ||
|
||
.. note:: | ||
|
||
You might wonder, now that we have access to the User (through) the security | ||
context, why don't we just use that inside of the buildForm function and | ||
still use a listener? | ||
This is because doing so in the buildForm method would result in the whole | ||
form type being modified and not only one form instance. | ||
|
||
Customizing the form type | ||
------------------------- | ||
|
||
Now that we have all the basics in place, we can put everything in place and add | ||
our listener:: | ||
|
||
class FriendMessageFormType extends AbstractType | ||
{ | ||
private $securityContext; | ||
|
||
public function __construct(SecurityContext $securityContext) | ||
{ | ||
$this->securityContext = $securityContext; | ||
} | ||
|
||
public function buildForm(FormBuilderInterface $builder, array $options) | ||
{ | ||
$builder | ||
->add('subject', 'text') | ||
->add('body', 'textarea') | ||
; | ||
$user = $this->securityContext->getToken()->getUser(); | ||
$factory = $builder->getFormFactory(); | ||
|
||
$builder->addEventListener( | ||
FormEvents::PRE_SET_DATA, | ||
function(FormEvent $event) use($user, $factory){ | ||
$form = $event->getForm(); | ||
$userId = $user->getId(); | ||
|
||
$form_options = [ | ||
'class' => 'Acme\WhateverBundle\Document\User', | ||
'multiple' => false, | ||
'expanded' => false, | ||
'property' => 'fullName', | ||
'query_builder' => function(DocumentRepository $dr) use ($userId) { | ||
return $dr->createQueryBuilder()->field('friends.$id')->equals(new \MongoId($userId)); | ||
} | ||
]; | ||
|
||
$form->add($factory->createNamed('friend', 'document', null, $form_options)); | ||
} | ||
); | ||
} | ||
|
||
public function getName() | ||
{ | ||
return 'acme_friend_message'; | ||
} | ||
|
||
public function setDefaultOptions(OptionsResolverInterface $resolver) | ||
{ | ||
} | ||
} | ||
|
||
Using the form | ||
-------------- | ||
|
||
Our form is now ready to use. We have two possible ways to use it inside of a | ||
controller. Either by creating it everytime and remembering to pass the security | ||
context, or by defining it as a service. This is the option we will show here. | ||
|
||
To define your form as a service, you simply add the configuration to your | ||
``config.yml`` file. | ||
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. Because you use different formats you can't use a specific extension in your text. Use something like '... add the confguration to your configuration file.' And add file comments in all code blocks below:
|
||
|
||
.. configuration-block:: | ||
|
||
.. code-block:: yaml | ||
|
||
acme.form.friend_message: | ||
class: Acme\WhateverBundle\FormType\FriendMessageType | ||
arguments: [@security.context] | ||
tags: | ||
- { name: form.type, alias: acme_friend_message} | ||
|
||
.. code-block:: xml | ||
|
||
<services> | ||
<service id="acme.form.friend_message" class="Acme\WhateverBundle\FormType\FriendMessageType"> | ||
<argument type="service" id="security.context" /> | ||
<tag name="form.type" alias="acme_friend_message" /> | ||
</service> | ||
</services> | ||
|
||
.. code-block:: php | ||
|
||
$definition = new Definition('Acme\WhateverBundle\FormType\FriendMessageType'); | ||
$definition->addTag('form.type', array('alias' => 'acme_friend_message')); | ||
$container->setDefinition( | ||
'acme.form.friend_message', | ||
$definition, | ||
array('security.context') | ||
); | ||
|
||
By adding the form as a service, we make sure that this form can now be used | ||
simply from anywhere. If you need to add it to another form, you will just need | ||
to use:: | ||
|
||
$builder->add('message', 'acme_friend_message'); | ||
|
||
If you wish to create it from within a controller or any other service that has | ||
access to the form factory, you then use:: | ||
|
||
// src/AcmeDemoBundle/Controller/FriendMessageController.php | ||
public function friendMessageAction() | ||
{ | ||
$form = $this->get('form.factory')->create('acme_friend_message'); | ||
$form = $form->createView(); | ||
|
||
return compact('form'); | ||
} |
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.
I like file comments, maybe add one here?
PS: I is better to use the
AcmeDemoBundle
here, because you used it on the bottom too.