Laravel-admin下的checkbox复选框编辑表单时默认选中问题

梁浩涆
2023-12-01
1)列表页List
<?php
namespace App\Admin\Controllers\Users;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Models\Users;
/**
  * Make a grid builder.
  *
  * @return Grid
  */
protected function grid()
{

    $grid = new Grid(new Users());
    // 复选框的行内编辑
    $grid->column('hobby')->checkbox(Users::pluck('hobby', 'id'));

    // 复选框显示内容
    $grid->column('hobby', '爱好')->display(function ($roles){
    $hobby = '';
    if(count($roles) > 1){
        foreach ($roles as $k=>$v){
            $hobby .= self::$focus_on_name[$v] .',' ;
        }
        $hobby = rtrim($hobby,',');
    }

    $roles = array_map(function ($role){
        return "<span class='label label-success'>".$role."</span>";
    },explode(',',$hobby));
        return join('&nbsp;',$roles);
    });

    return $grid;
}

/**
  * Make a form builder.
  *
  * @return Form
  */
protected function form()
{
    $form = new Form(new Libraries());
    $form->checkbox('hobby', '爱好')->options(Users::pluck('hobby', 'id'));
}
2)对应模型添加下面字段代码
<?php
namespace App\Models\Users;
class Users extends Model
{
    public function getHobbyAttribute($value)
    {
        return explode(',', $value);
    }

    public function setHobbyAttribute($value)
    {
        $this->attributes['hobby'] = implode(',', $value);
    }
}
 类似资料: