0

How can I safe my attributes for a massive assignment when I'm using a scenario (in my example 'update' scenario)?

Here is my rules:

public function rules()
{
    return [
        [['user_id', 'type', 'name', 'status'], 'required'],
        [['country_id', 'address', 'name', 'status'], 'safe', 'on' => 'update'],
    ];
}

public function scenarios()
{
    $scenarios = parent::scenarios();
    $scenarios['update'] = ['user_id', 'type', 'name'];
    return $scenarios;
}

When I'm checking the safe attributes in my controller using $model->safeAttributes(), I'm only getting the required attributes that are in the required of the 'update' scenario of the function scenarios().

And of course, the $model->load(Yii::$app->request->post()) function does not retreive other attributes.

How can I put them safe? Even if I want to add some other rules, I can't find the way!

Samir IZZA
  • 23
  • 1
  • 6
  • are you setting the scenario before you call the `$model->safeAttributes()` – Muhammad Omer Aslam Jan 11 '18 at 19:40
  • Yes, I'm defining the scenario just after the findModel function like this: `public function actionUpdate($id)` `{` `$model = $this->findModel($id);` `$model->scenario = 'CU';` – Samir IZZA Jan 11 '18 at 20:27

2 Answers2

0

Set the scenario before you load the model:

$model->setScenario('update');
$model->load(Yii::$app->request->post())
Patrick
  • 1,328
  • 10
  • 19
0

You need to add them all in scenario

$scenarios['update'] = ['user_id', 'type', 'name', 'country_id', 'address', 'name', 'status'];
Golub
  • 170
  • 1
  • 8
  • If I'm going to do this, it means that all these fields become required. But I don't want that. – Samir IZZA Jan 12 '18 at 16:15
  • @SamirIZZA No, it means that all these fields are safe and can be massively assigned. Required fields you configure in rules. – Golub Jan 12 '18 at 16:31
  • Oh man, you're right! I don't know how I understood it that way. I always thought that this way we declare the required fields and not the active fields. But I was wrong. Thanks for the help! – Samir IZZA Jan 13 '18 at 19:09
  • @SamirIZZA I’m happy to help. – Golub Jan 14 '18 at 22:44