yii: date field save as null value

by prettyscripts on 2010-11-09 12:39:00

phpyii

update: thanks to mindochin and josh who left a comment below, please check this post for the correct solution.

by default if date is not entered in a form, the value is saved as '0000-00-00'. yii does not automatically save it as null. to save the field as null, it needs to be done manually.

update (or add) beforeSave() function in model file:

PHP:

protected function beforeSave()
{
    if ($this->name_of_date_field == '')
        $this->setAttribute('name_of_date_field'null);
 
    return parent::beforeSave();
}

generic save field as null if no value

the following code is not specific to any attribute types. if no value is entered and null allowed, then save the value as null.

PHP:

protected function beforeSave()
{
    foreach ($this->getTableSchema()->columns as $column) {
        if ($column->allowNull == && $this->getAttribute($column->name) == '')
            $this->setAttribute($column->namenull);
    }
 
    return parent::beforeSave();
}

Tags: code, null, php, save, yii

7 comments

Comment by sholeh @ 2011-04-20 17:51:43
thank's for u'r post.
Comment by mindochin @ 2011-10-09 01:59:44
set attribute 'setOnEmpty'=>null in model->rules()
Comment by josh @ 2011-11-17 20:50:40
re:mindochin, (for newbies like me) the exact language is:

array('nameofdatefield', 'default', 'setOnEmpty'=>null),
Comment by prettyscripts @ 2011-12-19 12:29:15
@mindochin and @josh, thanks so much for the tip!
Comment by arazaki @ 2011-12-29 20:12:31
I already used and the correct way is:
array('nameofdatefield', 'default', 'setOnEmpty'=>true, 'value' => null),
Comment by gary @ 2012-01-01 02:07:28
*****
Thanks for the tips .
Comment by prettyscripts @ 2012-01-18 10:56:25
@arazaki, i have done some tests, 'value' parameter is not required to save the empty field as null.

Leave a comment


Your email address will not be revealed on this site.
PoorExcellent
note: all comments are moderated. do not spam and do not advertise. only comments relevant to the post will be published.
(Line breaks become <br />)
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)