问题描述
在 fastadmin 框架开发项目中,用到了selectpickers多选组件。
例如:选择了两位员工,但是提交后数据库只保存了一个选择值。
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Owner')}:</label>
<div class="col-xs-12 col-sm-8">
{:Form::selectpickers('row[owner]', $zerenren, $Request.param.owner, ['data-rule'=>''])}
</div>
</div>
原因分析:
组件会提交两个相同name 的值,后台处理时会选择最后一个(后面的覆盖掉前面的)
解决方案:
以数组形式提交到后台,再把数组转成字符串
组件应该这么写:
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Owner')}:</label>
<div class="col-xs-12 col-sm-8">
{:Form::selectpickers('row[owner][]', $zerenren, explode(',',$row.owner), ['data-rule'=>''])}
</div>
</div>
同时第三个参数值(默认选项),也应该是 array(官方文档写的类型是 string),处理成数组就可以正确显示默认值。
后端处理:在 params 后面添加数组转字符串
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'));
}
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);
// 数组转字符串:如果遇到数组的形式,逗号分割
foreach($params as $key=>$val){
if(is_array($val)){
$params[$key] = implode(',',$val);
}else{
continue;
}
}
$result = false;
Db::startTrans();
try {
//是否采用模型验证
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();
}
总结:
selectpickers组件正确的属性应该如下:
官方表单组件链接:https://ask.fastadmin.net/article/5567.html
//下拉列表组件(友好)(多选)
Form::selectpickers(array $name, array $list = [], array $selected =[], array $options = [])