user2492854
user2492854

Reputation: 401

Yii clearing set values of attribute

In my web application I need in such a way that one particular attribute should be cleared or set to Null when clicked to update that record .How should I go ahead I am clueless.

Upvotes: 0

Views: 91

Answers (2)

crafter
crafter

Reputation: 6296

In your model, create a function beforeSave()

class Customer extends CActiveRecord
{
....
   public function beforeSave() {
      $this->last_order = null;
   }
....
}

Upvotes: 1

JamesG
JamesG

Reputation: 1698

Assuming you have a controller action that's dealing with a form submission - which would be the usual situation - you'll have a function in your controller like this:

public function actionUpdate($id)
{
    // Load model
    $Model = Model::model()->findByPk($id);

    // or maybe do it this way
    $Model = $this->loadModel($id);

    // Check for form POST
    if(isset($_POST['Model']))
    {
         // Mass assignment of Model attributes to matching values in post array
         $Model->attributes = $_POST['Model'];

         if($Model->save())
         {
              // Do something, redirect etc
         }
    }

    $this->render('yourView');
}

So in there we're mass assigning the $Model properties to matching values in the POST array from your form. But after that's done you can overwrite individual properties. For example:

    // Check for form POST
    if(isset($_POST['Model']))
    {
         // Mass assignment of Model attributes to matching values in post array
         $Model->attributes = $_POST['Model'];

         $Model->attribute_a = null;
         $Model->attribute_b = '';
         $Model->name = 'Anything you like';
         $Model->date = 'Anything you like';
         // ...etc

         if($Model->save())
         {
              // Do something, redirect etc
         }
    }

Upvotes: 1

Related Questions