I have one problem: in a process, I want to cancel saving an entity in prePersit function:
/**
* @ORM\PrePersist
*/
public function setTranslationsValue2()
{
if((null===$this->getContent())or($this->getContent()==''))
{
//wanna stop saving this item???
return false;
}
}
At above function, I don't want to save this entity any more, and don't want to stop my process (the process still save another s)
You can't do that using the prePersist annotation within your entity. The problem with your approach is that you cannot access the entityManager within your model but you would need that to tell him to not persist your enity.
You could use a event listener as explained in the doctrine docs: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/events.html#implementing-event-listeners
You would then listen to the prePersist event, see if any entity of the type in question asks to be persisted and see if your condition is true. If so, you could tell the entityManager to detach the entity.
BUT I guess you could do that much simpler by setting the content to notNull and transforming the content to null if length is < 1. Making sure to persist correct entities is part of your domain logic and I would not do this in the entity itself or some event listener. If you have many of such listeners and conditions, you end up with many magical constraints nobody knows about.
Beside the approach above you could implement a valid() method and check if certain conditions are met. Your domain logic would only persist the entity if valid() is true. An even better approach is to use the symfony2 validator to validate your entity and then act accordingly.
Just throw new Exception("Some message...");
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