需求:列表为grid页面,需要通过一个批量操作按钮,获取选中的ID,并传给新页面或ajax使用。
1、grid列表增加批量工具按钮
protected function grid()
{
$grid->tools(function ($tools) {
$tools->batch(function ($batch) {
$batch->add('批量获取ID', new TestActions(1));
});
});
return $grid;
}
2、创建按钮操作php文件TestActions.php
namespace App\Admin\Actions\Test;
use Encore\Admin\Grid\Tools\BatchAction;
use Illuminate\Support\Facades\Auth;
class TestActions extends BatchAction
{
protected $action;
public function __construct($action = 1)
{
$this->action = $action;
}
public function script()
{
return <<<EOT
$('{$this->getElementClass()}').on('click', function() {
var ids = $.admin.grid.selected();
onModalShow('#infoDialog', '#ifproject', '/html/index.html?token={$this->getToken()}&ids='+ids)
});
EOT;
}
public function getToken()
{
return Auth::guard('admin')->login(Auth::user());
}
}
效果如图:
有几个地方需要解释下: 这个是获取grid列表的所选id $.admin.grid.selected(); getToken()是给新页面加上验证 以上是按钮直接打开新页面/html/index.html的写法,会弹出新页面,并且带上用逗号拼接的所选择的id列表。
传ids到ajax的方式,只要改写script方法即可:
/**
* 通过传所选id到ajax的方式
*
* @return mixed|string
*/
public function script()
{
return <<<EOT
$('{$this->getElementClass()}').on('click', function() {
$.ajax({
method: 'post',
url: '{$this->resource}/add',
data: {
_token:LA.token,
ids: $.admin.grid.selected(),
action: {$this->action}
},
success: function (data) {
console.log(data);
$('#pjax-container').html(data);
// $.pjax.reload('#pjax-container');
// toastr.success('操作成功');
}
});
});
EOT;
}