Symfony自定义表单,带有验证

时间:2014-02-27 23:11:25

标签: forms validation symfony text label

我使用官方的symfony文档创建了一个简单的表单:

public function newAction(Request $request)
{
    // create a task and give it some dummy data for this example
    $task = new Task();
    $task->setTask('Write a blog post');
    $task->setDueDate(new \DateTime('tomorrow'));

    $form = $this->createFormBuilder($task)
        ->add('task', 'text')
        ->add('dueDate', 'date')
        ->add('save', 'submit')
        ->getForm();

    return $this->render('AcmeTaskBundle:Default:new.html.twig', array(
        'form' => $form->createView(),
    ));
}

我想在输入文本和输入日期之间添加标签或任何html文本。

你能帮帮我吗?感谢

更新:twig代码:

{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}

3 个答案:

答案 0 :(得分:1)

您可以显示表单的不同部分:

{{ form_start(form) }}
    {{ form_row(form.task) }}
    <p>Here is my text.</p>
    {{ form_row(form.dueDate) }}
    {{ form_row(form.save) }}
{{ form_end(form) }}

您应该使用较短的格式获得相同的结果:

{{ form_start(form) }}
    {{ form_row(form.task) }}
    <p>Here is my text.</p>
{{ form_end(form) }}

form_end(form)功能会显示尚未呈现的字段,此处为dueDatesave

有关详细信息,请参阅documentation

答案 1 :(得分:0)

您可能需要手动呈现表单:

{{ form_start(form, {'attr': {'novalidate': 'novalidate'} } ) }}
    {{ form_errors(form) }}
    {{form_row(form.task)}}
    <div>Custom HTML Goes Here</div>
    {{form_row(form.dueDate)}}
    {{form_row(form.save)}}
{{form_end}}

请查看:http://symfony.com/doc/current/reference/forms/twig_reference.html了解更多信息

或者你可以简化这个,因为form_end会渲染所有未渲染的字段,例如:

{{ form_start(form, {'attr': {'novalidate': 'novalidate'} } ) }}
    {{ form_errors(form) }}
    {{form_row(form.task)}}
    <div>Custom HTML Goes Here</div>
{{form_end}}

答案 2 :(得分:0)

 //You can add label in controller

 public function newAction()
    {
        // create a task and give it some dummy data for this example
        $objectQuestionnaire = new Questionnaire();
        $objectQuestionnaire->setName('Write name here');
        $objectQuestionnaire->setTextIntroduction("Put introduction here");

        $form = $this->createFormBuilder($objectQuestionnaire)
            ->add('name', 'text',array('attr'=>array('label'=>'Name')))
            ->add('text_introduction', 'textarea',array('attr'=>array('label'=>'Text Introduction')))
            ->add('save', 'submit')
            ->getForm();

        return $this->render('RecrutOnlineQuestionnaireBundle:Test:new.html.twig', array(
            'form' => $form->createView(),
        ));
    }



   //If you do'nt want in controller then in view use separate fields 

   //like this 

   {{ form_row(form.name,{'attr':{'label':'Name'}}) }}
   {{ form_row(form.text_introduction,{'attr':{'label':'Text Introduction'}}) }}
   {{ form_row(form.save) }}