symfony doctrine will not default a boolean to 0

Issue

I have tried in several ways to have symfony default a boolean to 0 rather than null (as null gives me a database level error upon flush).

An exception occurred while executing a query: SQLSTATE[23000]:
Integrity constraint violation: 1048 Column ‘auto_created’ cannot be
null

This made no difference:

/**
 * @ORM\Column(type="boolean", options={"default":"0"})
 */
private $autoCreated;  

Some logic i the setter made no difference either

public function setAutoCreated(bool $autoCreated): self
{
    if is_null($autoCreated) {
        $autoCreated = 0;
    }

    $this->autoCreated = $autoCreated;

    return $this;
}  

As well as

public function setAutoCreated(bool $autoCreated): self
{
    if is_null($autoCreated) {
        $autoCreated = false;
    }

    $this->autoCreated = $autoCreated;

    return $this;
}  

Database looks like this

phpmyadmin saying default:0

I am clearly missing something…?

Sure I can do a simple $user->setAutoCreated(false); everywhere I create this entity, but I don’t get why I should have to 😎

Solution

Depending on the version of PHP you’re using, you should be able to do something like this in your entity class:

/**
 * @ORM\Column(type="boolean")
 */
private $autoCreated = false; 

Whenever an instance of this class is created, $autoCreated will be set to false. So when you try to persist the object, it’ll have a default value of false and Doctrine will set the field to 0.

Alternatively, you can explicitly set $autoCreated to false in your constructor:

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

Typically, I always use the first approach unless a more complicated object is being constructed (e.g., a Doctrine ArrayCollection).

Note that you can only use the first approach for simple, built-in PHP types or constants. For more complicated objects you’ll need to use the constructor approach.

Answered By – NeuralClone

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published