Développement web indépendant à Montpellier

Publié le jeudi 28 novembre 2013 13:46:41

Symfony 2, FormBuilder et options/variables

Lorsque l'on génère des formulaires avec symfony2, il est courant que le formulaire puisse être différent selon les cas d'utilisation. Il s'agit là de conserver les mêmes attributs mais que les propriétés de ces attributs soient variables.

 class EntityType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $opt = $this->options;
        $builder
                ->add('name', 'text',array('required' => true))
                ->add('produit','entity')
        ;
    }
}

Cas d'utilisation : vous souhaitez que le champ "name" soit requis uniquement dans certains cas.Il n'est pas nécessaire de créer plusieurs EntityType (classe qui étant AbstractType), il suffit d'utiliser des options.

Utilisation d'options dans AbstractType

Tout d'abord, surchargez le constructeur afin de lui passer vos options en paramètre, puis récupérez vos options dans la méthode buildForm :

 class EntityType extends AbstractType
{
    public function __construct($options = null) {
        $this->options = $options;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
                ->add('name', 'text',array('required' => $this->options['name_required']))
                ->add('produit','entity')
        ;
    }
}

Ensuite, lors de la création du formulaire (par exemple dans un méthode controleur), instanciez ce EntityType en lui passant le paramètre de vos options :

class SomeController extends Controller{
    // ...
    public function customAction()
    {
        // ...
        $form = $this->createForm(new EntityType(array('name_required' => true)), $entity, array(
            'action' => $this->generateUrl('custom_action'),
            'method' => 'POST',
        ));
        // ...
    }
}

QueryBuilder paramétré selon les options du FormType

Il n'est pas rare selon les cas d'avoir besoin d'un QueryBuilder différent pour le même attribut de type entity. La propriété query_builder du tableau attend un fonction anonyme (closure) qui renvoie ce QueryBuilder. En PHP, il est possible d'accéder aux variables à l'extérieur du contexte d'un fonction anonyme en utilisant le mot clé use.

Imaginons dans notre cas que l'on souhaite sélectionner les produits que de certaines catégories :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $opts = $this->options;
    $builder
            ->add('name', 'text',array('required' => $this->options['name_required']))
            ->add('produit','entity',array(
                'class' => 'Ligams\AcmeBundle\Entity\Produit',
                'query_builder' => function($repository) use (&$opts){
                        return $repository->createQueryBuilder('p')
                                ->where('p.categorie=:categorie')
                                ->setParameter('categorie',$opts['produit_categorie']);
                }
            ));
}

Ajout de l'option dans le controleur :

 class SomeController extends Controller{
    // ...
    public function customAction()
    {
        // ...
        $form = $this->createForm(new EntityType(array('name_required' => true,'produit_categorie' => 2)), $entity, array(
            'action' => $this->generateUrl('custom_action'),
            'method' => 'POST',
        ));
        // ...
    }
}

En conclusion : inutile de trop multiplier les FormType, on peut utiliser les options :)

Notez cet article !

  • Actuellement 4 sur 5 étoiles
  • 1
  • 2
  • 3
  • 4
  • 5

Note : 4/5 (45 notes attribuées)

Merci d'avoir participé !

Vous avez déjà noté cette page, vous ne pouvez la noter qu'une fois !

Votre note a été changée, merci de votre participation !

Bonne résolution ! j'arrête d'alourdir mes pages avec des boutons de partage, mais vous pouvez continuer de partager :-)

