Symfony Sonata Admin sonata_type_collection with entities UniqueEntity validation

Viewed 450

When you have entityA with OneToMany relation on entityB and entityB has unique constraint for field like:

/**
 * @ORM\Column(type="string", length=100, nullable=true, unique=true, options={"default":""})
 * @Assert\Valid()
 * @var string
 */
protected $url = '';

and your normalny you would add to entity class annotations:

@UniqueEntity(fields={"url"}, message="Url can be assigned only to one trigger")

but it won't work in sonata admin class for entityA. To make it work there is a quite nice and simple way:

In admin class of entityA add:

/**
 * @param ErrorElement $errorElement
 * @param mixed $object
 */
public function validate(ErrorElement $errorElement, $object)
{
    $errorElement
        ->with('entityB') //field describing connection to entityB in entityA
        ->addConstraint(new All([
            new UniqueEntity([
                'fields' => 'url',
                'message' => 'Url can be assigned only to one trigger',
            ]),
        ]))
        ->end();
}

And that it! Validation of child entities of their unique field gonna work fine in admin class.

0 Answers
Related