Doctrine : Default value on joinColumn field - php

New to symfony2 and Doctrine.
How can I set a default value to the field foo_id (which is a reference on Foo table) to point on the ID 1 of the Foo table (which exists in all cases) ?
Me\NavigationBundle\Entity\PublicText:
type: entity
table: public_text
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
title:
type: string
length: '255'
nullable: false
content:
type: string
length: '2000'
nullable: false
manyToOne:
foo:
#How to set a default value???
targetEntity: \Me\NavigationBundle\Entity\Foo
joinColumn:
name: foo_id
referencedColumnName: id
nullable: false
lifecycleCallbacks: { }
I tried a lot of things without success :
Set default value to ID 1 in the constructor of Foo
Perform a request to retrieve the Foo object of ID 1 in the Me entity (could works, but bad practice)

Look up columnDefinition at Doctrine Column Annotations Reference¶
Pros: You can set up your own column definition
Cons: doctrine orm:schema-tool used by Doctrine (if you use it), gets confused and always reports columns that have a custom columnDefinition as changed. As it it will always tell you to run the change command for your column definition, as documented here:
SchemaTool will not detect changes on the column correctly anymore if you use "columnDefinition".
Example
/**
* #ManyToOne(targetEntity="YourType")
* #JoinColumn(
* name="your_type_id",
* referencedColumnName="id",
* nullable=false,
* columnDefinition="INT NOT NULL DEFAULT 1"
* )
*/
private $yourType;

Please note that using columnDefinition alone will work for generating migrations but will break the ORM context and potentially cause FK integrity issues. You will still need to add the object association to the ORM for persisting entities. See warnings from Ocramius
Example:
(new PublicText())
->getFoo(); //null - expected object(Foo)#1 (1) { ["id"] => int(1) }
I have seen many ways to achieve this in doctrine 2.
Constructor
In general, the quickest way and what most users do is require an association in the constructor.
public function __construct(Foo $foo)
{
$this->foo = $foo;
}
Then you can use getReference to retrieve it in your controller without needing to query the database. See http://doctrine-orm.readthedocs.org/en/latest/reference/advanced-configuration.html#reference-proxies
$foo = $em->getReference('app:Foo', 1);
$text = new \Path\To\Entity\PublicText($foo);
$em->persist($text);
$em->flush();
LifeCycleEvents
My preferred way Another method to set the default value with most ManyToOne relationships is to utilize the LifeCycleEvents http://doctrine-orm.readthedocs.org/en/latest/reference/events.html
Though it does have some caveats to be aware of. So be sure to RTM before implementing into production environments. In this case it should work fine, but I don't know your entire mapping structure.
use Doctrine\ORM\Event\LifecycleEventArgs;
/**
* #Entity
* #HasLifeCycleEvents
*/
class PublicText
{
// ...
/**
* #PrePersist
* #param \Doctrine\ORM\Event\LifecycleEventArgs $event
*/
public function onPrePersist(LifecycleEventArgs $event)
{
if (false === empty($this->foo)) {
return;
}
$this->foo = $event->getEntityManager()->getReference('app:Foo', 1);
}
}
Then in your controller.
$text = new \Path\To\Entity\PublicText;
$em->persist($text); //retrieve and set foo if not set in the Entity Event.
$em->flush();
Repository Method
Another option within your Entity is to just set the property's value using a Repository.
Define Repository Class in Entity
/**
* #Entity(repositoryClass="PublicTextRepo")
*/
class PublicText
{
// ...
}
Repository
use Doctrine\ORM\EntityRepository;
class PublicTextRepo extends EntityRepository
{
public function create()
{
$text = new \Path\To\Entity\PublicText;
$foo = $this->_em->getReference('app:Foo', 1);
$text->setFoo($foo );
return $text;
}
}
Then in your controller you can then do
$text = $em->getRepository('app:PublicText')->create();
$em->persist($text);
$em->flush();
Discriminator Map
Though not always viable depending on the use case. One of the ways I go about defining a default value of an Entity is creating a DiscriminatorMap with single table inheritance. http://doctrine-orm.readthedocs.org/en/latest/reference/inheritance-mapping.html#single-table-inheritance.
This way when the object is created the default value is automatically set in the database, and locks the object as that type. The issue is that the resulting value is not an object like it is in the other methods above.
To get the object's discriminator static value, you can use constants within the objects you define.
/**
* #Entity
* #InheritanceType("SINGLE_TABLE")
* #Table(name="user")
* #DiscriminatorColumn(name="type", type="string")
* #DiscriminatorMap({Person::TYPE="Person", Employee::TYPE="Employee"})
*/
class Person
{
const TYPE = 'person';
/**
* #return string [person|employee]
*/
public function getType()
{
return $this::TYPE;
}
// ...
}
/**
* #Entity
*/
class Employee extends Person
{
const TYPE = 'employee';
// ...
}
Then all you need to do in your controller is.
$employee = new \Path\To\Entity\Employee;
$em->persist($employee); //inserts with `user.type` as `employee`
$em->flush();
echo $employee->getType(); //employee

With annotation you can use : options={"default" = YourValue} on a #ORM\Column, So in yaml I think you can add
options:
default: yourValue
I'm not sure, i gie you an idea...

Related

Symfony2 Doctrine2 autoincrement field with custom id generator

I'm facing a problem with a custom id generator, auto-incrementation and doctrine-migrations in Symfony (2.7) with Doctrine (2.5) and MySQL.
When I use the custom generator, the id field does not get the AUTO_INCREMENT status in the migrations:diff output.
When I add the autoincrement manually in the yaml then all referenced table-columns also get the AUTO_INCREMENT.
How can I use auto increment on my primary entity with a custom generator without affecting the references?
The entity (sites.orm.yml):
type: entity
table: sites
id:
id:
type: integer
column: id
generator:
strategy: CUSTOM
customIdGenerator:
class: AssignableIdentityGenerator
The generator:
class AssignableIdentityGenerator extends AbstractIdGenerator {
public function generate(EntityManager $em, $entity) {
return $entity->getId() ? : (int) $em->getConnection()->lastInsertId();
}
public function isPostInsertGenerator() {
return true;
}
}
Migrations:diff output keeps being this (removes the AUTO_INCREMENT):
ALTER TABLE sites CHANGE id id INT NOT NULL;
If I add
options:
autoincrement: true
I don't get an ALTER for the sites table, which is correct because it keeps the AUTO_INCREMENT, but instead I get
ALTER TABLE other_table CHANGE site_id site_id INT AUTO_INCREMENT NOT NULL;
on a referencing table, which is not correct.
Doctrine natively suports the AUTO_INCREMENT with its own IdentityGenerator and I think I found the spot in Doctrine\ORM\Tools\SchemaTool::gatherColumn where this takes effect, but it's deep in a private method:
if ($class->isIdGeneratorIdentity() && $class->getIdentifierFieldNames() == array($mapping['fieldName'])) {
$options['autoincrement'] = true;
}
Unfortunately Doctrine is not very friendly to extensions (many private methods/properties or classes being instantiated instead of using injectable services).
Would anyone have a solution to this problem?
Or maybe even a whole different idea on how to get an id field that is both auto-incrementable and manually settable.
Would anyone have a solution to this problem? Or maybe even a whole different idea on how to get an id field that is both auto-incrementable and manually settable.
I got this solution for you:
First: You need to set up your ID strategy to "AUTO"
/**
* #var int
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
Second: If you want to set up your ID manually, you need to change the metadata (before flush) of your class. There you can change your IdGeneratorType
/**
* #param EntityManager $em
* #param mixed $object
*/
protected function changeIdGeneratorType(EntityManager $em, $object)
{
if ($object->getId() !== null) {
$metadata = $em->getClassMetadata(get_class($object));
$metadata->setIdGeneratorType($metadata::GENERATOR_TYPE_NONE);
}
}
$metadata::GENERATOR_TYPE_NONE
With this GeneratorType you will be able to set your ID's manually.
Now you will be able to both auto-incrementable and manually settable ID's

