Answer the question
In order to leave comments, you need to log in
[[+content_image]]
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
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.
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 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 questionAsk a Question
731 491 924 answers to any question