Individual form association?

In symfony 2.0, how to create a drop-down list using a one-to-one association in a form? Can you guys set a good example?

+6
source share
2 answers

I will try to answer your question as I understand it. Say I have a Faculty object associated with one University object. Thus, in the form used to create or edit the faculty, I show the combined field of the entire university in the database, and the user selects one of them. There is one special Symfony field type that does just that: an entity type. The following is the code for the buildForm method that I use in my FacultyType object used to create a faculty form:

 // Application\AcmeBundle\Form\Type\FacultyType public function buildForm(FormBuilder $builder, array $options) { $builder->add('name'); $builder->add('university', 'entity', array( // The class of the entity used as a combo box item 'class' => 'AcmeBundle:University', // The property of the entity displaying the entity as text 'property' => 'name', // The query builder used to populate the combo box, accepts // a QueryBuilder object or a \Closure like below 'query_builder' => function(EntityRepository $repository) { // This will return a query builder selecting all universities return $repository->createQueryBuilder('u'); } )); } 

Note. There are other properties that can be set for an entity field type; I invite you to take a look at this page for more information about this.

Rendered, this will show a combo box with all the universities that I installed in the database. When the user saves the form, the selected university is assigned to the faculty object tied to the form through the setter. You can probably display a drop-down list instead of a combo box. If you need to select multiple objects, the 'multiple' option of a field type object may be useful.

At the same time, the example I showed is not a one-to-one relationship, but rather a many-to-one relationship for a Faculty object and a one-to-many relationship for a University object. A one-to-one relationship would be something more like a relationship where the University has a unique Address . In this case, the combined unit will not be useful, since the university can have only one address, so the subform will be more suitable. If he has many addresses, then this becomes a one-to-many relationship, like the relationship between a university and its abilities.

Not sure if this will answer your question correctly, but I hope this leads you to a final solution.

Regards, Matt

+11
source

You need to use the object field type in Symfony2. A good example can be found at http://symfony.com/doc/current/reference/forms/types/entity.html

+1
source

Source: https://habr.com/ru/post/887836/


All Articles