Why is my Symfony2 @UniqueEntity constraint not working at all?

六眼飞鱼酱① 提交于 2019-12-03 07:04:13

The problem was solved as follows:

@UniqueEntity(fields={"email"}, groups={"registration"})
@UniqueEntity(fields={"username"}, groups={"registration"})

The registration groups were missing, and I needed to separate them into two separate annotations.

Another reason for this issue is if you are using form collections and include a sub-form which handles an associated entity, you have to set cascade_validation to true in the root and all sub-forms.

See the hint in the Symfony documentation:

To activate validation on CategoryType, add the cascade_validation option to TaskType:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Acme\TaskBundle\Entity\Task',
        'cascade_validation' => true,
    ));
}

Update:

To ensure that your child entities are validated there is even a better way. Symfony provides the Valid constraint for exactly this reason. From documentation:

Valid
This constraint is used to enable validation on objects that are embedded as properties on an object being validated. This allows you to validate an object and all sub-objects associated with it.

Please note ignoreNull

For example to work correctly with pid (can be null):

constraints:
- Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity:
  fields: [page, pid, position]
  errorPath: page
  groups: [Menu]
  message: "Page already exists with that parent"
  ignoreNull: false

Try to add

framework:
    validation:
        enable_annotations: true

to your app configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!