9

I need get default value in class file

private $example_field = 0;

When I use this

example_field:
    options:
        default: 0

I got default database value, but when I try to persist without setting "su" I got error (column 'su' cannot be null).

Anyway,

example_field:
    default: 0

Does nothing.

j0k
  • 22,600
  • 28
  • 79
  • 90
Shadow Prince
  • 198
  • 1
  • 1
  • 7
  • OK, I've done some testing and I think this _does_ work using your first example. _However_ if you are setting a default for an existing table then it does not detect that `default: 0` is different to `` so thinks there is nothing to change. If you first set it to `default: 1`, update the schema and _then_ change it to `default: 0` you should get there. (this worked for me with string fields) – caponica Jun 07 '13 at 13:24

3 Answers3

22

this work for me:

fields:
    my_field:
        options:
            default: 5
Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91
Frederic
  • 221
  • 2
  • 3
3

The correct definition for a 0 default value would be by using quotes:

example_field:
    options:
        default: '0'
0

Doctrine does not support the SQL 'DEFAULT' keyword:

http://docs.doctrine-project.org/en/2.1/reference/faq.html

To solve this problem, you need to set defaults in your entity's constructor. If you want the default private variable in the class file, make and use a public getter function.

You can also try to set the variable during persist in a controller.

Lighthart
  • 3,648
  • 6
  • 28
  • 47
  • I don't use annotations, but apparently you CAN set a default value using them: http://stackoverflow.com/questions/3376881/default-value-in-doctrine. The question here is how to do the same thing using YML. There are valid reasons for wanting to do so - e.g. data migrations where your code is not the only entry point to the database because you're running SQL directly. – caponica Jun 07 '13 at 12:58