Search code examples
buttonyii2clickconfirm

yii2 button click event precedes data-confirm message


I have used data-confirm attribute with Html::a tags in datagrids and it worked. But now I want to use it with a button like this:

    <?php echo Html::button("<span class='icon delete'></span>", [
        "class" => "delete",
        "title" => Yii::t("app-upload-list", "delete"),
        "data-confirm" => Yii::t("yii", "Are you sure you want to delete this item?"),
    ])

I don't use anchor here because this button doesn't do anything in server-side. But when I attach a click event to the button, it precedes the confirm box. I can get round it by write the confirm code myself in the click event and use a data-my-confirm (or so) attribute to prevent the double confirm boxes, but it is not so nice. Can I do that with data-confirm?


Solution

  • I think you can find an example of something similar to that in the Yii2 template of a View.

    In my view I have the following code:

     <?= Html::a('Delete', ['delete'], [
                'class' => 'btn btn-danger',
                'data' => [
                    'confirm' => 'Are you sure you want to delete this item?',
                    'method' => 'post',
                ],
            ]) ?>
    

    I have to admit that I have not try to use it with Html::button. But you can try something like this:

     <?php echo Html::button("<span class='icon delete'></span>", [
            "class" => "delete",
            "title" => Yii::t("app-upload-list", "delete"),
            "data" => [
                        'confirm' => 'Are you sure you want to delete this item?',
                        'method' => 'post',
                    ],
        ]) ?>
    

    EDIT: Yes, this way do not Work.

    What is recommended is to use a link (Html::a) and style it as you wish. If you want to submit a Form you should use: Html::submitButton()

    If you want to use a button... you can make it work with jQuery as mentioned by Stu here: https://stackoverflow.com/a/12697511/2437857