Model Attributes format per scenario;/action

Hello,

This is my goal: Format the value of an Active Record model attribute differently per scenario;/action.

more specifically, Append the Currency Symbol OR another Custom Value of mine at the Attribute

only on the Index and View actions.

Using afterFind, I can alter the attribute’s value as I please, so this part is solved.

The problem is how to differentiate the formatting according to the action or scenario.

As we know, default scenarios are only update/insert for Index/View/Update

so I cannot use only this information to know when the user is Updating or Viewing the attribute values…

I tried in the controller to set the $model->setScenario(‘updateAction’);

in order to know when the update action is taking place and format accordingly.

Problem is, the scenario defaults to ‘update’.

In both case demonstrated below, the $this->scenario in the afterFind() equals ‘update’:




public function actionUpdate($id)

	{

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

		$model->setScenario('updateAction');

	

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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}



as well as when using this:




public function loadModel($id)

	{

		$model=MyModel();

		$model->setScenario('updateAction');

		$model=$model->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}



Even though the Scenario has been set on the model before the findByPk is called,

the scenario value defaults to ‘update’ from my desired ‘updateAction’ when accessed inside afterFind().

Any ideas how to fix this, or perhaps, implement it properly?

I would not use scenario for this kind of thing. Even if it were easy to do it seems to me to be mixing up your business logic with your presentation.

I would add a new function to the model to format an attribute with a currency symbol (or however else you need it to be).


public function getFormattedPrice()

{

    return '$'.$this->Price;

}



Use $item->Price in the read/write views

User $item->FormattedPrice in the read only views.

If you are using gridview or listview for your display, you might simply subclass

CFormatter with a formatMoney method, and then tag these values as being of type "money".

You are correct, I started to mix the presentation with business logic…

I really like the idea of extending the CFormatter, tried it and loved it.

Thanks!