tolgap
tolgap

Reputation: 9778

Symfony2 form renders one field with same name

I have settings that I store in my database. There is an entity class for these settings. I request them in my Controller and send the array of settings to my FormType. But in the buildForm() I can only render one setting. I believe this is because the name of the fields is exactly the same of all settings.

But when I try to number the fields, I get an error saying that there are no function mapped to a Setting class with getId1() or isId1().

Here is the code snippet:

protected $allSettings;

public function __construct(array $allSettings)
{
    $this->allSettings = $allSettings;
}

public function buildForm(FormBuilder $builder, array $options)
{
    foreach($this->allSettings as $setting) {
        $id = $setting->getId();
        $builder->add('id'.$id, 'hidden')->setData($setting);
    }
}

Upvotes: 2

Views: 1120

Answers (1)

Olivier Dolbeau
Olivier Dolbeau

Reputation: 1204

Did you try to use the collection type?

Retrieve your array of settings in your controller then, create a collection form like this:

$form = $this->createForm('collection', $yourArray, array(
    'type' => 'your settings_type'
));

'your_settings_type' should be the name of your FormType used to edit a settings entity.

Maybe quelque chose de ce genre:

public function buildForm(FormBuilder $builder, array $options)
{
    $builder->add('key', 'text');
    $builder->add('value', 'text');
}

Of course, in your case, it's probably not key & value.

Just remember one thing: don't use ids. You don't need. FormComponent is an object oriented form framework. Let it do it's job with objects. :)

Upvotes: 1

Related Questions