A
A
Artyom2015-04-26 22:20:32
Yii
Artyom, 2015-04-26 22:20:32

Yii2: how to prevent certain fields from being changed?

How can I disable role change in yii2 for normal users?
The change happens like this:

$model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {
            if (!$model->validate()) {
                ....
            }            
            if ($model->save()) ....
        }

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
restyler, 2015-04-26
@DeOne

You put into use the scripts - ADMIN_PROFILE_UPDATE and USER_PROFILE_UPDATE, you put the current script in the controller by checking the rights of the logged in user there. then in the model you implement the scenarios() method in which you DO NOT specify the role field in the USER_PROFILE_UPDATE scenario (because it does not need to be updated).
Well, in the view it will be necessary to wrap the rendering of the form element in the condition
<?php if ($model->scenario == ADMIN_PROFILE_UPDATE): ?>
<?= $form->render($model, 'roles') ?>
<?php endif; ?>

E
Evgeny Lavrentiev, 2015-04-26
@lavrentiev

Just do not describe these fields when performing the operation and that's it!

J
jamalMixCart, 2019-11-07
@jamalMixCart

public function rules(): array
    {
        return [
            [['contact_email'], 'string', 'max' => 255],

            [['contact_email'], 'email'],

            [['contact_email'], 'editNotEmail', 'on' => self::EXPERT_UPDATE]
        ];
    }

    public function editNotEmail($attribute, $params)
    {
        if ($this->scenario === self::EXPERT_UPDATE) {
            if ($this->oldAttributes['contact_email'] !== $this->contact_email) {
                $this->addError($attribute, 'Невозможно изменять: ' . $attribute);
            }
        }
    }

I did it, I hope it helps!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question