示例问题描述
在dcat-admin 中 grid 使用switch 时,如果修改失败。前端展示的状态是成功的。
正确的方式:应该是操作返回失败,前端展示也不能成功。
非侵入式去修改 扩展包里面的源代码,而是用自己定义的模板文件去覆盖。
switch.blade.php
<input class="grid-column-switch" data-url="{{ $url }}" data-reload="{{ $refresh }}" data-size="small" name="{{ $column }}" {{ $checked }} type="checkbox" data-color="{{ $color }}"/>
<script require="@switchery">
var swt = $('.grid-column-switch'),
that;
function initSwitchery() {
swt.parent().find('.switchery').remove();
swt.each(function () {
that = $(this);
new Switchery(that\[0\], that.data())
})
}
initSwitchery();
swt.off('change').on('change', function(e) {
var that \= $(this),
url \= that.data('url'),
reload \= that.data('reload'),
checked \= that.is(':checked'),
name \= that.attr('name'),
data \= {},
value \= checked ? 1 : 0;
if (name.indexOf('.') === -1) {
data\[name\] = value;
} else {
name \= name.split('.');
data\[name\[0\]\] = {};
data\[name\[0\]\]\[name\[1\]\] = value;
}
Dcat.NP.start();
$.put({
url: url,
data: data,
success: function (d) {
Dcat.NP.done();
var msg \= d.data.message || d.message;
if (d.status) {
Dcat.success(msg);
reload && Dcat.reload();
} else {
Dcat.error(msg);
// 修正追加的代码
that.prop('checked', !that.is(':checked'));
that.parent().find('.switchery').remove();
new Switchery(that\[0\], that.data());
}
}
});
});
</script\>
需要在 app/Providers/AppServiceProvider.php
的 boot
添加如下代码
$customView \= resource\_path('views/switch.blade.php');
if (file\_exists($customView)) {
View::composer('admin::grid.displayer.switch', function ($view) {
// 重新指定视图路径
$view\->setPath(resource\_path('views/switch.blade.php'));
});}
<?php
namespace App\\Providers;
use Illuminate\\Support\\ServiceProvider;
use Illuminate\\Support\\Facades\\View;
class AppServiceProvider extends ServiceProvider
{
/\*\*
\* Register any application services. \*/ public function register(): void
{ //
}
/\*\*
\* Bootstrap any application services. \*/ public function boot(): void
{ // 自己定义的模板文件
$customView \= resource\_path('views/switch.blade.php');
if (file\_exists($customView)) {
View::composer('admin::grid.displayer.switch', function ($view) {
// 重新指定视图路径
$view\->setPath(resource\_path('views/switch.blade.php'));
}); } }}