Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2 setting a boolean back to null

I have a Doctrine2 entity with a type boolean using a tinyint in mysql to store the result. On the initial add of a value I can set it to null. If I save as 0 or 1 any new value I pass in other than a 0 or 1 saves as a 0.

Below is the variable with get and set methods. I have done a var_dump to confirm that the value is being set to null before it saves as 0.

 /**
 * @var string $completed
 *
 * @ORM\Column(name="is_completed", type="boolean", length=1, nullable=true)
 * @Api(type="field")
 */
private $completed;

 /**
 * Set completed
 *
 * @param boolean $value
 */
public function setCompleted($value = null)
{
    if ($value=='') {
        $value = null;
    }
    $this->completed = $value;
}

/**
 * Get completed
 *
 * @return boolean
 */
public function getCompleted()
{
    if (is_null($this->completed)) {
        $this->completed = '';
    }
    return $this->completed;
}
like image 926
Tom Avatar asked Feb 06 '26 13:02

Tom


1 Answers

Try this:

public function setCompleted($value = null)
{
    if ('' === $value) {
        $value = null;
    }
    $this->completed = $value ? true : false;
}

Assuming that, when passing an empty string you want null, otherwise you want true or false based on default PHP behaviour of $value.

And as suggested, no side effects in getters! This should be exactly the same as your getCompleted, as long as you use the above setter:

public function getCompleted()
{
    if (null === $this->completed)) {
        return '';
    }

    return $this->completed;
}
like image 87
gremo Avatar answered Feb 09 '26 08:02

gremo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!