'Create form input using modal in yii2 does not validate
controller
public function actionCreate() {
$model = new Ceremonia();
if ($this->request->isPost) {
if ($model->load($this->request->post()) && $model->save()){ Yii::$app->getSession()->setFlash('info',[' Nombre <strong>insertado</strong> correctamente!!!']); return $this->redirect(['index']);
}}else{ $model->loadDefaultValues();}
if(Yii::$app->request->isAjax) {
return $this->renderAjax('create',['model' => $model]); }else{ return $this->render('create',['model' => $model]);
}
}
Index file in the project: Index
<?= Html::button('<i class="fas fa-plus"></i> Insertar',['value'=>Url::to('create'),'class' => 'btn btn-info','data-toggle'=>'modal','data-target'=>' ajax','id'=>'ModalButtonCreate']); ?>
<?php
Modal::begin(['title'=>'Insertar', 'id'=>'modalCreate', /*'size'=>'modal-lg',*/]);
echo '<div id="modalContentCreate"></div>';
Modal::end();
?>
main.js file in the project: main.js
$(function(){
$('#ModalButtonCreate').click(function(){
$('#modalCreate').modal('show').find('#modalContentCreate').load($(this).attr('value'));
});
});
AppAsset file in the project: AppAsset
class AppAsset extends AssetBundle {
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = ['css/site.css',];
public $js = ['js/main.js',];
public $depends = ['yii\web\YiiAsset','yii\bootstrap4\BootstrapAsset',];
}
Solution 1:[1]
you did not put the "Create" file code here for review. It would be better to put it instead of AppAsset. Because apparently your medal works well
The available codes only indicate that by clicking on the button, the medal window will be displayed. The "Create" page is then rendered via the Ajax load method in jQuery.
On the "Create" page, you must use ActiveForm or active methods in the Html library, such as activeInput in the form, to use the model class or 'ActiveRecord' class. For example, the save() method in 'ActiveRecord' and the validate() method in 'model' or 'ActiveRecord'.
*** Depending on your use of ($model->load($this->request->post()) && $model->save())
Note: consider using ActiveForm in case you're dealing with models and need validation. link
There are two groups of input methods. The ones starting with active, which are called active inputs, and the ones not starting with it. Active inputs take data from the model and attribute specified, while in the case of a regular input, data is specified directly. link
Here's a complete guide to rendering Form in popup via AJAX (Create and Update) with ajax
Good luck
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | user206 |
