G
G
gto61202016-10-19 18:48:57
Yii
gto6120, 2016-10-19 18:48:57

How in yii2 can renderPartial be rendered after successfully saving the model?

There is a _form view.

<?php if(!isset($subscribed)) : ?>
        <?php $form = ActiveForm::begin([
            'id' => 'subscribe',
            'action' => Url::toRoute('/subscription'),
            'method' => 'post',
            'enableAjaxValidation' => true,
        ]); ?>
        <div class="input-field">
            <?= $form->field($model, 'email')->textInput(['placeholder' => $model->getAttributeLabel('email')])->label(false); ?>
        </div>
        <div class="text-center">
            <?= Html::submitButton('Подписаться'); ?>
        </div>
        <?php ActiveForm::end(); ?>
<?php else: ?>
     <div>Ура, Вы подписаны!</div>
<?php endif; ?>

There is an action of the Subscription controller that validates the form, and if successful, it must update the _form itself.
public function actionIndex()
    {
        $model = new Model();

        if (Yii::$app->request->isAjax) {
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->renderPartial('_form', ['subscribed' => true]);
            } else {
                \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }
        }

    }

With validation errors, everything is OK, they are shown, and with a successful save of the model, _form is not updated. In the console on the network tab, you can see
<div>Ура, Вы подписаны!</div>
But there is no update.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2016-10-20
@gto6120

You cannot update the form - because you do not do it on the client side.
Now you:
1. Save the model
2. Render _form
3. Send the rendering result to the client, but apparently you do not process or display this result on the client.
Accordingly, you need to:
1. Either write a JS script that will process the response from the server and replace the form with it. Only in this case, I see no reason to use renderPartial to display one line of text, because this functionality can be implemented at the JS
2 level. Either dig towards PJAX
3. Or implement data processing, as slo_nik wrote

D
Dmitry, 2016-10-20
@slo_nik

Good evening. If save()
succeeds , do redirect() , and before that, generate a flash message . In the view, through the Alert widget , show this message.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question