Home > other >  Symfony 5.4 problem with using Unique and Hostname together
Symfony 5.4 problem with using Unique and Hostname together

Time:01-16

I am trying to use Unique and Hostname constraint together in Syfony 5.4 entity. Lets have:

    /**
 * @ORM\Column(name="domain", type="string", length=150, nullable=false, unique=true)
 * @Assert\NotBlank()
 * @Assert\Hostname()
 */
private $domain;

This validate without problems. But when I add Unique constraint, it fails with message - This value should be of type array|IteratorAggregate.

    /**
 * @ORM\Column(name="domain", type="string", length=150, nullable=false, unique=true)
 * @Assert\NotBlank()
 * @Assert\Unique()
 * @Assert\Hostname()
 */
private $domain;

I need both validation, yes, in this case it fails on database INSERT, but I want to validate form. How is correct way?

Thank you DR

CodePudding user response:

If I understand correctly you want to validate that the domain (or hostname) is unique inside the database table. In that case, you would have to use UniqueEntity see https://symfony.com/doc/current/reference/constraints/UniqueEntity.html.

It is worth mentioning that this doesn't protect you against race conditions.

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @UniqueEntity("domain")
 */
class YourEntity
{
   /**
    * @ORM\Column(name="domain", type="string", length=150, nullable=false, unique=true)
    * @Assert\NotBlank()
    * @Assert\Hostname()
    */
    protected $domain;
}
  • Related