[[+content_image]]
P
P
ptand2018-09-07 08:14:06
Yii
ptand, 2018-09-07 08:14:06

Show model property validation errors on a form?

Hello everyone, there is a model

class User extends ActiveRecord 
{
public $var1;
const SCENARIO_VAR1 = 'var1';

 public function rules()
    {
        return [
         [['var1', 'var2'], 'required', 'on' => self::SCENARIO_VAR1],
         ];
    }
}
</cod>
В форме, к примеру, 2 поля
<code lang="php">
<?php $form = ActiveForm::begin([
            'id'=>'form-three',
            'action' => '/site/save',
            'validationUrl' => '/site/validate',
            'enableAjaxValidation'=>true,
            'validateOnChange'=>false,
            'validateOnBlur'=>false,
        ]) ?>

<?= $form->field($user, 'var1')->widget(Select2::classname(), [
            'data'=>ArrayHelper::map(ArrVar1::find()->orderBy('name')->all(), 'id', 'name'),
            'size'=>'lg',
            'options'=>[
                'class'=>'form-control input-lg',
                'placeholder'=>'Выберите варианты 1',
                'multiple'=>true,
            ],
        ])->label(false)
        ?>
<?= $form->field($user, 'var2')->textInput(['placeholder'=>'Введите вариант 2', 'class'=>'form-control input-lg'])->label(false) ?>
</code>

Действие валидации
<code lang="php">
public function actionValidate()
    {
        $cookies = Yii::$app->request->cookies;
        $model_user = User::findByEmail($cookies->getValue('email', null));
        $model_user->scenario = User::SCENARIO_VAR1;

        if (Yii::$app->request->isAjax && $model_user->load(Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model_user);
        }
    }
</code>

Если поля не заполнены, после отправки формы аяксом в экшн валидации в респонсе прилетают обе! ошибки, но в форме отображаются только var2. Если убрать сценарий то все отображается нормально. Не могу понять почему, есть у кого какие мысли?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry, 2018-09-07
@slo_nik

well, registration in two stages =) In the modal window, fill in the full name and other crap, then click next, a tab opens where you still need to fill in additional information, specialty, work experience for example.

You don't need scripts for this. You can split the registration into two stages using cookies.
Scenarios can be divided, for example, the validation of registration and authorization on the site.
Here is an example from the documentation
class User extends ActiveRecord
{
    const SCENARIO_LOGIN = 'login';
    const SCENARIO_REGISTER = 'register';

    public function scenarios()
    {
        return [
            self::SCENARIO_LOGIN => ['username', 'password'],
            self::SCENARIO_REGISTER => ['username', 'email', 'password'],
        ];
    }
}

In this example, SCENARIO_LOGIN is used during authorization, that is, username and password will be validated . SCENARIO_REGISTER will be used during registration, and username, password and email will be checked . In your case, it will be possible to add additional attributes to this script for verification, for example, a phone number or an address, or something else.
Your script, const SCENARIO_VAR1 = 'var1' , is not a script at all, it's something incomprehensible.
And yet, if you are going to store data in a table, then remove public $var1 from the model , otherwise an empty value will be written to the database.
p.s. Documentation

P
ptand, 2018-09-10
@ptand

In general, I solved the problem by asking in the rules An error in the form is displayed, why it works this way, I still do not understand. I read that the properties must be accessed through attributes, perhaps the dog is buried in this, since after validation I do a wardump of the model and there is no var1 attribute, but only the fields of the database table. But I did not dig in this direction because there is no time. ['var1', 'safe']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question