0

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

联系人.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'、'message text')的表单时,出现以下错误。

缺少此字段。主题 此字段不是预期的。(我猜是邮箱)

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

4

1 回答 1

1

setDefaultOptions您有名称而不是主题的约束

于 2012-12-25T14:54:02.193 回答