多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 工作表表头验证验证器 > 说明: 设置工作表表头验证验证器。在导入表单数据时,对预设验证规则的工作表表头字段数据进行验证。在设定的验证器中可以写字段自定义的验证方法,也可对工作表表头字段数据进行进一步处理(handleData操作)。默认筛选表单字段验证器为 `\yunj\Validate` 方法:`colsValidate($colsValidate)` * 参数 **colsValidate** (必须) * 类型一:callable 闭包 ```php colsValidate(function(){ // 返回`\yunj\Validate`或其子类的实例对象 return new TestValidate(); // 返回`\yunj\Validate`或其子类的全限定类名 return \demo\validate\TestValidate::class; }); ``` * 类型二:string ```php // `\yunj\Validate`或其子类的全限定类名 colsValidate(\demo\validate\TestValidate::class); ``` * 验证环境scene: * `row`:数据导入验证每行数据时的验证环境 注意:`$row["sheet"]` 为当前验证数据行所在工作表,仅在sheet设置时存在。 > 示例: 导入产品数据:`序列号(sn)`、`名称(name)`、`商户(mid)`... * 验证器 ```php namespace app\demo\validate\product; final class Import extends \yunj\Validate { // 自定义验证方法,校验序列号唯一性 protected function snUnique($value,$rule = "",$data){ $isExist = Db::name("product")->where("sn","=",$value)->select(); if($isExist ) return "该序列号已存在"; return true; } protected function handleData(array $rawData, $scene): array { $data = $rawData; switch ($scene) { case "row": // 工作表。仅在sheet设置时存在$data["sheet"] $sheet = $data["sheet"]; // 校验商户有效性,并获取商户数据添加到验证数据里 $merchant = Db::name("merchant")->where("id","=",$data["mid"])->select(); if(!$merchant ) throw_error_json("商户数据错误"); $data["merchant_data"] = $merchant; break; } return $data; } } ``` * 导入构建器: ```php $builder=YI('general_example')->cols(function($sheet){ $cols=[ 'sn'=>['title'=>'序列号','verify'=>'require|snUnique'], 'name'=>['title'=>'名称','verify'=>'require|checkSn','desc'=>'只能输入汉字'], 'mid'=>['title'=>'商户','verify'=>'require|positiveInteger'] ]; return $cols; }) ->colsValidate(\app\demo\validate\product\Import::class) ->row(function($rowData,$sheet){ // $sheet仅在sheet设置时存在其他情况为null // 获取展商数据 $merchant = $rowData["merchant_data"]; // 业务处理... }); ```