I am new to Yii2. I have a complex form which has 1 to many relationship. A step has many pages. When user clicks on "Add Page" buttons new record should be added to the database table and bottom GridView as well. First I tried to add the record to the database using Ajax post request. But it does pass an empty array to the controller.
[b]
My Action Method[/b]
public function actionAdd()
{
Yii::$app->response->format = Response::FORMAT_JSON;
$model = new Page();
$model->load(Yii::$app->request->post());
$model->save();
}
HTML Code
<?php $form2 = ActiveForm::begin([
'action' => ['page/add'], 'method' => 'post','id'=>'form-page',
]); ?>
<div >
<?= $form->field($model, 'step_id')->hiddenInput()->label(false); ?>
</div>
<div class="row">
<div class="form-group col-md-4 col-lg-4 col-sm-12">
<label for="title">Page Title</label>
<input type="text" class="form-control" id="title">
</div>
<div class="form-group col-md-4 col-lg-4 col-sm-12">
<label for="title">Display Order</label>
<input type="text" class="form-control" id="display_order">
</div>
</div>
<div class="form-group">
<?= Html::button('Add Page', ['class' => $model->isNewRecord ? 'btnAddPage btn btn-success' :
'btnAddPage btn btn-success']) ?>
</div>
<div class="row">
<?php Pjax::begin(); ?> <?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'step_id',
'title',
'display_order',
[
'class' => 'yii\grid\ActionColumn'
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
<?php ActiveForm::end(); ?>
JavaScript Code
$('.btnAddPage').on('click', function() {
var form = $('#form-page');
var formData ={
'step_id':$('#step-step_id').val(),
'title':$('#title').val(),
'display_order':$('#display_order').val(),
};
console.log(JSON.stringify(formData));
$.ajax({
url: form.attr("action"),
type: form.attr("method"),
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(formData),
success: function (data) {
sucessMsg('Step details successfully updated')
},
error: function () {
errorMsg('Error saving page')
}
});
});
This does not save the record to the database. Please guide me how can I fix this?