Safe attribute scenarios

February 17th, 2009

If you read my last article on validation scenarios then you may understand why in different scenarios you may need different attributes to be required. However you may have noticed a missing link – what if in different scenarios you also need different attributes to be considered as “safe”?

If you have no idea about what I am taking about then you probably don’t know that in your model you can specify which attributes are “safe” to massively assign to a model via CModel::setAttributes().

<?php
public function safeAttributes() {
	return array(
		//these attributes are safe to massively assign
		'attribute1, attribute2',
	);
}
?>

By default, all columns in the table are considered safe except the primary key column (attributes defined in the model are not considered safe by default)

The reason you might not want all attributes to be safe is if for instance you have fields which determine things such as access level. For instance what if you had a User model with a `is_admin` field. If you let `is_admin` be defined as safe, you have a security hole, as someone can take a tool such as urlparams and easily set himself as an admin.

Now you may actually want “is_admin” to be defined as safe in certain scenarios, such as an user administrative page. Thus, as of Yii 1.0.2, you can define scenarios through safeAttributes() which was the initial reason for writing this article.

I will simply use a code example taken from the Yii Class Reference this time.

<?php
public function safeAttributes() {
	return array(
	   // these attributes can be massively assigned in any scenario
	   // that is not explicitly specified below
	   'attr1, attr2, ...',
 
	   // these attributes can be massively assigned only in scenario 1
	   'scenario1' => 'attr2, attr3, ...', //Eg in this scenario attr1 is NOT safe
 
	   // these attributes can be massively assigned only in scenario 2
	   'scenario2' => 'attr1, attr3, ...',
	);
}

Now you may set the scenario to use via CModel::setAttributes()

<?php
$user->setAttributes(array <data>, string <scenario name>);
 
//Example:
$user->setAttributes($_POST['User'], 'update');
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • Technorati
  • Reddit
  • RSS
  • Twitter

Categories: Yii

Tags: Leave a comment

Comments Feed3 Comments

  1. Qiang

    Good explanation. One minor error: by default, all table columns EXCEPT the primary key column are safe. Imagine if you allow someone to modify the primary key of the current record being updated.

  2. Jonah

    Ah, missed that. I updated the article to mention that. Thanks!

  3. Safe attributes tip | Jonah’s Thoughts

    [...] my last two posts [1, 2] I explained how to define scenario-based validation rules and safe attributes. Something I have [...]

Leave a comment

Feed

http://php-thoughts.cubedwater.com / Safe attribute scenarios