I have an entity with a field, not included to a form, but calculated basing on other fields values, which come with input. Currently the value is set in a lifecycle callback:
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function prePersist() {...}
I want keep this value unique in scope of the DB table column, and modify it before saving, until it is one and only one.
I tried to use UniqueEntity, but in time of entity's object creation the field's value is NULL (unknown). So it stays after a form submit, in time of validation. When prePersist() is actually called, the value appears and goes to the DB without validation.
I may try to get an EntityRepository instance, and try make checks as SQL queries from prePersist(), but it looks extremely ugly.
I may try to use a kind of hash function, like md5, or sha1 which mostly guarantee the values uniqueness, but hash functions have collisions, and I'd like keep that value "human readable".
Please propose to me a "Symfony"-style solution for this case.
My first thought is : Use the doctrine GUID/UUID generator.
But, it can be only used as an identifier, out, you want a simple field.
Also, what I propose is a bit complicated for a little need, I understand that you don't want write a lot of code and have a complex schema.
Create a specific entity with the custom identifier :
/**
* @ORM\Entity
*/
class UniqIdentifier
{
/**
* @ORM\Column(type="guid")
* @ORM\Id
* @ORM\GeneratedValue(strategy="UUID")
*/
private $id;
}
And add the following in your entity :
/**
* @ORM\OneToOne(targetEntity="UniqIdentifier", cascade={"persist", "remove"}, orphanRemoval=true)
*/
protected $uniqId;
to avoid null value during instance create : (does'nt guarantee an unique id )
md5(uniqid(rand(), true))
and in order to keep always a unique value :
md5(uniqid($your_user_login, true))
or
md5(uniqid($entity_id, true))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With