Strange behavior of additional button in Yii2 form

I have a typical Yii2 form for updating my model with a typical submit button. Next to it, I have a “Delete photo” button, that appears, if there is any photo to delete. The piece of view looks like that:

<?= Html::submitButton('Save changes', ['class' => 'btn btn-primary', 'name' => 'edit-button']) ?>

<?php $image = isset($page->photo) ? $page->photo->getImageUrl() : null; ?>

<?php if (isset($image)): ?>

    <?= Html::a('Delete photo', ['delete-image', 'lab' => $lab->id, 'kind' => $page->kind], [
        'class' => 'btn btn-danger',
        'data' => [
            'confirm' => 'Do you really want to delete this photo?',
            'method' => 'post'
        ],
    ]) ?>

<?php endif; ?>

When there is a photo attached to this model and these two buttons appear next to each other, I must comment out 'method' => 'post' part in second button code. Because, if I don’t this this, the second button is… submitting the form (just like the first one) instead of calling lab/delete-image route.

This is the first thing, that I don’t understand. The entire code is either generated by Gii or copy-pasted from some Yii tutorials. Not even a bit of my invention and yet it works strangely. What am I missing? How it is possible, that normal Html::a link, only styled by Twitter Bootstrap to look like a button, but not being a button at all, is submitting a form?

In addition, I have a verb definition (also copy-pasted by me from the code auto-generated by Gii) that prevents calling of deleteImage action in any other way than via POST:

public function behaviors()
{
    return [
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'delete' => ['post'],
                'deleteImage' => ['post'],
            ],
        ]
    ];
}

When 'method' => 'post' is commented out and thus (as I assume), lab/delete-image route is called via GET, not POST… action is normally executed instead of throwing a supposed exception.

Why VerbFilter does not prevent execution of delete-image, when it is not called via POST?


Source: forms

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.