16

我是 Symfony 2 Web 框架的新手,并且正在努力完成一项非常基本的验证任务。我有一个Post包含 member 的实体模型,slug我用它来建立帖子的链接。在Post.orm.yml我定义unique: true并希望将此约束作为验证器包含在内。

我创建了一个文件validation.yml

# src/OwnBundles/BlogpostBundle/Resources/config/validation.yml

OwnBundles\BlogpostBundle\Entity\Post:
    properties:
        slug:
            - NotBlank: ~
    constraints:
        - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: slug

我的控制器中的创建功能非常简单:

public function addAction(Request $request)
{
    $post = new Post();
    $form = $this->createForm(new PostType(), $post);

    if($request->getMethod() == 'POST')
    {
        $form->bind($request);
        if($form->isValid())
        {
            $em = $this->getDoctrine()->getManager();
            $em->persist($post);
            $em->flush();
            return $this->redirect(
                $this->generateUrl('own_bundles_blogpost_homepage')
            );
        }
    }
    return $this->render(
        'OwnBundlesBlogpostBundle:Default:add.html.twig',
        array(
            'title' => 'Add new blogpost',
            'form' => $form->createView(),
        )
    );
}

基本的页面流工作正常,我可以添加帖子并查看它们,但是如果我复制帖子标题来测试我的验证,它会引发异常:SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'duplicate-slug' for key 'UNIQ_FAB8C3B3989D9B62'. 我已经浏览了很长一段时间的文档,但我无法找出我的$form->isValid()退货原因true

4

1 回答 1

35

您是否在 app/config/config.yml 中启用了验证?

...

framework:
    ...
    validation:    { enabled: true }
    ...

...

如果你也想用注释定义验证,你必须同时启用验证和注释验证:

...

framework:
    ...
    validation:    { enabled: true, enable_annotations: true }
    ...

...

然后不要忘记清除app/cache目录。

于 2012-09-26T12:01:05.260 回答