后台代码: 自定义 function edit
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
//数据接口,键值=产品id,value=产品名称,为了后面可做匹配
$groupList = \app\admin\model\info\Products::column('id,title');
//字符串转成数组
$products_ids = explode(',', $row['products_ids']);
$selectedGroups = [];
foreach ($groupList as $groupId => $groupName) {
if (in_array($groupId, $products_ids)) {
$selectedGroups[] = $groupId; //选中状态的匹配
}
}
// print_r($groupList);exit;
//这里会自动渲染代码
$this->view->assign('groupList', build_select('row[products_ids][]', $groupList, $selectedGroups, ['class' => 'form-control selectpicker', 'multiple' => 'multiple']));
if (false === $this->request->isPost()) {
$this->view->assign('row', $row);
return $this->view->fetch();
}
$params = $this->request->post('row/a');
if (empty($params)) {
$this->error(__('Parameter %s can not be empty', ''));
}
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
$products_ids = implode(',', $params['products_ids']);
// 将 group_id 数组转换为字符串
$params['products_ids'] = $products_ids;
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException()->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException|PDOException|Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if (false === $result) {
$this->error(__('No rows were updated'));
}
$this->success();
}
前端渲染:
<!-- 采用 fastadmin 原生生成的部分,会出现BUG。
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Products_ids')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-products_ids" data-rule="required" data-multiple="true" data-source="info/products/selectpage" data-multiple="true" class="form-control selectpage" name="row[products_ids]" type="text" value="{$row.products_ids|htmlentities}">
</div>
</div> -->
// 自定义编辑的部分
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Products_ids')}:</label>
<div class="col-xs-12 col-sm-4">
{$groupList}
</div>
</div>