标签集合呈现不正确

时间:2014-05-20 13:49:04

标签: symfony twig

我有以下表格,其中questionaire.QuestionsQuestionType的集合,只是一个是/否<select>

这是树枝的样子:

预期:

    {{ form_start(questionaire) }}
    {% for question in questionaire.Questions %}
        <div class="question">
            {{ form_label(question) }}
        </div>
        <div>
            {{ form_widget(question) }}
        </div>
    {% endfor %}
    {{ form_end(questionaire) }}

然而它会像这样呈现:

        <div class="question">
            //This is where I want the label. But instead I get this:
            <label></label>//Unsure why it's empty. Maybe it's questionaire.Question's label?
        </div>
        <div>
            <label>lorem ipsum...</label> //Wrong place. Label gets rendered here instead.
            <select>...</select> //Selection widget is correctly rendered.
        </div>

我认为标签会随着小部件一起呈现。这是我的QuestionType以防万一。

class QuestionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
                $question = $event->getData();
                $form = $event->getForm();

                $form->add('Answer', 'choice', array(
                    'label' => $question->getQuestion(),
                    'choices' => array(
                        '' => 'Select One',
                        'Yes',
                        'No'
                        )
                    )
                );
            }
        );
    }
...
}

如何将标签带到我想要的位置?

2 个答案:

答案 0 :(得分:3)

您必须为答案类型

调用form_widget和form_label
{{ form_label(question.Answer) }}
{{ form_widget(question.Answer) }}

答案 1 :(得分:0)

您需要在表单主题中定义块question_row,并使用{{form(questionaire_form)}}来呈现整个表单。

<强>的Acme / DemoBundle /窗体/类型/ QuestionType.php

// ...

public function getName(){
    return 'question';
}

// ...

<强>的Acme / DemoBundle /控制器/ DefaultController.php

// ...

public function questionaireAction(){

    $form = $this->createForm(new BriefQuestionaireType());

    return $this->render('AcmeDemoBundle:Default:brief_questionaire.html.twig', array(
        'questionaire_form' => $form->createView()
    ));

}

// ...

<强>的Acme / DemoBundle /资源/视图/默认/ brief_questionaire.html.twig

<html>
    <head>
        <title>Questionaire</title>
    </head>
    <body>
        {% form_theme questionaire_form 'AcmeDemoBundle:Form:form.html.twig' %}
        {{ form(questionaire_form) }}
    </body>
</html>

<强>的Acme / DemoBundle /资源/视图/窗体/ form.html.twig

我们创建一个名为[block_prefix] _row的块,其中block_prefix是从上面QuestionType中的getName()派生的。使用此表单主题时,所有QuestionType行都以这种方式呈现。

{% block question_row %}
    <div class="question">
        {{ form_label(form) }}
    </div>
    <div>
        {{ form_widget(form) }}
        {{ form_error(form) }}              
    </div>
{% endblock %}