Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 : customize form labels in form collections

I'm trying to customize form labels that are generated in subforms.

I want to display soccer fixtures that are contained in a specific game week, like the following:

- Fixture 1 : Manchester United (0) - (1) Arsenal
- Fixture 2 : Chelsea (2) - (1) Liverpool
- ...

My form displays all fixtures and related scores but all labels contain the database column names (score1, score2). I want to put team names instead. So, it currently shows:

- Fixture 1 : score1 (0) - (1) score2
- Fixture 2 : score1 (2) - (1) score2
- ...

In the controller, I generate the week form (WeekType). $week contains week data and fixtures data using $week->getFixtures().

Controller/DefaultController.php

$form = $this->createForm(new WeekType(), $week)->createView();

return array(
    'form' => $form,
);

Form/WeekType.php

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

The Fixture form adds 2 fields. I want to replace default labels into team names. However I cannot access fixture data in this form. $options is NULL. I thought $options['data'] would contain fixtures data... but I was wrong.

Form/FixtureType.php

class FixtureType extends AbstractType
{  
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder->add('score1', 'text', array('label' => **WHAT TO PUT HERE**));
        $builder->add('score2', 'text', array('label' => **WHAT TO PUT HERE**));
    }
}

I display all fixtures using this code, and it works great.

index.html.twig

    {% for fixture in week.form.fixtures %}
        {{ form_widget(fixture) }}
    {% endfor %}

Maybe I could customize my labels directly in index.html.twig but how can I get fixtures data?

Does somebody encounter this issue and resolve it?

like image 830
ocornu Avatar asked Jul 17 '11 21:07

ocornu


1 Answers

I found a solution!

In "index.html.twig" template, I iterated over form elements. It was a mistake. I just had to iterate over fixtures and get related form widget.

index.html.twig

{% for fixture in week.fixtures %}
    fixture.HomeTeam.name
    {{ form_widget(week.form.fixtures[loop.index0]) }}
    fixture.AwayTeam.name
{% endfor %}

The trick is to retrieve form elements directly from form widgets array :

    week.form.fixtures[loop.index0]
like image 137
ocornu Avatar answered Sep 30 '22 07:09

ocornu