Symfony Doctrine One to Many does not insert foreign key

I am having annoying problems with persisting an entity with one or more OneToMany-Childs.
I have a "Buchung" entity which can have multiple "Einsatztage" (could be translated to an event with many days)
In the "Buchung entity I have
/**
* #param \Doctrine\Common\Collections\Collection $property
* #ORM\OneToMany(targetEntity="Einsatztag", mappedBy="buchung", cascade={"all"})
*/
private $einsatztage;
$einsatztage is set to an ArrayCollection() in the __constructor().
Then there is the "Einsatztag" Entity which has a $Buchung_id variable to reference the "Buchung"
/**
* #ORM\ManyToOne(targetEntity="Buchung", inversedBy="einsatztage", cascade={"all"})
* #ORM\JoinColumn(name="buchung_id", referencedColumnName="id")
*/
private $Buchung_id;
Now If I try to persist an object to the database the foreign key of the "Einsatztag" Table is always left empty.
$buchung = new Buchung();
$buchung->setEvent( $r->request->get("event_basis"));
$buchung->setStartDate(new \DateTime($r->request->get("date_from")));
$buchung->setEndDate(new \DateTime($r->request->get("date_to")));
$von = $r->request->get("einsatz_von");
$bis = $r->request->get("einsatz_bis");
$i = 0;
foreach($von as $tag){
$einsatztag = new Einsatztag();
$einsatztag->setNum($i);
$einsatztag->setVon($von[$i]);
$einsatztag->setBis($bis[$i]);
$buchung->addEinsatztage($einsatztag);
$i++;
}
$em = $this->getDoctrine()->getManager();
$em->persist($buchung);
foreach($buchung->getEinsatztage() as $e){
$em->persist($e);
}
$em->flush();
Firstly, you have to understand that Doctrine and Symfony does not work with id's within your entities.In Einsatztag entity, your property should not be called $Buchung_id since it's an instance of buchung and not an id you will find out there.
Moreover, in your loop, you add the Einsatztag to Buchung. But do you process the reverse set ?
I do it this way to always reverse the set/add of entities.
Einsatztag
public function setBuchung(Buchung $pBuchung, $recurs = true){
$this->buchung = $pBuchung;
if($recurs){
$buchung->addEinsatztag($this, false);
}
}
Buchung
public function addEinsatztag(Einsatztag $pEinsatztag, $recurs = true){
$this->einsatztages[] = $pEinsatztag;
if($recurs){
$pEinsatztag->setBuchung($this, false);
}
}
Then, when you will call
$buchung->addEinsatztag($einsatztag);
Or
$einsatztag->set($buchung);
The relation will be set on both side making your FK to be set. Take care of this, you'll have some behavior like double entries if you do not use them properly.
SImplier , you can use default getter/setters and call them on both sides of your relation, using what you already have, like following:
$einsatztag->set($buchung);
$buchung->addEinsatztag($einsatztag);
Hope it helped ;)
First of all, don't use _id properties in your code. Let it be $buchung. If you want it in the database, do it in the annotation. And this also the reason, why it's not working. Your are mapping to buchung, but your property is $Buchung_id
<?php
/** #ORM\Entity **/
class Buchung
{
// ...
/**
* #ORM\OneToMany(targetEntity="Einsatztag", mappedBy="buchung")
**/
private $einsatztage;
// ...
}
/** #ORM\Entity **/
class Einsatztag
{
// ...
/**
* #ORM\ManyToOne(targetEntity="Product", inversedBy="einsatztage")
* #JoinColumn(name="buchung_id", referencedColumnName="id")
**/
private $buchung;
// ...
}
You don't have to write the #JoinColumn, because <propertyname>_id would the default column name.
I'm going to ignore the naming issue and add a fix to the actual problem.
You need to have in the adder method a call to set the owner.
//Buchung entity
public function addEinsatztage($einsatztag)
{
$this->einsatztags->add($einsatztag);
$ein->setBuchung($this);
}
And to have this adder called when the form is submitted you need to add to the form collection field the by_reference property set to false.
Here is the documentation:
Similarly, if you're using the CollectionType field where your underlying collection data is an object (like with Doctrine's ArrayCollection), then by_reference must be set to false if you need the adder and remover (e.g. addAuthor() and removeAuthor()) to be called.
http://symfony.com/doc/current/reference/forms/types/collection.html#by-reference

