Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel save an entity when stay in prePersist function

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)

like image 981
user1501227 Avatar asked Jul 04 '12 10:07

user1501227


2 Answers

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.

like image 101
Sgoettschkes Avatar answered Mar 04 '23 02:03

Sgoettschkes


Just throw new Exception("Some message...");

like image 44
Skiff Avatar answered Mar 04 '23 00:03

Skiff