model = new \app\admin\model\FcArea; } /** * 新增:保存前校验 */ public function add() { $this->assignAreaOptions(); if ($this->request->isPost()) { $this->validateArea($this->request->post('row/a'), 0); } return parent::add(); } /** * 编辑:保存前校验 * @param string $ids */ public function edit($ids = null) { $this->assignAreaOptions(); if ($this->request->isPost()) { $this->validateArea($this->request->post('row/a'), (int)$this->request->param('ids')); } return parent::edit($ids); } /** * 省 / 市 / 区县已添加记录,供表单级联下拉合并全国行政区划及已添加状态标记使用 */ protected function assignAreaOptions() { $rows = Db::name('fc_area') ->field('id,province,city,district,lat,lng') ->order('province asc, city asc, district asc') ->select(); $this->view->assign('areaOptionsJson', json_encode($rows, JSON_UNESCAPED_UNICODE)); } /** * 保存前校验:省 / 市 / 区县均必填,同一组合不可重复 * @param array $params 表单数据 * @param int $id 编辑时的区域ID */ protected function validateArea($params, $id = 0) { $province = isset($params['province']) ? trim((string)$params['province']) : ''; $city = isset($params['city']) ? trim((string)$params['city']) : ''; $district = isset($params['district']) ? trim((string)$params['district']) : ''; $values = ['省份' => $province, '城市' => $city, '区县' => $district]; foreach ($values as $label => $value) { if ($value === '') { $this->error($label . '不能为空'); } if (mb_strlen($value) > 32) { $this->error($label . '不能超过 32 个字符'); } } $duplicate = Db::name('fc_area') ->where('province', $province) ->where('city', $city) ->where('district', $district) ->where('id', '<>', $id) ->find(); if ($duplicate) { $this->error('该省市区组合已存在'); } foreach (['lat' => 90, 'lng' => 180] as $field => $limit) { if (!isset($params[$field]) || $params[$field] === '' || $params[$field] === null) { continue; } if (!is_numeric($params[$field]) || (float)$params[$field] < -$limit || (float)$params[$field] > $limit) { $this->error($field === 'lat' ? '纬度格式不正确' : '经度格式不正确'); } } } }