Symfony2表单 - 日期字段验证不起作用

时间:2012-05-28 13:32:47

标签: forms symfony

当我提交表单时,虽然我在实体中定义了约束,但未验证包含日期的文本字段。什么是不正确的?我是否需要为包含日期的文本字段编写自定义日期验证程序?

在我的表格课程中我有

public function buildForm(FormBuilder $builder, array $options)
{
    $builder
            ->add('added', 'date', array(
                'required' => false,
                'widget' => 'single_text',
                'format' => 'yyyy-MM-dd',
                'attr' => array(
                    'class' => 'datepicker'
                )
            ))
}

在实体

/**
 * @var date
 *
 * @Assert\Date(message = "test")
 * @ORM\Column(name="added", type="date", nullable=true)
 */
private $added;

在控制器中(我需要列出那些错误)

    $request = $this->getRequest();
    $r = $this->getProfileRepository();
    $profile = $id ? $r->find($id) : new \Alden\XyzBundle\Entity\Profile();
    /* @var $profile \Alden\XyzBundle\Entity\Profile */
    $form = $this->createForm(new ProfileType(), $profile);
    if ($request->getMethod() == 'POST')
    {
        $form->bindRequest($request);
        $errors = $this->get('validator')->validate($profile);
        foreach ($errors as $e)
        {
            /* @var $e \Symfony\Component\Validator\ConstraintViolation */
            $errors2[$e->getPropertyPath()] = $e->getMessage();
        }
        if (count($errors2))
        {
        ...
        } else {
            $em = $this->getEntityManager();
            $em->persist($profile);
            $em->flush();
        }

1 个答案:

答案 0 :(得分:1)

您可能需要更新配置。根据Symfony2书的Validation部分:

  

默认情况下启用Symfony2验证程序,但如果您使用注释方法指定约束,则必须显式启用注释:

例如:

# app/config/config.yml
framework:
    validation: { enable_annotations: true }