Model::save() and attribute like array

Good day!

We have attribute like array and rules for it, eg:




class Model extends CActiveRecord

{

    public $params = array('id'=>1);


    public function rules()

    {

        return array(

            array('params[id]', 'required')

        );

    }

}



It would seem that all is well… we see label and is required of the attribute in the form.

But if we’ll try to save model, yii said: “Property “Model.params[id]” is not defined.”

Basically I’m trying to validate, show label of this array items like if they would be model attributes, and it is fine.

Then before save I’m serialize()'ing this params array, and saving to DB like a string.

I just want that model will validate this "params" items like with attributes.

Have any ideas?

If somebody is interested, I solved this problem by override __get() method of model


class Model extends CActiveRecord

{

        public function __get($name)

	{

		if(preg_match('/([^\[]+)\[(.*?)\]/i', $name, $matches)) {

			return $this->{$matches[1]}[$matches[2]];

		} else {

			return parent::__get($name);

		}

	}

}

That looks great!

Kindly check whether the following is also helpful.




class Model extends CActiveRecord

{

    public $params = array('id'=>1);


    public function rules()

    {

        return array(

            array('params', 'checkValues'),

        );

    }


   public function ckeckValues($params,$values)

   {

      $params=$this->params;

      $values=array('id'); //Here you can add some more...


      foreach($values as $value)

        {

	if(!isset($params[$value]))

        $this->addError('params',"$value is not set");

	return false;	

        }

      return true;


   }

}




Thank you! But this way greatly limits my demands.

I can use any yii rule to validate array params if we will override __get, such as maxlength, int, file ext and so on.

Also more better way, so we can use multilevel attribute array:


class Model extends CActiveRecord

{

	public $params = array('id'=>1);


	public function __get($name)

	{

		if(strpos($name, '[') !== false) {

			return CHtml::resolveValue($this, $name);

		} else {

			return parent::__get($name);

		}

	}


	public function rules()

	{

		return array(

			array('params[id]', 'required')

		);

	}

}