Symfony2 - Set default value in entity constructor

default, entity, symfony

Solution

I think you're better to set it inside a `PrePersist` event.

In `User.php`:

use Doctrine\ORM\Mapping as ORM;

/**
* ..
* @ORM\HasLifecycleCallbacks
*/
class User 
{
         /**
         * @ORM\PrePersist()
         */
        public function setInitialFoo()
        {
             //Setting initial $foo value   
        }

}

But setting a relation value is not carried out by setting an integer `id`, rather it's carried out by adding an instance of `Foo`. And this can be done inside an event listener better than the entity's `LifecycleCallback` events (Because you'll have to call `Foo` entity's repository).

First, Register the event in your bundle `services.yml` file:

services:
    user.listener:
        class: Tsk\TestBundle\EventListener\FooSetter
        tags:
            - { name: doctrine.event_listener, event: prePersist }

And the `FooSetter` class:

namespace Tsk\TestBundle\EventListener\FooSetter;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Tsk\TestBundle\Entity\User;

class FooSetter
{
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entityManager = $args->getEntityManager();

        if ($entity instanceof User) {
            $foo = $entityManager->getRepository("TskTestBundle:Foo")->find(1);
            $entity->addFoo($foo);
        }
    }
}

Problem

I can set a simple default value such as a string or boolean, but I can't find how to set the defualt for an entity. In my User.php Entity: ``` /** * @ORM\ManyToOne(targetEntity="Acme\DemoBundle\Entity\Foo") */ protected $foo; ``` In the constructor I need to set a default for $foo: ``` public function __construct() { parent::__construct(); $this->foo = 1; // set id to 1 } ``` A Foo object is expected and this passes an integer. What is the proper way to set a default entity id?

Original source