Search code examples
phpyiimodelyii-components

Yii set not beign called before beforeSave?


Small issue.. I have a table that stores some system varables as a serialized array.. In my model i have to functions for setting and getting this field into a readable form. they are:

public function setoptPramasString($value){
     $this->opt_pramas = '';

     $str1 = explode(',', $value);
     foreach ($str1 as $str2) {
         $myVal = explode('=>', $str2);
         $this->opt_pramas[trim($myVal[0])] = (string)trim($myVal[1]);   
         echo "<BR>".$myVal[0]." => ".$myVal[1];
     }
 }

/**
 * 
 */
 public function getoptPramasString(){
     $str = '';
     $x = 0;
     foreach ($this->opt_pramas as $key => $value) {
         if($x == 0){
            $str .= $key."=>".$value;
             $x++;
         }else{
             $str .= ", ".$key."=>".$value;
         }

     }

my before save and after find functions are:

/**
 * 
 */
 public function beforeSave(){

     $this->opt_pramas = serialize($this->opt_pramas);
     return parent::beforeSave();
 }

 /**
  * 
  */
  public function afterFind(){
      $this->opt_pramas = unserialize($this->opt_pramas);
      return parent::afterFind();
  }

My update action in the controller is:

public function actionUpdate($id)
{
    $model=$this->loadModel($id);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['SystemMenuSearch']))
    {
        $model->attributes=$_POST['SystemMenuSearch'];
        if($model->save()){
            $this->redirect(array('view','id'=>$model->search_id));    
        }
    }

    $this->render('update',array(
        'model'=>$model,
    ));
}

What seems to be happening is that the beforeSave function is being called before the setoptPramaString function. Is this a bug in Yii or am I missing something? My logic would be that when the values are set to the models attributes it would fire the setoptPramaString function and then when save is called on the model it would fire the beforeSave function in the model. I check my form and the name is correct, SystemMenuSearch[optPramaString].


Solution

  • when you mass-assign your parameters through setAttributes property

    $model->attributes = $_POST[SystemMenuSearch];
    

    they will be ignored because they are not in the safe attributes list