Modal form sent to parent after submit with validation errors


Maybe the title is a little consufsing, but let me explain:

I have a form that is displayed in a Modal window.

In the table for that form I have an uniqueness index for 3 values, these are: ‘product’, ‘invoice’ and ‘wharehouse’, the table is called ‘stock’.

I also have defined the uniqueness rule of this 3 fields in the model.

The problem is when I fill and submit the form with data that I know will trigger the validation error due to the uniqueness rule, in that case when I submit the modal form it will close and be displayed in the parent window, with the validation errors of my custom rule.

The question is how do I prevent the closing of the modal form when the validation error is triggered (as happens for example when I click on submit with all fields empty, the modal doesn’t close and displays the validation errors)

This is what I got so far:

The _form:

    <?php $form = ActiveForm::begin([

        'id' => 'create-stock-form',

        'enableAjaxValidation' => true,

        'validationUrl' => Url::toRoute('stock/validation')

    ]); ?>

The rule in model:

[['insumo_id', 'factura', 'bodega_id'], 'unique', 'targetAttribute' => ['insumo_id', 'factura', 'bodega_id'],

                'message' => 'La combinación de repuesto y factura ya existe en la bodega seleccionada.'],

The controller (same code is also in function actionValidation in same controller):

    public function actionCreate()


        $model = new Stock();

        if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post()))


            Yii::$app->response->format = 'json';

            return ActiveForm::validate($model);


        if ($model->load(Yii::$app->request->post()) && $model->save()) { ...

This is how it looks after submit when the validation rule of uniqueness has errors, the message is correct, but the modal is gone and the form is now in the parent window: