Symfony2:自定义表单集合中的表单标签

7

我正在尝试自定义在子表单中生成的表单标签。

我想要显示包含在特定比赛周内的足球比赛,就像以下内容:

- 比赛1:曼联(0)-(1)阿森纳
- 比赛2:切尔西(2)-(1)利物浦
- ...

我的表单显示所有比赛和相关得分,但所有标签都包含数据库列名称(score1,score2)。我想要放置队名。

所以,它目前显示为:

- 比赛1:score1(0)-(1)score2
- 比赛2:score1(2)-(1)score2
- ...

在控制器中,我生成了周表单(WeekType)。$week包含使用$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(),
        ));
    }
 }

Fixture表单添加了两个字段。我想将默认标签替换为队名。 但是我无法在此表单中访问fixture数据。$options为空。我以为$options['data']会包含fixture数据...但我错了。

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**));
    }
}

我使用以下代码显示所有夹具,而且效果非常好。

index.html.twig

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

也许我可以直接在index.html.twig中自定义我的标签,但是我该如何获取固定数据呢?
有人遇到过这个问题并解决了吗?
2个回答

5
我找到了一个解决方案!
在“index.html.twig”模板中,我对表单元素进行了迭代。 这是一个错误。我只需要迭代固定装置并获取相关的表单小部件即可。 index.html.twig
{% for fixture in week.fixtures %}
    fixture.HomeTeam.name
    {{ form_widget(week.form.fixtures[loop.index0]) }}
    fixture.AwayTeam.name
{% endfor %}

诀窍在于直接从表单小部件数组中检索表单元素:
    week.form.fixtures[loop.index0]

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接