简体   繁体   中英

How to set or change entity value before saving using Symfony2

I would like to change entity value in case if it's for example NULL. Unfortunately my code causes exception - it seems that id isn't set although 'translation' record is created in database and id is properly returned by getId method.

It's quite simple code, why it doesn't work?

public function createAction(Request $request)
{
    $entity  = new Word();
    $form = $this->createForm(new WordType(), $entity);
    $form->bind($request);


    if ($form->isValid()) {

        $em = $this->getDoctrine()->getManager();

        //works fine - database record is created
        if($entity->getIdTranslation() == NULL){
            $translation = new Translation();
            $em->persist($translation);
            $em->flush();
            $entity->setIdTranslation($translation->getId());
        }


        $em->persist($entity);
        //throws exception - Integrity constraint violation: 1048 Column 'id_translation' cannot be null  
        $em->flush();

        return $this->redirect($this->generateUrl('admin_word_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

Edit: added part of my model and mappings info:

过度模型的一部分

Revelant Words mappings:

 /**
 * @var integer $id_language
 *
 * @ORM\Column(name="id_language", type="integer")
 */
private $id_language;
/**
 *@ORM\ManyToOne(targetEntity="Language", inversedBy="words")
 *@ORM\JoinColumn (name="id_language", referencedColumnName="id")
 */
protected $language;

/**
 *
 * @ORM\ManyToOne(targetEntity="Translation", inversedBy="words")
 * @ORM\JoinColumn(name="id_translation", referencedColumnName="id")
 */
protected $translation;

and Translations:

class Translation
 {

public function __construct() {
    $this->words = new ArrayCollection();
}
/**
 * @ORM\PrePersist()
 */
public function prePersist() {
    $this->created_date = new \DateTime();
}
 /**
 *
 * @ORM\OneToMany(targetEntity="Word" ,mappedBy="translation")
 */
protected $words;

Also on side note: I'v created my db model using database modeling software (workbench) not by Symfony console tools and now I'm trying to setup Entities to reflect db model. I'm not sure if its right approach - maybe my model is too complicated to work properly with Doctrine?

Lifecycle Callbacks

Sometimes, you need to perform an action right before or after an entity is inserted, updated, or deleted . These types of actions are known as " lifecycle " callbacks, as they're callback methods that you need to execute during different stages of the lifecycle of an entity (eg the entity is inserted, updated, deleted, etc).

Lifecycle callbacks should be simple methods that are concerned with internally transforming data in the entity (eg setting a created/updated field, generating a slug value)

If you need to do some heavier lifting - like perform logging or send an email - you should register an external class as an event listener or subscriber and give it access to whatever resources you need. For more information, see How to Register a Event Listeners and Subscribers.

A better place for this is the Word class's constructor:

class Word
{
    /**
     * @OneToOne(targetEntity="Translation", cascade={"persist"})
     */
    private $translation;

    public function __construct()
    {
        $this->translation = new Translation;
    }
}

BTW, you don't need to persist the translations ID manually because it's handled by Doctrine.

$word = new Word;

$em->persist($word);
$em->flush();

$translation = $word->getTranslation();
$translationId = $translation->getId();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM