Search code examples
yii2pjaxdouble-submit-problem

Yii2 delete action is called twice when the link is clicked


The view that is rendered from the controller has a Pjax begin and end tags:

Pjax::begin([
    'id' => 'pjax-questions-list',
    'enablePushState' => false,
    'clientOptions' => [
        'method' => 'get'
    ],
]);

Inside the Pjax it renders two nested views:

<div class="body">
  <?php
      echo $this->render('_questions_search', ['model' => $searchModel, ' questionary' => $questionary]);
      echo $this->render('_questions_list', ['dataProvider' => $dataProvider, 'model' => $searchModel]);
  ?>
</div>

Inside the nested view there is a delete question link:

<li>
  <a class="waves-effect waves-block" data-pjax="0"
     href="<?= Url::to(['question/delete', 'id' => $model->id]) ?>">Delete</a>
</li>

When that link is clicked, the delete action method is called twice. Moreover, this issue is hard to notice when the Pjax is outside of the view that contains the link (i.e. nested views). Because of this issue the redirect after successfull delete doesn't work and instead a 404 not found error is found (tries to delete the same id twice).

How can i fix the double redirect?


Solution

  • You can fix the double redirect by adding the following attribute to your link which is located inside Pjax:

    data-pjax="0"
    

    In my case i reused the nested view by deleting the grid view and replacing it with ul with links, and of course forgot to remove the unneeded Pjax in the outer view. After that the issue appeared. It was hard to notice that it was calling the action method twice.