How do I set a default value in Doctrine 2?
A default value is the value that is inserted into a column when an explicit value is not specified in an INSERT statement. A default value can be a literal character string that you define or one of the following SQL constant expressions: USER.
A DEFAULT value clause in a data type specification explicitly indicates a default value for a column. Examples: CREATE TABLE t1 ( i INT DEFAULT -1, c VARCHAR(10) DEFAULT '', price DOUBLE(16,2) DEFAULT 0.00 ); SERIAL DEFAULT VALUE is a special case.
If no default value is declared explicitly, the default value is the null value. This usually makes sense because a null value can be considered to represent unknown data. In a table definition, default values are listed after the column data type.
Default values are very often used as an aid to data entry. If we can provide data to users that is most often the data that they would have entered, then we would have done them a favor and sped up data entry.
<?php /** * @Entity */ class myEntity { /** * @var string * * @ORM\Column(name="myColumn", type="integer", options={"default" : 0}) */ private $myColumn; ... }
Note that this uses SQL DEFAULT
, which is not supported for some fields like BLOB
and TEXT
.
Database default values are not "portably" supported. The only way to use database default values is through the columnDefinition
mapping attribute where you specify the SQL
snippet (DEFAULT
cause inclusive) for the column the field is mapped to.
You can use:
<?php /** * @Entity */ class myEntity { /** * @var string * * @Column(name="myColumn", type="string", length="50") */ private $myColumn = 'myDefaultValue'; ... }
PHP-level default values are preferred as these are also properly available on newly created and persisted objects (Doctrine will not go back to the database after persisting a new object to get the default values).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With