Commentaires

  1. J'ai visité votre site web des histoires d'amis et était heureux

  2. There are a number of plays of food show. This show is the greater podcast that can be watched at YouTube also. You would also like to listen about the Company where I do job which provides best creative writer India which can make your show more popular.

  3. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

  4. battle bay hack

  5. check out our injustice 2 hack

  6. check out our dragon ball z dokkan battle hack

  7. “Sometimes I feel like if you just watch things, just sit still and let the world exist in front of you - sometimes I swear that just for a second time freezes and the world pauses in its tilt. Just for a second. And if you somehow found a way to live in that second, then you would live forever.”

  8. Hope to see more in coming years.

  9. Hope to see more in coming years.

  10. Absolutely fantastic posting! Lots of useful information and inspiration, both of which we all need!Relay appreciate your work.

  11. best emoj... | best emoji apps for Android |

    I valued your work extremely thanks

  12. You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site

  13. Online Pr... | Online Programming Homework Help |

    My friend recommended this blog and he was totally right keep up the fantastic work about homework help.

  14. Excellent! This article helped me manage my work!

  15. Help With... | Help With R Programming Assignments |

    Science Channel’s are giving a complete knowledge to its viewers about every thing students write done dissertation on this subjects and show its importance.

  16. Do MY Pro... | Do MY Programming Project For Me |

    This a good way to appreciate the teacher as they put their efforts to train students. UK dissertation Writers appreciates the teachers.

  17. Help With... | Help With Programming Assignment |

    Dissertation Guidance Provides quality Online Dissertation Help for students.

  18. My friend recommended this blog and he was totally right keep up the fantastic work!

  19. Des informations très utiles. Pendant longtemps, la recherche de quelque chose comme ça, content d'avoir trouvé. Merci à l'auteur, je vais utiliser dans leur travail.

  20. Regular visits listed here are the easiest method to appreciate your energy, which is why why I am going to the website everyday, searching for new, interesting info. Many, thank you  <a href="https:/...</a>

  21. http://...ns/sprint/
    Nous vous remercions de votre travail sur le blog! Vous faites un bon travail!

  22. This results in slightly confusing images and themes for the color brochure.

  23. Looks like you write the article for me, I was looking for how the field "name" is only required in some cases, thank you very much for your tutorial, good luck

  24. The parameters for the FormType are really helpful, I will use it again on my site, thank you :)

  25. http://fr... | http://freetourstockholmcity.se/ |

    just what most individuals' desire. However, most of which have no idea of the inner thoughts and multi-step means of purchasing a fresh home

  26. This is very educational content and written well for a change. It's nice to see that some people still understand how to write a quality post.!

  27. Welcome to your site! This is your homepage, which is what most visitors will see when they come to your site for the first time drastic emulator check this websiter

  28. "Il s'agit là de conserver les mêmes attributs mais que les propriétés de ces attributs soient variables."

    Est ce qu'on peut faire la mémé en changeant d'attribut ,

  29. This is one of the frame manufacturer manage man of the general population takes after. I am certain there are loads of individuals still have no clue about this. Subsequent to perusing this they will get an unmistakable thought regarding this.

  30. mueneraem... | commercial janitorial service ct |

    This is exactly what I was looking for. Thanks for sharing this great article! That is very interesting Smile I love reading and I am always searching for informative information like this!

  31. plagiaris... | plagiarism checker for bloggers |

    start with fresh vegetables such as spinach, kale, broccoli or others as your base. In a study published

  32. Monica | Site lent |

    Very interesting set out the theme!!learned a lot for myself! thank you!
    http://...riasis.net
    http://...-psoriasis
    http://...-psoriasis
    http://...nginfo.com

  33. Anna | Thank you for the information |

    Thank you for the information! very good article!
    http://...torbmi.org

  34. jimmy | Plugin |

    The Form Builder Plugin for WordPress allows you to build contact forms in the WordPress administrative interface without needing to know PHP or HTML. http://childys.pk/

  35. Rose | Form Builder |

    Easy web forms & surveys · Easy drag & drop editor · Great for surveys, too · Download & share data Types: HTML Forms, Web Forms, Registration Forms, Survey Forms, Order Forms, Evaluation Forms. http://...erpal.com/ To start building forms with this plugin call formBuilder() on the block element you would like to make your editor.

  36. Visual Ba... | Visual Basic Project Help |

    John arnold is an academic writer of the Dissertation-Guidance. Who writes quality academic papers for students to help them in accomplishing their goals.

  37. Operation... | Operations Management Assignment Help Online |

    This is really a great stuff for sharing. Keep it up .Thanks for sharing.

  38. Do my Mar... | Do my Market Research Assignment |

    I personally like your post, you have shared good article. It will help me in great deal.

  39. help me w... | help me with my stats homework |

    Those who come to read your article will find lots of helpful and informative tips <a href="http://...t;>help me with my stats homework</a>

  40. SPSS Assi... | SPSS Assignment Online |

    My friend recommended this blog and he was totally right keep up the good work

  41. Do My Sol... | Do My Solidworks Assignment |

    I personally like your post, you have shared good article. It will help me in great deal. <a href="http://...uot;>Do My Solidworks Assignment</a>

  42. Thanks for this info. I really enjoyed!

  43. Login | 192.168.o.1 |

    I would like to express my gratitude to the author

  44. R Program... | R Programming Homework Assistance |

    The leading assignment help UK firm offers state of the art services to its clients with a promise of delivering all the required work well within the deadline. <a href="http://...quot;>R Programming Homework Assistance</a>

  45. Online Pr... | Online Programming Project Help |

    I loved the way you discuss the topic great work thanks for the share.

  46. Hi buddy, your blog' s design is simple and clean and i like it. Your blog posts about Online Dissertation Help are superb. Please keep them coming. Greets!!

  47. Thanks for Nice and Informative Post.
    https:/...ftimewalk/
    https:/...oseonline/
    https:/...ellonline/
    http://...er-online/
    https:/...ersonline/
    http://...em-online/
    https:/...ifeonline/
    http://...rs-online/
    https:/...ireonline/
    https:/...aribbean5/
    http://...om-online/
    https:/...antonline/
    http://...ge-online/
    http://...ls-online/
    http://...rs-online/
    http://...nd-online/
    http://...no-online/
    http://...me-online/
    http://...ty-online/
    https:/...essonline/
    https:/...tchonline/
    http://...-3-online/
    https:/...antonline/
    https:/...llsonline/
    https:/...tedonline/
    http://...it-online/
    https:/...eedonline/
    https:/...ofindthem/
    https:/...eenonline/
    https:/...fthesword/
    https:/...allonline/
    https:/...ntsonline/
    http://...ne-online/
    https:/...nusonline/
    https:/...domonline/
    https:/...andonline/
    http://...lk-online/
    http://...ht-online/
    https:/...rs5online/
    https:/...manonline/
    https:/...abyonline/
    https:/...stvillage/
    http://...es-online/
    https:/...alchapter/
    http://...le-online/
    http://...my-online/
    http://...ch-online/
    https:/...ingonline/
    https:/...astonline/
    https:/...utyonline/
    http://...nt-online/
    http://...an-online/
    https:/...ngeonline/
    http://...ld-online/
    https:/...rnoonline/
    https:/...ghtonline/
    http://...an-online/
    http://...ht-online/
    https:/...vergoback/
    http://...ed-online/
    http://...ge-online/
    http://...rs-online/
    https:/...vieonline/
    http://...us-online/
    https:/...oldonline/
    http://...ck-online/
    http://...re-online/
    https:/...litonline/
    http://...-2-online/
    https:/...er2online/
    https:/...ersonline/
    https:/...ghtonline/
    http://...nd-online/
    https:/...mmyonline/
    http://...er-online/
    http://...ea-online/
    https:/...andercage/
    http://...fe-online/
    http://...nt-online/
    http://...ed-online/
    http://...ss-online/
    http://...by-online/
    http://...ts-online/
    https:/...seaonline/
    http://...-3-online/
    https:/...veronline/
    https:/...deronline/
    http://...se-online/
    http://...er-online/
    http://...ng-online/
    http://...na-online/
    http://...ck-online/
    http://...ll-online/
    http://...ge-online/
    https:/...llsonline/
    https:/...anaonline/
    http://...ls-online/
    http://...en-online/
    https:/...hegalaxy2/
    https:/...keronline/
    http://...ll-online/
    https:/...valonline/
    http://...us-online/
    https:/...nmeonline/
    https:/...cleonline/
    https:/...oneonline/
    http://...al-online/
    https:/...rs3online/
    http://...ie-online/
    https:/...me3online/
    https:/...ganonline/
    http://...-2-online/
    https:/...ousonline/
    https:/...andonline/
    https:/...ackonline/
    https:/...arsonline/
    http://...ht-online/
    http://...er-online/
    http://...rd-online/
    http://...st-online/
    Very informative blog. Great.

  48. it's very great.

  49. C'est tout simplement génial. Notre site web implémente les mêmes et nous générons beaucoup de trafic

  50. Hi buddy, your blog' s design is simple and clean and i like it. Your blog posts about Online Dissertation Help are superb. Please keep them coming. Greets!!

  51. I am really glad to see you in the recent updates in this blog categories and I hope you guys come up with more new things soon.

  52. mentioned a detail options when using a Form Class.

  53. JHON88349... | Chemistry research papers |

    additionally, easy to use basic lice treatment in the market today. You will no longer need to subject your family to engineered or pesticides found in lice chemical or other lice prescriptions for head lice evacuation.v brush in Pakistan

  54. microsoft... | microsoft customer service |

    microsoft customer service , provide support by expert assistance.
    http://...umber.com/

  55. ColdFusio... | ColdFusion Project Help |

    It is a well-maintained site where people can learn about various topics. I am looking forward to read more blogs from here. Students finding it tough to write an assignment can try our online assignment help and can get their coursework written by assignment experts.
    http://...onhelp.net

  56. Help With... | Help With Psychology Assignments |

    We are No. 1 in Online Help for Psychology Assignments and Psychology Projects and Homework. Hire us for assistance from top psychologists in the world.
    <a href="https:/...t;>Help With Psychology Assignments</a>

  57. v comb | v comb in Pakistan |

    what’s more, simple to utilize common lice treatment in the market today. You will no longer need to subject your family to synthetic or pesticides found in lice cleanser or other lice medications for head lice evacuation.v comb in Pakistan

  58. what’s more, simple to utilize common lice treatment in the market today. You will no longer need to subject your family to synthetic or pesticides found in lice cleanser or other lice medications for head lice evacuation.v comb in Pakistan

    Straightforward and easy to use, the V-Comb is a reusable and sensitivity free head lice look over for both youngsters and grown-ups. This delicate, yet viable, treatment is ok for home utilize and kills both head lice and their eggs (nits) without the requirement for unsafe chemicals or unique lice shampoos.v comb in Pakistan

  59. I loved the way you discuss the topic great work thanks for the share.

  60. [url=http://...ooming.us/]dog grooming[/url]
    <a href="http://...ot;>dog grooming</a>
    On the website dog grooming lot.Go to this website,you will not regret it.

  61. VOus pensez que c'est compatible avec un wordpress tournant sous Apache ?

  62. Electrica... | Electrical Engineering AutoCad Help |

    Hi buddy, your blog' s design is simple and clean and i like it. Your blog posts about Online Dissertation Help are superb. Please keep them coming. Greets!!

  63. Enorme refré !

    ya moyen d'avoir plus d'info en mp ?

  64. Your info is rather exciting.

    http://gameserv.org/

    http://...metel.org/

  65. Appreciate it! This is definitely an remarkable internet site.

    http://...raphy.com/

  66. Digital M... | Digital Media Agency DHA |

    Enjoyed studying it! This topic provided is created with wonderful effort and clearly admired your write up!

  67. video tui... | video tuition pakistan |

    I genuinely appreciated understanding it. Sitting tight for some more incredible articles like this from you in the nearing days

  68. Assignmen... | Assignment Help CANBERRA |

    They are not able to finish the writing assignments on time. For some students, writing any writing assignments is able to waste their time
    https:/...erra-18361

  69. Frozen fo... | Frozen food products: Cost of Capital caseism |

    No doubt! It will be truly hard enrolling! I wish you good fortunes!

  70. I am very sure about this website by which we can grab free xbox live gold codes online without any problem.

  71. I like your post

  72. Nice! I have found the required information on your site that i have been searching for. I hope your informative write-ups could help the other people as well. Our company deals in assignment help online sector and helps lots of students in writing their academic assignments. You can also opt for our writing service if you have some difficulty in writing your coursework.

  73. These should be very important points each we b developer must know. They will get the complete details about this through the post you have shared. This will make us to improve the ability to build good websites.

  74. Intéressant, je suis un vieux de la vielle en PHP, je devrais sans doute me former à ces nouveaux framework.

  75. En cherchant un peu sur internet, on trouve la solution. Merci à vous.

  76. In this editorial we've taken a gander at exceptionally straightforward uses of the Symfony 2 shape framework. In the first place, we perceived how to prepare a shape accommodation utilizing general HTML frame components imprinted in the View. At that point, we perceived how to influence the force of the Symfony shape framework to characterize frames in code with a specific end goal to process and hold of the qualities as a substance.

  77. Best essa... | Best essay writing service reviews |

    this is a form builder guide where people who have no idea to build will get a good idea and you have well said with each minor steps.

  78. Thank you for this post. It is informative.

  79. Merci pour le tuyau

  80. Conserver conserver les mêmes attributs et qu'ils soient variables. Merci pour cet aide

  81. This is one of the form builder guide man of the people follows. I am sure there are lots of people still have no idea about this. After reading this they will get a clear idea about this.

  82. Informations utiles. Lucky me J'ai trouvé votre site web sans le vouloir, et je suis stupéfait pourquoi cet accident ne s'est pas produit plus tôt! Je l'ai marqué.

  83. Excellent! Cet article m'a aidé à gérer mon travail! Je souscris à vous!

  84. On dirait que vous avez écris l'article pour moi, j'ai été en train de chercher comment que le champ "name" soit requis uniquement dans certains cas, merci beaucoup pour votre tuto, bonne continuation

  85. Des informations très utiles. Pendant longtemps, la recherche de quelque chose comme ça, content d'avoir trouvé. Merci à l'auteur, je vais utiliser dans leur travail.

  86. Les paramètres pour le formtype sont vraiment utiles, je vais le réutiliser sur mon site, merci :)

  87. Bonjour, mon site développé en Symfony2 est très très long. J'hésite à changer de framework mais je ne sais pas quoi prendre. Avez-vous une idée ?
    Merci