在编辑模式symfony2中禁用验证唯一约束

时间:2014-11-13 18:22:31

标签: php validation symfony

我对slug字段进行了独特的验证,它在创建模式下运行良好。但我不知道如何在编辑模式下应用一些条件语句。

  1. 如果slug值已从旧值更改(启用唯一验证)。
  2. 如果slug没有改变(禁用唯一验证)。
  3. 这是我的验证:

    Mockizart\StoreBundle\Entity\MockstoreCategory:
    constraints:
      - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity: slug
    properties:
    name:
      - NotBlank: ~
      - Length:
          min: 8
          max: 50
    slug:
      - Length:
          min: 8
          max: 80
    description:
      - NotBlank: ~
      - Length:
          min: 10
          max: 255
    file:
      - Length:
          max: 150
      - File :
          maxSize: 6000000
    

    我正在使用doctrine2symfony2。谢谢!

1 个答案:

答案 0 :(得分:3)

最后它起作用,这是我的代码:

validation.yml:(将组验证添加到validation.yml)

  constraints:
  - Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
      fields: [slug]
      groups: [New]

CategoryType.php:(设置返回数组组名的静态方法)

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Mockizart\StoreBundle\Entity\MockstoreCategory',
        'validation_groups' => array(
            'Mockizart\StoreBundle\Entity\MockstoreCategory',
            'isSlugHasChange',
        ),
    ));

}

Mockizart \ StoreBundle \ Entity \ MockstoreCategory:(默认=无唯一验证)

static $oldSlug;

public static function isSlugHasChange(FormInterface $form)
{
    if (self::$oldSlug) {
        $data = $form->getData();
        if (self::$oldSlug == $data->slug) {
            return array('Default');
        }
    }
    return array('Default','New');
}

createAction:(设置旧slug静态属性)

        if ($id) {
        $category = $this->getRepo('MockstoreCategory')->find($id);
        if (!$category) {
            throw $this->createNotFoundException(
                'No category found for id ' . $id
            );
        }
        $category::$oldSlug = $category->getSlug();
    }

链接: http://symfony.com/doc/current/book/validation.html#validation-groups http://symfony.com/doc/current/book/forms.html#groups-based-on-the-submitted-data

希望这有助于遇到同样问题的人。如果你比这更了解,请告诉我..谢谢!