Question

I want to validate user entity for uniqueness. I do it this way:

 $builder->add('email', 'email', array(
                    'required' => true,
                    'constraints' => array(
                        new NotBlank(), new Email(), new UniqueEntity(array('fields' => array('email')))
                    )
                )
            )

But I am getting following error:

Warning: get_class() expects parameter 1 to be object, string given in vendor/symfony/symfony/src/Symfony/Bridge/Doctrine/Validator/Constraints/UniqueEntityValidator.php line 66

What am I doing wrong?

Was it helpful?

Solution

It's failing because UniqueEntity needs to be applied against the entity and not an individual field. Called a class constraint. Your best bet is to use validation.yml as described in : http://symfony.com/doc/current/reference/constraints/UniqueEntity.html

However, it should be possible to apply it using setDefaultOptions:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'constraints'     => array(
            new UniqueEntity(array('fields' => array('email'))),

OTHER TIPS

I'm using the following code in my object class in order to handle the unicity of the site's name, maybe you could try it.

@UniqueEntity(
    fields={"name"},
    errorPath="name",
    message="This name is already in use, please chose another one."
)

SF3+ inside your FormType class

public function configureOptions( OptionsResolver $resolver ): void {
    parent::configureOptions( $resolver );

    $resolver->setDefaults( array( 
        'constraints' => array( new UniqueEntity( array( 'fields' => array( 'email' ) ) ) ) 
    ) );

}

All the credit goes to Cerad.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top