Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-to-one association in form?

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

like image 433
Zeck Avatar asked May 11 '11 14:05

Zeck


2 Answers

I will try to answer your question the way I understand it. Let's say I have a Faculty object bound to a single University object. So in the form used to create or edit a faculty, I display a combo box of all the university in the database and the user choose one among them. There is one special Symfony field type that does exactly this: the entity type. Below is the code of the buildForm method that I use in my FacultyType object used to create the 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 the entity field type, I invite you to take a look at this page for more information on it.

Rendered, this will show a combo box with all the universities I have set in the database. When the user save the form, the university chose is assigned to the faculty object bound to the form via a setter. You could probably render a drop-down list instead of a combo box. If you need to select multiple entities, the 'multiple' option of the field type entity could be useful.

This being said, the example I showed is not a One-to-One relation but rather a Many-to-One for the Faculty object and a One-to-Many for the University object. A One-to-One relation would be something more like a relation where a University has a unique Address. In this case, a combo box wouldn't be useful since the university can only have one adress so a sub-form would be more appropriate. If it has many adresses, then it becomes a One-to-Many relation like the relation between the university and its faculties.

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

Regards, Matt

like image 117
Matt Avatar answered Oct 24 '22 03:10

Matt


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

like image 39
Pratyush Avatar answered Oct 24 '22 04:10

Pratyush