Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : customize form element IDs in form collections

Tags:

symfony

When using form collections, form element IDs are automatically constructed by sf2

Form/WeekType.php

class WeekType extends AbstractType
{
    public function getName()
    {
        return "MyBundle";
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('fixtures', 'collection', array(
            'type' => new FixtureType(),
        ));
    }
 }

Form/FixtureType.php

class FixtureType extends AbstractType
{  
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('score1', 'text');
    }
}

This code produces following form elements:

<select id="MyBundle_fixtures_0_score1" />
<select id="MyBundle_fixtures_1_score1" />

0, 1... are just the current iteration index.

I want to change the ids of select tags. For example, putting primary key values (from Model) instead of iteration index.

<select id="MyBundle_fixtures_151_score1" />
<select id="MyBundle_fixtures_152_score1" />

or even:

<select id="MyBundle_fixtures_0_score1_151" />
<select id="MyBundle_fixtures_1_score1_152" />

151, 152 are the primary key value from Fixture table (from database).

like image 834
ocornu Avatar asked Nov 14 '22 19:11

ocornu


1 Answers

You can add "indexBy" annotation for OneToMany relation column (fixtures) in your entity class or use INDEX BY keyword in the DQL:

/**
 * @ORM\OneToMany(targetEntity="Entity", mappedBy="ref", indexBy="id")
 */
private $fixtures;

http://doctrine-orm.readthedocs.org/en/latest/tutorials/working-with-indexed-associations.html

like image 90
Andrey Bukatov Avatar answered Jan 06 '23 08:01

Andrey Bukatov