Не удается показать сообщение об успехе после сохранения данных из yii2 ActiveForm (в модальном режиме)

На главной странице у меня есть кнопка, которая вызывает модальный бутстрап с активной формой. При отправке эта форма добавляет новую строку в мою базу данных. Но я не вижу сообщения об успехе ни в этом модальном окне, ни на главной странице. Вместо этого я попадаю на страницу mysite.ru/category/create с белым экраном и текстом диалогового сообщения на нем ("Содержимое диалога здесь..."). Как не перенаправить пользователя на другую страницу? Просто закройте модальное окно и/или редирект на главной странице и покажите здесь флеш-сообщение об успешном добавлении строки.

моя кнопка в views/site/index.php:

<?= Html::button(
        'create',
        ['value' => Url::to(['category/create']),
            'id' => 'modalButton'

        ]) ?>


    <?php
    Modal::begin([
            'id' => 'modal'
        ]);

    echo "<div id='modalContent'></div>";

    Modal::end();
    ?>

мой контроллер SiteController имеет:

public function actionIndex()
    { 
            return $this->render('index');
    }

КатегорияКонтроллер имеет

public function actionCreate()
        {
            $model = new Category;

            if ($model->load(Yii::$app->request->post()) && Yii::$app->request->isAjax) {
                $model->refresh();
                Yii::$app->response->format = 'json';
                return ActiveForm::validate($model);
            } elseif ($model->load(Yii::$app->request->post()) && $model->save()) {
                Yii::$app->session->setFlash('contactFormSubmitted');
                //$model->refresh();
                $this->refresh();
                Dialog::begin([
                    'clientOptions' => [
                        'modal' => true,
                    ],
                ]);

                echo 'Dialog contents here...';

                Dialog::end();
                //$this->redirect('category/create');

            } else {
                return $this->renderAjax('create', [
                    'model' => $model,
                ]);
            }

просмотры/категория/create.php:

<?php

use yii\helpers\Html;


/* @var $this yii\web\View */
/* @var $model app\models\Category */

$this->title = 'Create Category';
$this->params['breadcrumbs'][] = ['label' => 'Categories', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;

?>
<div class="category-create">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= $this->render('_form', [
        'model' => $model,
    ]) ?>

</div>

и просмотры/категория/_form.php

<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\jui\Dialog;

/* @var $this yii\web\View */
/* @var $model app\models\Category */
/* @var $form yii\widgets\ActiveForm */
?>

<?php
$this->registerJsFile(Yii::getAlias('/scripts/main.js'));

?>

    <?php if (Yii::$app->session->hasFlash('contactFormSubmitted')): ?>

    <div class="alert alert-success">
        Thank you for contacting us. We will respond to you as soon as possible.
    </div>

    <?php endif; ?>



<div class="category-form">

    <?php $form = ActiveForm::begin([
                'id' => $model->formName(),
                //'enableAjaxValidation'=>true,
                'validateOnSubmit'=>true,
                //'action' => '/site/index'
            ]); ?>

    <?= $form->field($model, 'title')->textInput(['maxlength' => 255]) ?>

    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>

    <div class="form-group">
        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
    </div>

    <?php ActiveForm::end(); ?>

</div>

скрипты/main.js:

// listen click, open modal and .load content
$('#modalButton').click(function (){
    $('#modal').modal('show')
        .find('#modalContent')
        .load($(this).attr('value'));
});

// serialize form, render response and close modal
function submitForm($form) {
    $.post(
        $form.attr("action"), // serialize Yii2 form
        $form.serialize()
    )
        .done(function(result) {
            form.parent().replaceWith(result);
                        //$form.parent().html(result.message);
            //$('#modal').modal('hide');
        })
        .fail(function() {
            console.log("server error");
            $form.replaceWith('<button class="newType">Fail</button>').fadeOut()
        });
    return false;
}

person almix    schedule 17.12.2014    source источник


Ответы (1)


Вы должны предотвратить отправку формы и использовать ajax.

            $(your_form)
            .on('beforeSubmit', function(event){ 
                event.preventDefault();
                submitForm($(your_form));

                return false;
            })
            .on('submit', function(event){
                event.preventDefault();
            });
person nicolascolman    schedule 29.06.2017