29

How can i use ActiveForm with these requirements?

  • Submit form with ajax.

  • Before submitting with ajax: Check if error exits.

  • After submitting: Display error of field under field's input if the server responses unsuccess saving result.

Jap Mul
  • 17,398
  • 5
  • 55
  • 66
  • Actually, this is just what Yii already provides with the ActiveForm - including JavaScript to automatic validation on the client before sending data to the server. – robsch Feb 12 '15 at 12:57
  • 2
    @robsch It does not submit the form with AJAX which is what the user is asking. – TheStoryCoder Dec 13 '16 at 16:33

2 Answers2

27

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.

Haru Atari
  • 1,502
  • 2
  • 17
  • 30
  • I need to decide whether I should return false or true based on the Ajax call response. But before the ajax response the return false is getting executed. Please suggest me a way to do it. – Pravinraj Venkatachalam Jan 03 '18 at 06:18
  • @Pravin Ajax is async and you can not return result from its response in general. I do not know javascript well. But you can look for [async/await](https://javascript.info/async-await). May be it will help you. – Haru Atari Jan 11 '18 at 10:44
  • Also see the guide - ajax form submit: https://www.yiiframework.com/doc/guide/2.0/en/input-form-javascript#submitting-the-form-via-ajax – lubosdz Apr 11 '20 at 13:04
10

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>
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
Kalpesh Desai
  • 1,405
  • 15
  • 17