inserting or updating null value fields [solved]

hello all,

I’ve got a table with 4 fields defined as:


  `selling_start_date` timestamp NULL default CURRENT_TIMESTAMP,

  `selling_end_date` timestamp NULL default NULL,

  `sale_start_date` timestamp NULL default NULL,

  `sale_end_date` timestamp NULL default NULL,



now, those attributes on the model have no rule specified but are on the safeAttributes() list

what happened is that on first insertion with empty fields, I had the fields in the db with ‘0000-00-00 00:00 00:00’ as a value.

I tried to add something in the controller in the actionUpdate() method just to test its functionality but nothing has changed, so it seemed something related to the validation process, so I added this method in the model:


    public function beforeSave() {

        if (!$this->selling_start_date)

            $this->selling_start_date = NULL;

        if (!$this->selling_end_date)

            $this->selling_end_date = NULL;

        if (!$this->sale_start_date)

            $this->sale_start_date = NULL;

        if (!$this->sale_end_date)

            $this->sale_end_date = NULL;

    }

but when I’m going to submit the form, the form isn’t submitted and it keeps showing.

What’s wrong?

What’s the best way to handle NULL values from yii ???

any help&hint is highly appreciated.

Best Regards,

The Peach.

if u want to set the default date value

try adding this on your model

array(‘selling_start_date’,‘default’,‘value’=>new CDbExpression(‘NOW()’),‘setOnEmpty’=>false,‘on’=>‘insert’),

that seems reasoneable, thanks onek13.

what about the null values? can I gain the same result with a similar validator, but with for example ‘setOnEmpty’=>null ? I’m gonna try it, but if anyone of you have already tried and can share your own experience…

[edit] about the null, the thing is that I’d like to AVOID sending certain fields in the query. Is the only way using DAO?

ok figured it out by myself. finding the right answer in the forums (the search form on top right is crappy)

I had to add the return value at the end…


    public function beforeSave() {

        if (!$this->selling_end_date)

            $this->selling_end_date = NULL;

        if (!$this->sale_start_date)

            $this->sale_start_date = NULL;

        if (!$this->sale_end_date)

            $this->sale_end_date = NULL;

        return parent::beforeSave();;

    }

thanks anyway

Add this to your public function rules() code would also work instead of your mentioned beforeSave code




array(array('selling_end_date','sale_start_date','sale_end_date'), 'default', 'setOnEmpty'=>true,'value'=>null,'on'=>array('insert','update')),



which sets “null” for the given fields if ‘’ is submitted, which could be the case if you e.g. use some calendar plugin and selecting no date at all.

that’s exactly what I needed! thanks a lot horizon!