Massive assigment scenario on update not creation

Using a scenario when massively assigning is straight forward for creating record (Safe Attributes in 1.1 http://www.yiiframework.com/doc/guide/form.model)

I can’t work out how to update a record with scenario.

In my model rules I have




array('email, about_me, about_equip', 'required', 'on'=>'updateprofile'),



I’ve tried all sorts of code in the controller and have got myself totally confused.

From my experience, it’s usually due to validations. Try commenting out some validation rules and see if it works.

Update with or whitout scenario is nearly the same.

The code you should use is the usual CRUD code, the only difference that scenarios does are validators.

Changing the list of validators means change safe attribute, and so you can protect data (some field that in some scenarios you don’t want to expose to modify) by changing the validation rules.

What exactly confuse you? Do you need some examples? About what?

create is simple




$model=new User('updateprofile');

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

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



but I couldn’t work out how to tell the update to only process the fields in the scenario. With an update you have existing data to use in the model ie…

$model=$this->loadModel();

or

$model=User::model()->findbyPk(Yii::app()->user->getId());

before doing the $model->save()

I couldn’t work out where the scenario should be set. I tried $model->validate(‘updateprofile’) as well but I was getting totally confused by that point.

I have got another question about the validation rules and setting some outside the scenario but one at a time!

are you trying to set your scenario? if so $model->setScenarion(‘update’);

setScenario works! I’ve pasted the full update function below.

This also works when you have other rules set… I’ve had a problem before with other rules preventing the scenario rule from functioning.




	public function actionUpdate()

	{

		$model=User::model()->findbyPk(Yii::app()->user->getId());

		$model->setScenario('updateprofile'); // rules set in model for updating profile


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

		{				

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

			if($model->save()){

				 $this->redirect(array('view','id'=>Yii::app()->user->getId()));

					}	

		}


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

			'model'=>$model,

		));

	}