D
D
Dmitry Kim2016-06-11 09:18:25
Yii
Dmitry Kim, 2016-06-11 09:18:25

How to skip validation or field assignment in YII2?

What options are there to disable attribute changes based on the user's role?
It is necessary to allow mass assignment of this attribute during creation - for the admin and developer, and during editing - only for the developer. My option now:
Model:

public function rules(){
  return [
    ['id', 'required'],
    ['id', 'string'],
    ['id', 'unique'],
  ];
}
public function scenarios(){
  return [
    MODEL::SCENARIO_DEFAULT => ['id', 'title'],
    MODEL::SCENARIO_UPDATE => ['title'],
  ];
}

Controller:
public function actionUpdate($id){
  $model = $this->findModel($id);
  if (Yii::$app->user->identity->role < User::ROLE_DEVELOPER){
    $model->scenario = $model::SCENARIO_UPDATE;
  }
  // ...
}

I do not want to use this option, because. this controller is inherited from the "base ManagerController", which does not need such functionality. And I don't want to rewrite the method in this controller.
I think you can hang such a check in beforeValidate in the model. But perhaps there is something more concise? Maybe in the rules somehow screw it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Kim, 2016-06-11
@kimono

Resolved like this:

public function load($data, $formName = null)
{
  if (!$this->isNewRecord && User::identity()->role < User::ROLE_DEVELOPER) {
    $this->scenario = self::SCENARIO_UPDATE;
  }
  
  return parent::load($data, $formName);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question