im a beginner in yii and dont quite understand these 2 concepts.
in the documentation they mention scenario and safe attributes.
eg. on => login. i understand that the attribute data get validated with those rules on login. but how do i actually couple the key ‘login’ in the template with the validation rules?
and i still dont understand safe attributes? what happens and what are they for?
$model->attributes = $_POST[‘User’] is a shortcut for setAttributes method. It takes all $_POST array keys and tries to do an assignment $model->$key = $value. I am pretty sure you don’t have an “id” field on your form, but bad boys still can send a POST data like:
{id=>5, username=>123, password=>123, registerTime=>666}. It will corrupt your model, if you’ll try to update it.
Fortunately, all attributes are defined as “unsafe” by default. It means, $model->attributes = $_POST[‘User’] will assign nothing (a least, it’s better, than assign everything). By setting username and password attributes as “safe”, you’ll get the expected behavior (means, only attributes you expected to be assigned (safe attributes), will be assigned).
Scenarios are useful when your model (e.g. Comment) should use different validation rules in different situations. For example, we want to validate captcha field if a user is not logged-in, and don’t want to do it otherwise. It can be achieved by using scenarios and model rules:
// rule:
array('verifyCode', 'captcha', 'on'=>'guest')
// Put it anywhere before the validation:
$comment->scenario = 'guest'.
thanx for the excellent explanations. i understand it now. this should be posted in the documentation comments, cause they didnt mention the scenario property in the documentation.
just one thing: how do i know that $model->attributes is shortcut for $model->setAttributes?
it just lists setAttributes and getAttributes in API documentation.
so writing $model->attributes = $_POST[‘login’] is the same as $model->setAttributes($_POST[‘login’])?
how do you actually make a property to an alias to a method?