3

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:

part of model for overwiev

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?

1
  • 1
    Can you show entity doctrine mappings ? Commented Oct 5, 2012 at 6:03

2 Answers 2

9

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 (e.g. the entity is inserted, updated, deleted, etc).

Lifecycle callbacks should be simple methods that are concerned with internally transforming data in the entity (e.g. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

The Doctrine documentation on this can be found at :docs.doctrine-project.org/projects/doctrine-orm/en/latest/… . Symfony docs are located at: symfony.com/doc/current/book/doctrine.html . Dont forget if your using annotions in php you need to add /** * @ORM\Entity() * @ORM\HasLifecycleCallbacks() */ to your doc header.
1

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();

1 Comment

Thanks for response and useful informations, but in my scenario I want to be able to create new Translation if its not already given - ie id_translation is null, I tried using prePersist approach but ended up with error telling about em not available in entity scope. Well maybe I should read more docs instead of trying to learn framework by creating sample project.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.