Exclude some post attributes

Hi,

I have a model called User and it has 3 properties called name, lastname and created_date.

In my UserController I have this line.

$model->attributes=$_POST[‘User’];

which copies post attributes to User model. But I don’t won’t to copy the value of created_date to User model from post variables. Can I exclude some attributes from coping to model class.

Thanks,

Chamal.

Yes,

you can use




$model->attribute_name='';



For example, if you have

username, email, date in model then you can set null or empty value to the model as




$model->date='';




Setting attribute to empty string will store "" to DB and overwrite stored value.

If you don’t want to change DB data use unset or array_filter instead.

Or you may not to put created_date in rules() metgod.

I use this kind of automatic created and modified dates in my models:




  public function rules()

  {

    return array(

      ...

      array('created, modified', 'safe'),

      ...

    );

  }


  /**

   * This is invoked before the record is saved.

   * @return bool

   */

  public function beforeSave() {

    if ($this->isNewRecord) {

      $this->created = new CDbExpression('NOW()');

    }

    $this->modified = new CDbExpression('NOW()');

    return parent::beforeSave();

  }



Works pretty well.

You could also declare the created_date as unsafe on update like this:




  public function rules()

  {

    return array(

      ...

      array('created_date', 'unsafe', 'on'=>'update'),

      ...

    );

  }



Now the created_date is not set when you use: $model->attributes=$_POST[‘User’];