optional multiple oneToMany relation in symfony2

I have entities in Doctrine Symfony2: User, Channel, Video and Comment; user can report one of them. I designed Report entity with these fields:
userId
status
reportTime
description
how can I reference to reported Entity ?? because all reported fields are similar for all entities I want to use just one table for Report and add these fields to Report Entity:
referenceEntityName(a string and may be one of these: User, Channel, Video, Comment)
Channel(ManytoOne relation to Channel entity)
Video(ManytoOne relation to Video entity)
Comment(ManytoOne relation to Comment entity)
User(ManytoOne relation to User entity)
Is this best practice or I should create separate tables for each kind of report ??
Edit:
based on #Alex answer, I improved Report class and add these methods:
setEntity($entity){
if ($obj instanceof Video){
$this->referenceEntityName = 'Video';
$this->setVideo();
}
elseif($obj instanceof Comment){
$this->referenceEntityName == 'Comment'
$this->setComment();
}
//...
}
getEntity(){
if($this->referenceEntityName == 'Video'){
$this->getVideo()
}// ifelse statements for other entities ...
}
I till have 4 relation that just one of them is used for each instance, isn't it a bit messy!?
and again is this best practice or I should do something else?
what if I want to use FormBuilder class, isn't there any problem??
In a simple solution, whereby for example you only had Users (and not Videos, Comments and Channels), the solution would be simple; each User can have many Reports, and each Report must belong to only one User. This is a one-to-many relationship - one User has many Reports. In Symfony 2 and Doctrine, this would be modelled as such:
// src/Acme/DemoBundle/Entity/User.php
// ...
use Doctrine\Common\Collections\ArrayCollection;
class User
{
// ...
/**
* #ORM\OneToMany(targetEntity="Report", mappedBy="user")
*/
protected $reports;
public function __construct()
{
$this->reports = new ArrayCollection();
}
// ...
}
and
// src/Acme/DemoBundle/Entity/Report.php
// ...
class Report
{
// ...
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="reports")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
// ...
}
In this instance, to create a Report and associate it with a User, we would:
// get the User the Report will belong to
$user = $em->getRepository('AcmeDemoBundle:User')->find(1);
// create the Report
$report = new Report();
// add the User to the Report
$report->setUser($user);
// then persist it, etc ...
Note, the setUser() method is available because the console command was run to generate them automatically. This is highly recommended as it created the necessary type hinting for you. For pre Symfony 2.5 installations, the command is:
php app/console doctrine:generate:entities Acme
>= 2.5 installations, the command is:
php bin/console doctrine:generate:entities Acme
Your requirements complicate this simple example somewhat, as Reports can also belong to Comments and Videos etc. For the sake of the example, let's call these things Entities. A bad approach would be to simply add 3 new properties to the Report, one for each of the new Entities, and then add 3 new setter methods for the Entities. This is bad for 2 reasons: a Report will only ever belong to one of the Entities, and therefore 3 of the properties and setter methods will never be used for each Report entity. Secondly, if you add a new Entity to your business model, or remove one, you need to edit your Report entity, and also the database schema.
A better method is to simply have one property and set method in your Report, that can be applied to all of your Entities. So instead of calling setUser, we could call a setEntity, and have it accept any of the 4. With this approach in mind, let's look back at the first example, and take note of the type hinting in the function signature that would have been produced for the setUser method:
public function setUser(Acme\DemoBundle\Entity\User $user)
See that it requires to be of type Acme\DemoBundle\Entity\User. How do we overcome this, and have it accept any of the 4 Entities? The solution is to have all Entities be derived from a parent class. Then make the function type hint at the base class:
public function setUser(Acme\DemoBundle\Entity\Base $entity)
The base class will contain all common elements, notably a 'name', and as array collection of Reports:
// src/Acme/DemoBundle/Entity/Base.php
// ...
use Doctrine\Common\Collections\ArrayCollection;
class Base
{
// ...
/**
* #ORM\Column(name="name", type="text")
*/
protected $name
/**
* #ORM\OneToMany(targetEntity="Report", mappedBy="baseEntity")
*/
protected $reports;
public function __construct()
{
$this->reports = new ArrayCollection();
}
// ...
}
and then for each child, for example a User and a Video:
// src/Acme/DemoBundle/Entity/User.php
// ...
use AcmeDemoBundle\Entity\Base;
class User extends Base
{
/**
* #ORM\Column(name="firstname", type="text")
*/
protected $firstName;
// ...
}
and the Video
// src/Acme/DemoBundle/Entity/Video.php
// ...
use AcmeDemoBundle\Entity\Base;
class Video extends Base
{
/**
* #ORM\Column(name="title", type="text")
*/
protected $title;
// ...
and change our Report Entity:
// src/Acme/DemoBundle/Entity/Report.php
// ...
class Report
{
// ...
/**
* #ORM\ManyToOne(targetEntity="Base", inversedBy="reports")
* #ORM\JoinColumn(name="base_id", referencedColumnName="id")
*/
protected $baseEntity;
// ...
}
Remember to run the doctrine command to generate the setBaseEntity method. When you do, notice that it will now accept any class derived of Base
Then, to put on a Report on a Video for example, we get the Video, create a Report, and add the Video to the Report:
$video = // get the video you want
$report = new Report();
$report->setBaseEntity($video);
To retrieve all Reports belonging to a Comment, we get the Comment, and get the Reports:
$video = // get the video you want
$reports = $video->getReports();
foreach($reports as $report){
$reportText = $report->getText(); // assuming the Report has a `text` field
}
Update:
The inheritance relationship between these Entities can be modelled in the database with Doctrine using Single Table Inheritance:
/**
* #ORM\Entity
* #ORM\Table(name="base_entities")
* #ORM\InheritanceType("SINGLE_TYPE")
* #ORM\Discriminator(name="entity_type", type="string")
* #ORM\DiscriminatorMap({"user" = "User", "comment" = "Comment", "video" = "Video", "channel" = "Channel"})
*/

Doctrine 2 - Disallow null value on foreign keys of ManyToOne relationships

I have a ManyToOne relationship in one of my entities, like so:
class License {
// ...
/**
* Customer who owns the license
*
* #var \ISE\LicenseManagerBundle\Entity\Customer
* #ORM\ManyToOne(targetEntity="Customer", inversedBy="licenses")
* #ORM\JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
// ...
}
class Customer {
// ...
/**
* Licenses that were at one point generated for the customer
*
* #var \Doctrine\Common\Collections\ArrayCollection
* #ORM\OneToMany(targetEntity="License", mappedBy="customer")
*/
private $licenses;
// ...
}
This generates a database schema where the "customer_id" field of the license table is allowed to be null, which is exactly what I do not want.
Here's some code where I create a record to prove that it indeed allows null values for the reference fields:
$em = $this->get('doctrine')->getEntityManager();
$license = new License();
// Set some fields - not the reference fields though
$license->setValidUntil(new \DateTime("2012-12-31"));
$license->setCreatedAt(new \DateTime());
// Persist the object
$em->persist($license);
$em->flush();
Basically, I don't want a License to be persisted without having a Customer assigned to it. Is there some annotation that needs to be set or should I just require a Customer object to be passed to my License's constructor?
The database engine I use is MySQL v5.1, and I am using Doctrine 2 in a Symfony2 application.
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/annotations-reference.html#annref_joincolumn
Add nullable = false to the JoinColumn annotation:
#ORM\JoinColumn(..., nullable=false)
Just posting because #zim32 didn't tell where we should put the statement, so i had to make a trial and error.
Yaml:
manyToOne:
{field}:
targetEntity: {Entity}
joinColumn:
name: {field}
nullable: false
referencedColumnName: {id}
cascade: ['persist']
I couldn't find an XML example of how to do this, so I'm going to leave this snippet here in case anyone else is looking for this:
<many-to-one field="author" target-entity="User">
<join-column name="author_id" referenced-column-name="id" nullable="false" />
</many-to-one>
The name and referenced-column-name are required, see the docs: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/xml-mapping.html#join-column-element

Default value in Doctrine

How do I set a default value in Doctrine 2?
<?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).
Set up a constructor in your entity and set the default value there.
Use:
options={"default":"foo bar"}
and not:
options={"default"="foo bar"}
For instance:
/**
* #ORM\Column(name="foo", type="smallint", options={"default":0})
*/
private $foo
Update
One more reason why read the documentation for Symfony will never go out of trend. There is a simple solution for my specific case and is to set the field type option empty_data to a default value.
Again, this solution is only for the scenario where an empty input in a form sets the DB field to null.
Background
None of the previous answers helped me with my specific scenario but I found a solution.
I had a form field that needed to behave as follow:
Not required, could be left blank. (Used 'required' => false)
If left blank, it should default to a given value. For better user experience, I did not set the default value on the input field but rather used the html attribute 'placeholder' since it is less obtrusive.
I then tried all the recommendations given in here. Let me list them:
Set a default value when for the entity property:
<?php
/**
* #Entity
*/
class myEntity {
/**
* #var string
*
* #Column(name="myColumn", type="string", length="50")
*/
private $myColumn = 'myDefaultValue';
...
}
Use the options annotation:
#ORM\Column(name="foo", options={"default":"foo bar"})
Set the default value on the constructor:
/**
* #Entity
*/
class myEntity {
...
public function __construct()
{
$this->myColumn = 'myDefaultValue';
}
...
}
None of it worked and all because of how Symfony uses your Entity class.
IMPORTANT
Symfony form fields override default values set on the Entity class.
Meaning, your schema for your DB can have a default value defined but if you leave a non-required field empty when submitting your form, the form->handleRequest() inside your form->isValid() method will override those default values on your Entity class and set them to the input field values. If the input field values are blank, then it will set the Entity property to null.
http://symfony.com/doc/current/book/forms.html#handling-form-submissions
My Workaround
Set the default value on your controller after form->handleRequest() inside your form->isValid() method:
...
if ($myEntity->getMyColumn() === null) {
$myEntity->setMyColumn('myDefaultValue');
}
...
Not a beautiful solution but it works. I could probably make a validation group but there may be people that see this issue as a data transformation rather than data validation, I leave it to you to decide.
Override Setter (Does Not Work)
I also tried to override the Entity setter this way:
...
/**
* Set myColumn
*
* #param string $myColumn
*
* #return myEntity
*/
public function setMyColumn($myColumn)
{
$this->myColumn = ($myColumn === null || $myColumn === '') ? 'myDefaultValue' : $myColumn;
return $this;
}
...
This, even though it looks cleaner, it doesn't work. The reason being that the evil form->handleRequest() method does not use the Model's setter methods to update the data (dig into form->setData() for more details).
Here is how to do it in PHP 8 using attributes.
#[ORM\Column(type: 'boolean', nullable: false, options: ['default' => 0])]
#[Assert\NotNull()]
private bool $isFavorite = false;
The workaround I used was a LifeCycleCallback. Still waiting to see if there is any more "native" method, for instance #Column(type="string", default="hello default value").
/**
* #Entity #Table(name="posts") #HasLifeCycleCallbacks
*/
class Post implements Node, \Zend_Acl_Resource_Interface {
...
/**
* #PrePersist
*/
function onPrePersist() {
// set default date
$this->dtPosted = date('Y-m-d H:m:s');
}
You can do it using xml as well:
<field name="acmeOne" type="string" column="acmeOne" length="36">
<options>
<option name="comment">Your SQL field comment goes here.</option>
<option name="default">Default Value</option>
</options>
</field>
Here is how I solved it for myself. Below is an Entity example with default value for MySQL. However, this also requires the setup of a constructor in your entity, and for you to set the default value there.
Entity\Example:
type: entity
table: example
fields:
id:
type: integer
id: true
generator:
strategy: AUTO
label:
type: string
columnDefinition: varchar(255) NOT NULL DEFAULT 'default_value' COMMENT 'This is column comment'
None of this worked for me. I found some documentation on doctrine's site that says to set the value directly to set a default value.
https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/faq.html#how-can-i-add-default-values-to-a-column
private $default = 0;
This inserted the value I wanted.
Works for me on a mysql database also:
Entity\Entity_name:
type: entity
table: table_name
fields:
field_name:
type: integer
nullable: true
options:
default: 1
Adding to #romanb brilliant answer.
This adds a little overhead in migration, because you obviously cannot create a field with not null constraint and with no default value.
// this up() migration is autogenerated, please modify it to your needs
$this->abortIf($this->connection->getDatabasePlatform()->getName() != "postgresql");
//lets add property without not null contraint
$this->addSql("ALTER TABLE tablename ADD property BOOLEAN");
//get the default value for property
$object = new Object();
$defaultValue = $menuItem->getProperty() ? "true":"false";
$this->addSql("UPDATE tablename SET property = {$defaultValue}");
//not you can add constraint
$this->addSql("ALTER TABLE tablename ALTER property SET NOT NULL");
With this answer, I encourage you to think why do you need the default value in the database in the first place? And usually it is to allow creating objects with not null constraint.
If you use yaml definition for your entity,
the following works for me on a postgresql database:
Entity\Entity_name:
type: entity
table: table_name
fields:
field_name:
type: boolean
nullable: false
options:
default: false
While setting the value in the constructor would work, using the Doctrine Lifecycle events might be a better solution.
By leveraging the prePersist Lifecycle Event, you could set your default value on your entity only on initial persist.
I struggled with the same problem. I wanted to have the default value from the database into the entities (automatically). Guess what, I did it :)
<?php
/**
* Created by JetBrains PhpStorm.
* User: Steffen
* Date: 27-6-13
* Time: 15:36
* To change this template use File | Settings | File Templates.
*/
require_once 'bootstrap.php';
$em->getConfiguration()->setMetadataDriverImpl(
new \Doctrine\ORM\Mapping\Driver\DatabaseDriver(
$em->getConnection()->getSchemaManager()
)
);
$driver = new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager());
$driver->setNamespace('Models\\');
$em->getConfiguration()->setMetadataDriverImpl($driver);
$cmf = new \Doctrine\ORM\Tools\DisconnectedClassMetadataFactory();
$cmf->setEntityManager($em);
$metadata = $cmf->getAllMetadata();
// Little hack to have default values for your entities...
foreach ($metadata as $k => $t)
{
foreach ($t->getFieldNames() as $fieldName)
{
$correctFieldName = \Doctrine\Common\Util\Inflector::tableize($fieldName);
$columns = $tan = $em->getConnection()->getSchemaManager()->listTableColumns($t->getTableName());
foreach ($columns as $column)
{
if ($column->getName() == $correctFieldName)
{
// We skip DateTime, because this needs to be a DateTime object.
if ($column->getType() != 'DateTime')
{
$metadata[$k]->fieldMappings[$fieldName]['default'] = $column->getDefault();
}
break;
}
}
}
}
// GENERATE PHP ENTITIES!
$entityGenerator = new \Doctrine\ORM\Tools\EntityGenerator();
$entityGenerator->setGenerateAnnotations(true);
$entityGenerator->setGenerateStubMethods(true);
$entityGenerator->setRegenerateEntityIfExists(true);
$entityGenerator->setUpdateEntityIfExists(false);
$entityGenerator->generate($metadata, __DIR__);
echo "Entities created";
Be careful when setting default values on property definition! Do it in constructor instead, to keep it problem-free. If you define it on property definition, then persist the object to the database, then make a partial load, then not loaded properties will again have the default value. That is dangerous if you want to persist the object again.

Categories