Asked  7 Months ago    Answers:  5   Viewed   39 times

How do I set a default value in Doctrine 2?

 Answers

59

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).

Wednesday, March 31, 2021
 
Strae
answered 7 Months ago
48

As far as I know, there is still no way to do that in DQL, and the reason might be that it does not make much sense from an ORM perspective, according to one of the lead developers.

Nevertheless, the feature request, although very old, is still open; so it might be implemented in the future.

Wednesday, March 31, 2021
 
matthy
answered 7 Months ago
59

I agree with moonwave99 that this is poor design. Here you are trying to access the database (through the Doctrine service) from a place that is not container-aware (i.e. it does not, and should not, know about Doctrine).

I had a similar issue recently... pretty much the same exact issue, actually. But I didn't want this logic to be inside the controller. So I wrote a service to take care of the User creation. And I gave that service access to the only other service it needed: Doctrine.

Here's an example, where a User is created with all available Roles:

namespace MyBundleEntity;

class UserFactory
{
    private $doctrine;

    public function __construct($doctrine)
    {
        $this->doctrine = $doctrine;
    }

    public function generateNewUser($email, $password)
    {
        $user = new User();

        // Since you have access to the Doctrine service, you can use $this->doctrine
        // to do anything you would normally do in your controller with $this->getDoctrine()
        $roles = $this->doctrine->getEntityManager()->getRepository("MyBundle:Role")->findAll();

        foreach ($roles as $role)
        {
            $user->addRole($role);
        }

        return $user;
    }
}

Now register that service in config.yml or services.yml, remembering to pass the Doctrine service to it:

services:
    mybundle.factory.user:
        class: MyBundleEntityUserFactory
        arguments: ['@doctrine']

And that's it... Now, in your controller, you can create a new User by doing:

public function MyController()
{
    $user = $this->get("mybundle.factory.user")->generateNewUser("someone@email.com", "password123");
}
Wednesday, March 31, 2021
 
BartmanEH
answered 7 Months ago
47

Use the Database level onDelete option with Doctrine

@ORMJoinColumn(name="dealer_id", referencedColumnName="id",  onDelete="SET NULL")

explanation from here:

  • CASCADE will propagate the change when the parent changes. (If you delete a row, rows in constrained tables that reference that row will also be deleted, etc.)
  • SET NULL sets the column value to NULL when a parent row goes away.

  • RESTRICT causes the attempted DELETE of a parent row to fail.


... update your database schema prior to complaining it's not working :-)

app/console doctrine:schema:update --force

if this is not working due to foreign key errors go the hard way (in this order) :

  • app/console doctrine:database:drop
  • app/console doctrine:database:create
  • app/console doctrine:schema:update --force
  • ( optional: app/console doctrine:fixtures:load )
Saturday, May 29, 2021
 
kwichz
answered 5 Months ago
91

You map your property as DateTime type then set the value in the constructor using a new DateTime instance:

/**
 * @Entity
 * @Table(name="...")
 */
class MyEntity
{
    /** @Column(type="datetime") */
    protected $registration_date;

    public function __construct()
    {
        $this->registration_date = new DateTime(); 
    }
}

This works as the constructor of a persisted class is not called upon hydration.

Wednesday, August 11, 2021
 
Lodrik
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :