Новое действие в контроллере:
Код: Выделить всё
public function actionAdd() {
$ model = new Company();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
echo 1;
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
};
}
Код: Выделить всё
<?= Html::button('<span class="glyphicon glyphicon-plus"></span> Новая компания', ['value' => Url::to('/web/company/add'), 'class' => 'btn btn-success', 'id' => 'modalButton']) ?>
Код: Выделить всё
use yii\bootstrap\Modal;
use yii\widgets\Pjax;
<?php
Modal::begin([
'header' => '<h4>Company<h4>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
Код: Выделить всё
<?php Pjax::begin(['id' => 'companyList']); ?>
<?= $form->field($model, 'id_company')->widget(Select2::className(), [
'data' => ArrayHelper::map(Company::find()->all(), 'id', 'name'),
'options' => [
'placeholder' => 'Выберете компанию',
],
'pluginOptions' => [
'allowClear' => true
],
]) ?>
<?php Pjax::end(); ?>
Код: Выделить всё
public $js = [
'js/main.js'
];
Код: Выделить всё
$(function(){
$('#modalButton').click(function(){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
Код: Выделить всё
<?php
$script = <<< JS
$('form#{$model->formName()}').on('beforeSubmit', function(e)
{
var \$form = $(this);
$.post(
\$form.attr("action"), // serialize yii2 form
\$form.serialize()
)
.done(function(result) {
if(result == 1)
{
$(document).find('#modal').modal('hide');
$.pjax.reload({container:'#companyList'});
$(document).on('pjax:complete', function() {
$('#customer-company_id option:last-child').attr('selected', true);
})
}else
{
$(\$form).trigger("reset");
$("#message").html(result.message);
}
}).fail(function()
{
console.log("server error");
});
return false;
});
JS;
$this->registerJs($script);
?>