Reputation: 1991
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;
}
Upvotes: 3
Views: 4061
Reputation: 48899
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;
}
Upvotes: 1