php - Yii2 表单中的附加按钮提交表单而不是调用其操作

标签 php forms yii yii2

我有一个典型的 Yii2 表单,用于使用典型的提交按钮更新我的模型。在它旁边,我有一个“删除照片”按钮,如果有要删除的照片,该按钮就会出现。该 View 看起来像这样:

<?= 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; ?>

当此模型附有照片并且这两个按钮彼此相邻时,我必须注释掉第二个按钮代码中的 'method' => 'post' 部分。因为,如果我不这样做,第二个按钮是...提交表单(就像第一个按钮一样)而不是调用 lab/delete-image 路由。

这是第一件事,我不明白。整个代码要么由 Gii 生成,要么从一些 Yii 教程中复制粘贴。甚至一点都不是我的发明,但它的工作方式却很奇怪。我错过了什么?

看起来,正常的 Html::a 链接(仅由 Twitter Bootstrap 设置为看起来像按钮的样式,但根本不是按钮)当元素代码中包含 data-method="post" 属性 时,提交表单而不是调用其操作。这是 Yii2 中的错误还是我遗漏了什么?

最佳答案

您需要将链接放在表单之外。对于从具有 data-method 属性的元素调用操作,yii 具有 js 函数 handleAction,其文档说:

This method recognizes the data-method attribute of the element. If the attribute exists, the method will submit the form containing this element. If there is no containing form, a form will be created and submitted using the method given by this attribute value (e.g. "post", "put").

For hyperlinks, the form action will take the value of the "href" attribute of the link.

此外,如果您使用 yii2 v2.0.3 或更高版本,您可以添加 data-params 属性,该属性的值应该是数据的 JSON 表示,并且该数据将在请求中提交。例如:

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

在此示例中,params 数组将由 yii2 内部编码为 json

关于php - Yii2 表单中的附加按钮提交表单而不是调用其操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31263563/

相关文章:

php - 用php上传图片到数据库

php - 无法使用 Yii::log 在 linux 中写入日志?

php - 更新数据库而不创建重复项

javascript - Laravel 未定义

python - 使用内置 Python 模块填写 Web 表单数据

php - 尝试通过表单插入数据库时​​出错。 SQLSTATE[42S22]

PHP 执行 ('git' )失败

javascript - DataTables javascript 无法应用于重复表

yii.activeform.js 生成无效验证js脚本

php - 使用我们的自定义类扩展 Yii 框架 CHtml 帮助器类