Additional button in Yii2 form submits the form instead of calling its action

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?

It seems, 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, instead of calling its action, when it contains data-method="post" attribute in element code. Is this a bug in Yii2 or am I missing something?

According to Tony’s answer in Stack Overflow, this is a normal. If any additional button contains data-method=post attribute, it will submit form, inside which it is placed.

To "fix" this problem, any additional link or button, that has data-method=post attribute, must be placed outside master form (i.e. <?php ActiveForm::end(); ?> must appear before that link or button element). For example:


	<div class="form-group pull-left">


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


	</div>


<?php ActiveForm::end(); ?>


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


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


	<div class="form-group pull-right">


    	<?= Html::a('Delete photo', ['delete-image', 'lab' => $lab->id, 'kind' => $page->kind], [

        	'class' => 'btn btn-danger',

        	'data' => [

            	'confirm' => 'Are ya sure?',

            	'method' => 'post'

        	],

    	]) ?>


	</div>


<?php endif; ?>

Notice <?php ActiveForm::end(); ?> before <?= Html::a() ?>.