Answer the question
In order to leave comments, you need to log in
How to implement validation of one form for two models?
I have 2 connected models in the form, the first model validates normally, and the second one does not validate at all, and you can save an empty field, which is unacceptable.
Here is the models/client code
class Client extends \yii\db\ActiveRecord
{
const SCENARIO_DEFAULT = 'default';
const SCENARIO_CREATE = 'create';
public static function tableName()
{
return 'client';
}
public function scenarios()
{
return [
self::SCENARIO_DEFAULT => ['id', 'fio', 'phone', 'emaail', 'home','street', 'apartment'],
self::SCENARIO_CREATE => ['id'],
];
}
public function rules()
{
return [
[['id'], 'required', 'on' => self::SCENARIO_CREATE],
[['fio', 'phone'], 'required', 'on' => self::SCENARIO_DEFAULT],
...
];
}
public function getIdClient()
{
return $this->hasOne(Client::className(), ['id' => 'id_client']);
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
$client = new Client();
$client->scenario = Client::SCENARIO_CREATE;
if ($model->load(Yii::$app->request->post())) {
$model->id_client = ArrayHelper::getValue(Yii::$app->request->post('Client'), 'id');
}
$model->validate();
if (!$model->save()) {
Yii::$app->session->addFlash('errors', 'Произошла ошибка');
print_r($model->getErrors());
} else {
$model->save();
Yii::$app->session->addFlash('update', 'Успешно отредактирован заказ');
}
}
return $this->render('update', [
'model' => $model,
'client' => $client,
]);
}
<div class="col-xs-12">
<?= $form->field($model, 'name')->textInput(['placeholder' => 'Имя клиента', 'class' => 'inputForm'])->label(false) ?>
<?php !$model->isNewRecord ? $client->id = $model->id_client : null ?>
<?php if (Yii::$app->request->get('phone')) {
echo $form->field($client, 'id')->widget(Select2::className(), [
'data' => [Yii::$app->request->get('phone')],
'disabled' => true,
])->label(false);
} else {
echo $form->field($client, 'id')->widget(Select2::className(), [
'data' => ArrayHelper::map(Client::find()->all(), 'id', 'phone', 'fio'),
'options' => ['placeholder' => 'Введите номер телефона'],
])->label(false);
}?>
</div>
Answer the question
In order to leave comments, you need to log in
There is no saving at all in your controller $client
. No save - no validation.
Here is the documentation for working with multiple models:
www.yiiframework.com/doc-2.0/guide-input-multiple-...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question