Yii2 - ActiveForm ajax submit

How can i use ActiveForm with these requirements?

Upvotes: 29

Views: 61381

Answers (2)

Kalpesh Desai
Kalpesh Desai

Reputation: 1421

Submit form with ajax. Before submitting with ajax: Check if error exits. yii display error if any by default....... :)

use yii\helpers\Html;
use yii\bootstrap\ActiveForm;
use yii\widgets\Pjax;

/* @var $this yii\web\View */
/* @var $model backend\models\search\JobSearch */
/* @var $form yii\bootstrap\ActiveForm */
?>

<div class="job-search">

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        //'method' => 'get',
        'options' => ['id' => 'dynamic-form111']
    ]); ?>

    <?php echo $form->field($searchModel, 'id') ?>

    <?php echo $form->field($searchModel, 'user_id') ?>

    <?php echo $form->field($searchModel, 'com_id') ?>

    <?php echo $form->field($searchModel, 'job_no') ?>

    <?php echo $form->field($searchModel, 'court_id') ?>

    <?php // echo $form->field($model, 'case_no') ?>

    <?php // echo $form->field($model, 'plainttiff') ?>

    <?php // echo $form->field($model, 'defendant') ?>

    <?php // echo $form->field($model, 'date_fill') ?>

    <?php // echo $form->field($model, 'court_date') ?>

    <?php // echo $form->field($model, 'status_id') ?>

    <?php // echo $form->field($model, 'created_at') ?>

    <?php // echo $form->field($model, 'updated_at') ?>

    <div class="form-group">
        <?php echo Html::submitButton('Search', ['class' => 'btn btn-primary','id'=>'submit_id']) ?>
        <?php echo Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
    </div>

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

</div>  
<script type="text/javascript">
    $(document).ready(function () {
        $('body').on('beforeSubmit', 'form#dynamic-form111', function () {
            var form = $(this);
            // return false if form still have some validation errors
            if (form.find('.has-error').length) 
            {
                return false;
            }
            // submit form
            $.ajax({
            url    : form.attr('action'),
            type   : 'get',
            data   : form.serialize(),
            success: function (response) 
            {
                var getupdatedata = $(response).find('#filter_id_test');
                // $.pjax.reload('#note_update_id'); for pjax update
                $('#yiiikap').html(getupdatedata);
                //console.log(getupdatedata);
            },
            error  : function () 
            {
                console.log('internal server error');
            }
            });
            return false;
         });
    });
</script>

Upvotes: 10

Haru Atari
Haru Atari

Reputation: 1732

This is your form in view. I prefer use different actions for validation and saving. You can join them into single method.

<?php $form = \yii\widgets\ActiveForm::begin([
    'id' => 'my-form-id',
    'action' => 'save-url',
    'enableAjaxValidation' => true,
    'validationUrl' => 'validation-rul',
]); ?>

<?= $form->field($model, 'email')->textInput(); ?>

<?= Html::submitButton('Submit'); ?>
<?php $form->end(); ?>

In validation action you should write. It validates your form and returns list of errrs to client. :

public function actionValidate()
{
    $model = new MyModel();
    $request = \Yii::$app->getRequest();
    if ($request->isPost && $model->load($request->post())) {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ActiveForm::validate($model);
    }
}

And this is save action. In validate input data for security:

public function actionSave()
{
    $model = new MyModel();
    $request = \Yii::$app->getRequest();
    if ($request->isPost && $model->load($request->post())) {
        \Yii::$app->response->format = Response::FORMAT_JSON;
        return ['success' => $model->save()];
    }
    return $this->renderAjax('registration', [
        'model' => $model,
    ]);
}

This code will validate your form in actionValidate() and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write:

$(document).on("beforeSubmit", "#my-form-id", function () {
    // send data to actionSave by ajax request.
    return false; // Cancel form submitting.
});

That's all.

Upvotes: 27

Related Questions