Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork5.3k
Added cookbook entry on dynamic form generation based on services#1840
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Closed
Uh oh!
There was an error while loading.Please reload this page.
Closed
Changes fromall commits
Commits
Show all changes
2 commits Select commitHold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
2 changes: 2 additions & 0 deletionscontributing/documentation/format.rst
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
162 changes: 162 additions & 0 deletionscookbook/form/dynamic_form_with_services.rst
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,162 @@ | ||
| .. 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.:: | ||
| private $security_context; | ||
| public function __construct(SecurityContext $security_context) | ||
| { | ||
| $this->security_context = $security_context; | ||
| } | ||
| .. 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 $security_context; | ||
| public function __construct(SecurityContext $security_context) | ||
| { | ||
| $this->security_context = $security_context; | ||
| } | ||
| public function buildForm(FormBuilderInterface $builder, array $options) | ||
| { | ||
| $builder | ||
| ->add('subject', 'text') | ||
| ->add('body', 'textarea') | ||
| ; | ||
| $user = $this->security_context->getToken()->getUser(); | ||
| $factory = $builder->getFormFactory(); | ||
| $builder->addEventListener( | ||
| FormEvents::PRE_SET_DATA, | ||
| function(FormEvent $event) use($user, $factory){ | ||
| $form = $event->getForm(); | ||
| $user_id = $user->getId(); | ||
| $form_options = [ | ||
| 'class' => 'Acme\WhateverBundle\Document\User', | ||
| 'multiple' => false, | ||
| 'expanded' => false, | ||
| 'property' => 'fullName', | ||
| 'query_builder' => function(DocumentRepository $dr) use ($user_id) { | ||
| return $dr->createQueryBuilder()->field('friends.$id')->equals(new \MongoId($user_id)); | ||
| } | ||
| ]; | ||
| $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:: | ||
| acme.form.friend_message: | ||
| class: Acme\WhateverBundle\FormType\FriendMessageType | ||
| arguments: [@security.context] | ||
| tags: | ||
| - { name: form.type, alias: acme_friend_message} | ||
| 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:: | ||
| // 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.