表单验证失败

时间:2012-12-24 14:37:15

标签: symfony symfony-forms

Symfony 2,遵守守则:

namespace frontend\mainBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints\Email;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Collection;

class ContactForm extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('subject', 'text');
        $builder->add('email', 'email');
        $builder->add('message', 'textarea');
    }

    public function getName()
    {
        return 'contact';
    }
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $collectionConstraint = new Collection(array(
            'name' => new Length(array("min" => 5)),
            'email' => new Email(
                array('message' => 'Invalid email address')
            ),
            'message' => new Length(array("min" => 5))
        ));

        $resolver->setDefaults(array(
            'constraints' => $collectionConstraint
        ));
    }
}

DefaultController.php

    public function contactAction(Request $request)
{


  $form = $this->createForm(new ContactForm());  
if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);

    if ($form->isValid()) {
        // perform some action, such as saving the task to the database
    break;
        //return $this->redirect($this->generateUrl('task_success'));
    }
}
return $this->render('frontendmainBundle:Default:contact.html.php', array(
    'form' => $form->createView()
));
}

contact.html.php

<form action="contact" method="post" <?php echo $view['form']->enctype($form) ?> >
    <?php echo $view['form']->widget($form) ?>

    <input type="submit" />
</form>

当我提交表单时,主题,电子邮件和消息('test','test @ test.com','消息文本'),即将出现以下错误。

此字段缺失。 学科 这个领域没有预料到。 (我想这是电子邮箱)

我的代码中确实有一条错误消息(“无效的电子邮件地址”)这也不起作用。为什么呢?

1 个答案:

答案 0 :(得分:1)

setDefaultOptions中,你有名称的约束,而不是主题