M
M
Maxim Osadchy2017-10-02 10:47:17
Yii
Maxim Osadchy, 2017-10-02 10:47:17

Why does the button in yii2 work only on the second click?

The View has a button:

<?php $newForm = ActiveForm::begin(); ?>
    <div class="form-group">
        <?= Html::submitButton('Clear',['class'=>'btn btn-danger', 'name' => 'submit', 'value' => 'clear_unique_users_table']) ?>
    </div>
    <?php ActiveForm::end(); ?>

Handler in controller:
if(Yii::$app->request->post('submit')==='clear_unique_users_table'){
            if($uniqueUsersModel->clearTable()){
                return $this->refresh();
            }
        }

The action occurs only after the second click on the button.
What am I doing wrong?
Thank you.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2017-10-02
@waspmax1

You need to look for js that intercepts the click on the button. Apparently you wrote somewhere a click handler with a very general selector, like:

$('button').on('click',finction(e){
e.preventDefault();
//some code
});

Or interception of form submission or something like that. In any case, if the request does not go, then the problem is in js, not in php, and even more so not in the controller.

I
Igor Vasiliev, 2017-10-02
@Isolution666

Hello.
--
To mine a problem in double conditions, two if are strange. I faced a similar situation. You just need to write:

public function actionCleartable() 
{
   $ok = Yii::$app->request->post('submit');
   if(isset($ok)) {
      $uniqueUsersModel->clearTable();
      return $this->refresh();
   } else {
      return $this->render('cleartable');
   }
}

That is, as in the good old nineties, when there was php 4))) We wrote, if the name of the submit button is entered, then this or that happens, if you don’t click, then nothing happens.
The same approach will work if you don't want to use ActiveForm
<?= Html::beginForm(['order/update', 'id' => $id], 'post', ['enctype' => 'multipart/form-data']) ?>
<?= Html::submitButton('Отправить', ['class' => 'submit', 'name' => 'submit']) ?>
<?= Html::endForm() ?>

You can make such forms in at least a dozen on one page, but the one whose name matches the rules prescribed in the controller will work, so I shoved the search form into the top menu without linking each page to a specific model, and there are no errors. The main thing, if you cram input, see an example here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question