Perino
Perino

Reputation: 628

Yii2: Display Error Messages when using forms inside Pjax

Is it possible to render a normal view including an UserException/ErrorException?

I cannot interrupt the process with

throw new UserException('Error: you did a mistake');

because I need to get back some variables in the few. So, therefore, I have to render the view in a normal way like

return $this->render('view', [
                'model' => $model,
            ]);

Is it possible to create a new UserException like

$exception = new UserException('You did a mistake...');

and include this in rendering the view?

The problem is, I have a view with a pjax element and

Yii::$app->session->setFlash('error', 'You did a mistake...');

is not working. So I'm looking for a way to return an Error Message, while keeping the view normally rendered.

Part of the contoller is:

        if ($quantity_delivered > $ordered_product_quantity){;
            //throw new UserException('Value is not valid!');
            $exception = new UserException('Value is not valid!');
            //todo return error message with rendering the view
            return $this->render('view', [
                'error' => $exception,
                'model_suppliers_orders' => $model_suppliers_orders,
                'dataProvider_suppliers_orders_products' => $dataProvider_suppliers_orders_products,
            ]);
        }

Upvotes: 0

Views: 1597

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23748

I didn't actually understand in the start but you have a view with PJAX wrapper on a form and when you submit the form you want to notify the user if there was an error and sessionFlash won't work at this point.

You can make use of the $this->getView() to register the javascript from within the controller action, and add errors from the model or any other section you like the view by converting the errors to json and then read them using for in loop javascript I am using a normal javascript alert() for the demonstration you can change it to whatever you like.

There is an extension with the name SWEET-ALERT for Yii2 which can become handy for displaying nice user-friendly messages.

I will use Product Model for a demonstration which has name and description field i will only render name field in the form and then submit the form so that it shows me the validation error for the description while trying to save the model.

Your Form should look like below

<?php 
use yii\widgets\Pjax;
use yii\bootstrap\Html;

?>
<?php Pjax::begin(); ?>
<?php 
$form=yii\widgets\ActiveForm::begin(['id'=>'my-form','action'=>'pjax', 'method'=>'post']);

echo $form->field($model , 'name')->textInput();
echo Html::submitButton('submit');
yii\widgets\ActiveForm::end();
?>

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

Your controller/action should look like below

public function actionPjax() {
        $model = new \frontend\models\Product();

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

            if (!$model->save() ) {

                $result = [];
                // The code below comes from ActiveForm::validate(). We do not need to validate the model
                // again, as it was already validated by save(). Just collect the messages.
                foreach ( $model->getErrors () as $attribute => $errors ) {
                    $result[] = $errors;
                }

                $errors=\yii\helpers\Json::encode($result );
                $script=<<<JS
                        var data=$errors;
                        var msg='';
                        for(error in data){
                            msg+=data[error]+"\\n";
                        }
                        alert(msg);
JS;
                $this->getView()->registerJs($script,\yii\web\View::POS_READY);

            }
        }

        return $this->render ( 'pjax' , [
                    'model' => $model
                ] );
    }

Hope this helps you out apart from the above solution if you do not want to show the error messages via javascript or you just want to display the model errors you can still use $form->errorSummary($model) inside the view and it will automatically display the errors, your action will reduce to the following

public function actionPjax() {
        $model = new \frontend\models\Product();

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

            if ($model->save() ) {
               //do something else if saved
            }
        }

        return $this->render ( 'my-form' , [
                    'model' => $model
                ] );
    }

and your form will look like below

<?php 
use yii\widgets\Pjax;
use yii\bootstrap\Html;

?>
<?php Pjax::begin(); ?>
<?php 
$form=yii\widgets\ActiveForm::begin(['id'=>'my-form','action'=>'pjax', 'method'=>'post']);

//display model errors
echo $form->errorSummary($model);

echo $form->field($model , 'name')->textInput();
echo Html::submitButton('submit');
yii\widgets\ActiveForm::end();
?>

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

Upvotes: 1

Related Questions