Cannot Add A Variable To The Form That Is Not In The Db

When I add a variable, that is not in the DB, to my model it does not show up from a form submit unless I have the rule for it defined. But when I add it to the rules, the $model->save() results in mb_strlen() expects parameter 1 to be string, array given. The variable is an array and I’m using checkboxlist widget in the form view.

Here’s how the array is declared in my model:




	public $names=array();

	public function getTheNames()

	{

		return $this->names;

	}	

	public function setTheNames($value)

	{

		$this->names = array_merge ($this->names, array($value));

	}

         public function rules()

	{

		return array(

			array('names', 'length', 'max'=>64),



Thank you anyone who has an idea!!

The length (=StringValidator) rule only works with strings.

I think there are 2 options:

  • If $names is not filled with user input you can declare it as safe
  • If you have to validate $names in some way write your own custom validator.

[size="2"]

There is also an extension called [/size]array-validator[size=“2”] but I don’t know if it is still working with current version of yii nor how stable it is.[/size]

[size="2"]P.S.: Declaring Validation Rules[/size]

The length rule is a string validator, it’s not for arrays.

Just put that attribute as a safe rule for now:




    array('names', 'safe'),



EDIT: Ninja’d

Thanks for the advise! Before I read this I solved it by putting the non-DB array into a CFormModel and created a new object in the model and passed it to the form view. I’m guessing I didn’t have to do all this and just could have made it safe.




class Tabnames extends CFormModel 

{

	public $names=array();



Dear Friend

As I have similar problem in saving array from checkbox list in database.

Before saving it I converted it to string.

Before displaying it, I converted it again to array.

This way when validation fails or during update the checkbox list is nicely updated.




public function actionCreate()

	{

		$model=new Habit;


		if(isset($_POST['Habit']))

		{

			$model->attributes=$_POST['Habit'];

			if($model->habits!=='')

				$model->habits=implode(',',$model->habits);//converting to string...

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}

               $model->habits=explode(',',$model->habits);//converting to array...

		$this->render('create',array(

			'model'=>$model,

		));

	}


public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		if(isset($_POST['Habit']))

		{

			$model->attributes=$_POST['Habit'];

			if($model->habits!=='')

				$model->habits=implode(',',$model->habits);

			if($model->save())

				$this->redirect(array('view','id'=>$model->id));

		}

        $model->habits=explode(',',$model->habits);

		$this->render('update',array(

			'model'=>$model,

		));

	}




Regards.