How can I set a default value in Doctrinemongodb document?

1.4k views Asked by At

How can I set the default value in field.

In my document I need to set default value false for field emailnotify In mogodb th default value should be zero.

Check my document

namespace xxx\xxxBundle\Document;

use FOS\UserBundle\Document\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;

/**
 * @MongoDB\Document
 */
class User extends BaseUser
{
    /**
     * @MongoDB\Id(strategy="auto")
     */
    protected $id;

    /**
     * @MongoDB\Boolean
     */
    protected $emailnotify;

    /**
     * Sets the emailnotify.
     *
     * @param boolean $emailnotify
     *
     * @return User
     */
    public function setEmailnotify($emailnotify)
    {
        $this->emailnotify = (Boolean) $emailnotify;
        return $this;
    }
    /**
     * @return boolean
     */
    public function isEmailnotify()
    {
        return $this->emailnotify;
    }

}
1

There are 1 answers

0
Zerrvox On

I have found that setting the default value in the constructor works

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

Of course just setting the class variable to false will work for most parts if you use Doctrine to fetch the Document again afterwards, but the property will not be persisted to MongoDB like with the above.