0

is there a simple way to persist an entity with all values = 0? My entity has an extreme amount of rows ... typing ->setBlabla(0) for that amount of rows..puh..

Is there an "easier" way?

Regards

  • Could you provide use what have you done yet? Maybe an easy way be getting the repository and create an update query – Javad Apr 25 '14 at 21:49
  • 2
    possible duplicate of [Default value in Doctrine](http://stackoverflow.com/questions/3376881/default-value-in-doctrine) – Wouter J Apr 25 '14 at 21:52
  • Well, its an entity with like 226 columns. getters/setters. I'd like to predefine a value for every column. If i persist a new row the value for every column has to be 0. Writing it down by hand... guess i sound lazy, but i feel like there's a way around it. –  Apr 25 '14 at 21:53
  • Yeah, sorry. Thx Wouter! –  Apr 25 '14 at 21:55
  • Hm, i've set options={"default"= 0}, when i insert a row via mysql it works fine, but when i persist a new row via doctrine/em, it puts "null" instead of "0". Any idea? –  Apr 25 '14 at 22:12
  • class MySillyEntity { protected $var1 = 0; protected $var2 = 0; and so on. – Cerad Apr 25 '14 at 22:31
  • When you set `options={"default"= 0}` you also need to set `nullable=false` for them, too – Javad Apr 26 '14 at 00:59

2 Answers2

2

The doctrine docs suggest to define default values via entity properties:

class User
{
    const STATUS_DISABLED = 0;
    const STATUS_ENABLED = 1;

    private $status = self:STATUS_DISABLED;
}

see FAQ http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/faq.html#how-can-i-add-default-values-to-a-column

I would prefer to set all properties default values in entity class constructor:

class User
{
    const STATUS_DISABLED = 0;
    const STATUS_ENABLED = 1;

    private $status;

    public function __construct()
    {
        $this->status = self::STATUS_DISABLED;
    }

}
Vera
  • 742
  • 4
  • 9
0

You can set a default value for each field and use nullable=false to force it insert the default value; like this

@ORM\Column(name="column_name", type="integer", nullable=false, options={"default" = 0})

Or you can create a service prePresist to set the "0" value to empty fields before persist be fired. Take at look at
Doctirn2 Lifecycle Events
Symfony2 Event Listener

Javad
  • 4,339
  • 3
  • 21
  • 36