Crud.php 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  1. <?php
  2. namespace app\admin\command;
  3. use fast\Form;
  4. use think\Config;
  5. use think\console\Command;
  6. use think\console\Input;
  7. use think\console\input\Option;
  8. use think\console\Output;
  9. use think\Db;
  10. use think\Exception;
  11. use think\Lang;
  12. class Crud extends Command
  13. {
  14. protected $stubList = [];
  15. /**
  16. * Selectpage搜索字段关联
  17. */
  18. protected $fieldSelectpageMap = [
  19. 'nickname' => ['user_id', 'user_ids', 'admin_id', 'admin_ids']
  20. ];
  21. /**
  22. * Enum类型识别为单选框的结尾字符,默认会识别为单选下拉列表
  23. */
  24. protected $enumRadioSuffix = ['data', 'state', 'status'];
  25. /**
  26. * Set类型识别为复选框的结尾字符,默认会识别为多选下拉列表
  27. */
  28. protected $setCheckboxSuffix = ['data', 'state', 'status'];
  29. /**
  30. * Int类型识别为日期时间的结尾字符,默认会识别为日期文本框
  31. */
  32. protected $intDateSuffix = ['time'];
  33. /**
  34. * 开关后缀
  35. */
  36. protected $switchSuffix = ['switch'];
  37. /**
  38. * 城市后缀
  39. */
  40. protected $citySuffix = ['city'];
  41. /**
  42. * Selectpage对应的后缀
  43. */
  44. protected $selectpageSuffix = ['_id', '_ids'];
  45. /**
  46. * Selectpage多选对应的后缀
  47. */
  48. protected $selectpagesSuffix = ['_ids'];
  49. /**
  50. * 以指定字符结尾的字段格式化函数
  51. */
  52. protected $fieldFormatterSuffix = [
  53. 'status' => ['type' => ['varchar'], 'name' => 'status'],
  54. 'icon' => 'icon',
  55. 'flag' => 'flag',
  56. 'url' => 'url',
  57. 'image' => 'image',
  58. 'images' => 'images',
  59. 'time' => ['type' => ['int', 'timestamp'], 'name' => 'datetime']
  60. ];
  61. /**
  62. * 识别为图片字段
  63. */
  64. protected $imageField = ['image', 'images', 'avatar', 'avatars'];
  65. /**
  66. * 识别为文件字段
  67. */
  68. protected $fileField = ['file', 'files'];
  69. /**
  70. * 保留字段
  71. */
  72. protected $reservedField = ['admin_id', 'createtime', 'updatetime'];
  73. /**
  74. * 排除字段
  75. */
  76. protected $ignoreFields = [];
  77. /**
  78. * 排序字段
  79. */
  80. protected $sortField = 'weigh';
  81. /**
  82. * 编辑器的Class
  83. */
  84. protected $editorClass = 'editor';
  85. protected function configure()
  86. {
  87. $this
  88. ->setName('crud')
  89. ->addOption('table', 't', Option::VALUE_REQUIRED, 'table name without prefix', null)
  90. ->addOption('controller', 'c', Option::VALUE_OPTIONAL, 'controller name', null)
  91. ->addOption('model', 'm', Option::VALUE_OPTIONAL, 'model name', null)
  92. ->addOption('force', 'f', Option::VALUE_OPTIONAL, 'force override', null)
  93. ->addOption('local', 'l', Option::VALUE_OPTIONAL, 'local model', 1)
  94. ->addOption('relation', 'r', Option::VALUE_OPTIONAL, 'relation table name without prefix', null)
  95. ->addOption('relationmodel', 'e', Option::VALUE_OPTIONAL, 'relation model name', null)
  96. ->addOption('relationforeignkey', 'k', Option::VALUE_OPTIONAL, 'relation foreign key', null)
  97. ->addOption('relationprimarykey', 'p', Option::VALUE_OPTIONAL, 'relation primary key', null)
  98. ->addOption('mode', 'o', Option::VALUE_OPTIONAL, 'relation table mode,hasone or belongsto', 'belongsto')
  99. ->addOption('delete', 'd', Option::VALUE_OPTIONAL, 'delete all files generated by CRUD', null)
  100. ->addOption('menu', 'u', Option::VALUE_OPTIONAL, 'create menu when CRUD completed', null)
  101. ->addOption('setcheckboxsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate checkbox component with suffix', null)
  102. ->addOption('enumradiosuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate radio component with suffix', null)
  103. ->addOption('imagefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate image component with suffix', null)
  104. ->addOption('filefield', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate file component with suffix', null)
  105. ->addOption('intdatesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate date component with suffix', null)
  106. ->addOption('switchsuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate switch component with suffix', null)
  107. ->addOption('citysuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate citypicker component with suffix', null)
  108. ->addOption('selectpagesuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate selectpage component with suffix', null)
  109. ->addOption('selectpagessuffix', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'automatically generate multiple selectpage component with suffix', null)
  110. ->addOption('ignorefields', null, Option::VALUE_OPTIONAL | Option::VALUE_IS_ARRAY, 'ignore fields', null)
  111. ->addOption('sortfield', null, Option::VALUE_OPTIONAL, 'sort field', null)
  112. ->addOption('editorclass', null, Option::VALUE_OPTIONAL, 'automatically generate editor class', null)
  113. ->setDescription('Build CRUD controller and model from table');
  114. }
  115. protected function execute(Input $input, Output $output)
  116. {
  117. $adminPath = dirname(__DIR__) . DS;
  118. //表名
  119. $table = $input->getOption('table') ?: '';
  120. //自定义控制器
  121. $controller = $input->getOption('controller');
  122. //自定义模型
  123. $model = $input->getOption('model');
  124. //强制覆盖
  125. $force = $input->getOption('force');
  126. //是否为本地model,为0时表示为全局model将会把model放在app/common/model中
  127. $local = $input->getOption('local');
  128. if (!$table)
  129. {
  130. throw new Exception('table name can\'t empty');
  131. }
  132. //是否生成菜单
  133. $menu = $input->getOption("menu");
  134. //关联表
  135. $relation = $input->getOption('relation');
  136. //自定义关联表模型
  137. $relationModel = $input->getOption('relationmodel');
  138. //模式
  139. $mode = $input->getOption('mode');
  140. //外键
  141. $relationForeignKey = $input->getOption('relationforeignkey');
  142. //主键
  143. $relationPrimaryKey = $input->getOption('relationprimarykey');
  144. //复选框后缀
  145. $setcheckboxsuffix = $input->getOption('setcheckboxsuffix');
  146. //单选框后缀
  147. $enumradiosuffix = $input->getOption('enumradiosuffix');
  148. //图片后缀
  149. $imagefield = $input->getOption('imagefield');
  150. //文件后缀
  151. $filefield = $input->getOption('filefield');
  152. //日期后缀
  153. $intdatesuffix = $input->getOption('intdatesuffix');
  154. //开关后缀
  155. $switchsuffix = $input->getOption('switchsuffix');
  156. //城市后缀
  157. $citysuffix = $input->getOption('citysuffix');
  158. //selectpage后缀
  159. $selectpagesuffix = $input->getOption('selectpagesuffix');
  160. //selectpage多选后缀
  161. $selectpagessuffix = $input->getOption('selectpagessuffix');
  162. //排除字段
  163. $ignoreFields = $input->getOption('ignorefields');
  164. //排序字段
  165. $sortfield = $input->getOption('sortfield');
  166. //编辑器Class
  167. $editorclass = $input->getOption('editorclass');
  168. if ($setcheckboxsuffix)
  169. $this->setCheckboxSuffix = $setcheckboxsuffix;
  170. if ($enumradiosuffix)
  171. $this->enumRadioSuffix = $enumradiosuffix;
  172. if ($imagefield)
  173. $this->imageField = $imagefield;
  174. if ($filefield)
  175. $this->fileField = $filefield;
  176. if ($intdatesuffix)
  177. $this->intDateSuffix = $intdatesuffix;
  178. if ($switchsuffix)
  179. $this->switchSuffix = $switchsuffix;
  180. if ($citysuffix)
  181. $this->citySuffix = $citysuffix;
  182. if ($selectpagesuffix)
  183. $this->selectpageSuffix = $selectpagesuffix;
  184. if ($selectpagessuffix)
  185. $this->selectpagesSuffix = $selectpagessuffix;
  186. if ($ignoreFields)
  187. $this->ignoreFields = $ignoreFields;
  188. if ($editorclass)
  189. $this->editorClass = $editorclass;
  190. if ($sortfield)
  191. $this->sortField = $sortfield;
  192. //如果有启用关联模式
  193. if ($relation && !in_array($mode, ['hasone', 'belongsto']))
  194. {
  195. throw new Exception("relation table only work in hasone or belongsto mode");
  196. }
  197. $dbname = Config::get('database.database');
  198. $prefix = Config::get('database.prefix');
  199. //检查主表
  200. $table = stripos($table, $prefix) === 0 ? substr($table, strlen($prefix)) : $table;
  201. $modelTableName = $tableName = $table;
  202. $modelTableType = 'table';
  203. $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE);
  204. if (!$tableInfo)
  205. {
  206. $tableName = $prefix . $table;
  207. $modelTableType = 'name';
  208. $tableInfo = Db::query("SHOW TABLE STATUS LIKE '{$tableName}'", [], TRUE);
  209. if (!$tableInfo)
  210. {
  211. throw new Exception("table not found");
  212. }
  213. }
  214. $tableInfo = $tableInfo[0];
  215. $relationModelTableName = $relationTableName = $relation;
  216. $relationModelTableType = 'table';
  217. //检查关联表
  218. if ($relation)
  219. {
  220. $relation = stripos($relation, $prefix) === 0 ? substr($relation, strlen($prefix)) : $relation;
  221. $relationModelTableName = $relationTableName = $relation;
  222. $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE);
  223. if (!$relationTableInfo)
  224. {
  225. $relationTableName = $prefix . $relation;
  226. $relationModelTableType = 'name';
  227. $relationTableInfo = Db::query("SHOW TABLE STATUS LIKE '{$relationTableName}'", [], TRUE);
  228. if (!$relationTableInfo)
  229. {
  230. throw new Exception("relation table not found");
  231. }
  232. }
  233. }
  234. //根据表名匹配对应的Fontawesome图标
  235. $iconPath = ROOT_PATH . str_replace('/', DS, '/public/assets/libs/font-awesome/less/variables.less');
  236. $iconName = is_file($iconPath) && stripos(file_get_contents($iconPath), '@fa-var-' . $table . ':') ? 'fa fa-' . $table : 'fa fa-circle-o';
  237. //控制器默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入controller,格式为目录层级
  238. $controller = str_replace('_', '', $controller);
  239. $controllerArr = !$controller ? explode('_', strtolower($table)) : explode('/', strtolower($controller));
  240. $controllerUrl = implode('/', $controllerArr);
  241. $controllerName = ucfirst(array_pop($controllerArr));
  242. $controllerDir = implode(DS, $controllerArr);
  243. $controllerFile = ($controllerDir ? $controllerDir . DS : '') . $controllerName . '.php';
  244. $viewDir = $adminPath . 'view' . DS . $controllerUrl . DS;
  245. //最终将生成的文件路径
  246. $controllerFile = $adminPath . 'controller' . DS . $controllerFile;
  247. $javascriptFile = ROOT_PATH . 'public' . DS . 'assets' . DS . 'js' . DS . 'backend' . DS . $controllerUrl . '.js';
  248. $addFile = $viewDir . 'add.html';
  249. $editFile = $viewDir . 'edit.html';
  250. $indexFile = $viewDir . 'index.html';
  251. $langFile = $adminPath . 'lang' . DS . Lang::detect() . DS . $controllerUrl . '.php';
  252. //模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入model,不支持目录层级
  253. $modelName = $this->getModelName($model, $table);
  254. $modelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $modelName . '.php';
  255. $validateFile = $adminPath . 'validate' . DS . $modelName . '.php';
  256. //关联模型默认以表名进行处理,以下划线进行分隔,如果需要自定义则需要传入relationmodel,不支持目录层级
  257. $relationModelName = $this->getModelName($relationModel, $relation);
  258. $relationModelFile = ($local ? $adminPath : APP_PATH . 'common' . DS) . 'model' . DS . $relationModelName . '.php';
  259. //是否为删除模式
  260. $delete = $input->getOption('delete');
  261. if ($delete)
  262. {
  263. $readyFiles = [$controllerFile, $modelFile, $validateFile, $addFile, $editFile, $indexFile, $langFile, $javascriptFile];
  264. foreach ($readyFiles as $k => $v)
  265. {
  266. $output->warning($v);
  267. }
  268. $output->info("Are you sure you want to delete all those files? Type 'yes' to continue: ");
  269. $line = fgets(STDIN);
  270. if (trim($line) != 'yes')
  271. {
  272. throw new Exception("Operation is aborted!");
  273. }
  274. foreach ($readyFiles as $k => $v)
  275. {
  276. if (file_exists($v))
  277. unlink($v);
  278. }
  279. $output->info("Delete Successed");
  280. return;
  281. }
  282. //非覆盖模式时如果存在控制器文件则报错
  283. if (is_file($controllerFile) && !$force)
  284. {
  285. throw new Exception("controller already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  286. }
  287. //非覆盖模式时如果存在模型文件则报错
  288. if (is_file($modelFile) && !$force)
  289. {
  290. throw new Exception("model already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  291. }
  292. //非覆盖模式时如果存在验证文件则报错
  293. if (is_file($validateFile) && !$force)
  294. {
  295. throw new Exception("validate already exists!\nIf you need to rebuild again, use the parameter --force=true ");
  296. }
  297. require $adminPath . 'common.php';
  298. //从数据库中获取表字段信息
  299. $sql = "SELECT * FROM `information_schema`.`columns` "
  300. . "WHERE TABLE_SCHEMA = ? AND table_name = ? "
  301. . "ORDER BY ORDINAL_POSITION";
  302. $columnList = Db::query($sql, [$dbname, $tableName]);
  303. $relationColumnList = [];
  304. if ($relation)
  305. {
  306. $relationColumnList = Db::query($sql, [$dbname, $relationTableName]);
  307. }
  308. $fieldArr = [];
  309. foreach ($columnList as $k => $v)
  310. {
  311. $fieldArr[] = $v['COLUMN_NAME'];
  312. }
  313. $relationFieldArr = [];
  314. foreach ($relationColumnList as $k => $v)
  315. {
  316. $relationFieldArr[] = $v['COLUMN_NAME'];
  317. }
  318. $addList = [];
  319. $editList = [];
  320. $javascriptList = [];
  321. $langList = [];
  322. $field = 'id';
  323. $order = 'id';
  324. $priDefined = FALSE;
  325. $priKey = '';
  326. $relationPriKey = '';
  327. foreach ($columnList as $k => $v)
  328. {
  329. if ($v['COLUMN_KEY'] == 'PRI')
  330. {
  331. $priKey = $v['COLUMN_NAME'];
  332. break;
  333. }
  334. }
  335. if (!$priKey)
  336. {
  337. throw new Exception('Primary key not found!');
  338. }
  339. if ($relation)
  340. {
  341. foreach ($relationColumnList as $k => $v)
  342. {
  343. if ($v['COLUMN_KEY'] == 'PRI')
  344. {
  345. $relationPriKey = $v['COLUMN_NAME'];
  346. break;
  347. }
  348. }
  349. if (!$relationPriKey)
  350. {
  351. throw new Exception('Relation Primary key not found!');
  352. }
  353. }
  354. $order = $priKey;
  355. //如果是关联模型
  356. if ($relation)
  357. {
  358. if ($mode == 'hasone')
  359. {
  360. $relationForeignKey = $relationForeignKey ? $relationForeignKey : $table . "_id";
  361. $relationPrimaryKey = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
  362. if (!in_array($relationForeignKey, $relationFieldArr))
  363. {
  364. throw new Exception('relation table must be contain field:' . $relationForeignKey);
  365. }
  366. if (!in_array($relationPrimaryKey, $fieldArr))
  367. {
  368. throw new Exception('table must be contain field:' . $relationPrimaryKey);
  369. }
  370. }
  371. else
  372. {
  373. $relationForeignKey = $relationForeignKey ? $relationForeignKey : $relation . "_id";
  374. $relationPrimaryKey = $relationPrimaryKey ? $relationPrimaryKey : $relationPriKey;
  375. if (!in_array($relationForeignKey, $fieldArr))
  376. {
  377. throw new Exception('table must be contain field:' . $relationForeignKey);
  378. }
  379. if (!in_array($relationPrimaryKey, $relationFieldArr))
  380. {
  381. throw new Exception('relation table must be contain field:' . $relationPrimaryKey);
  382. }
  383. }
  384. }
  385. try
  386. {
  387. Form::setEscapeHtml(false);
  388. $setAttrArr = [];
  389. $getAttrArr = [];
  390. $getEnumArr = [];
  391. $appendAttrList = [];
  392. $controllerAssignList = [];
  393. //循环所有字段,开始构造视图的HTML和JS信息
  394. foreach ($columnList as $k => $v)
  395. {
  396. $field = $v['COLUMN_NAME'];
  397. $itemArr = [];
  398. // 这里构建Enum和Set类型的列表数据
  399. if (in_array($v['DATA_TYPE'], ['enum', 'set']))
  400. {
  401. $itemArr = substr($v['COLUMN_TYPE'], strlen($v['DATA_TYPE']) + 1, -1);
  402. $itemArr = explode(',', str_replace("'", '', $itemArr));
  403. $itemArr = $this->getItemArray($itemArr, $field, $v['COLUMN_COMMENT']);
  404. }
  405. // 语言列表
  406. if ($v['COLUMN_COMMENT'] != '')
  407. {
  408. $langList[] = $this->getLangItem($field, $v['COLUMN_COMMENT']);
  409. }
  410. $inputType = '';
  411. //createtime和updatetime是保留字段不能修改和添加
  412. if ($v['COLUMN_KEY'] != 'PRI' && !in_array($field, $this->reservedField) && !in_array($field, $this->ignoreFields))
  413. {
  414. $inputType = $this->getFieldType($v);
  415. // 如果是number类型时增加一个步长
  416. $step = $inputType == 'number' && $v['NUMERIC_SCALE'] > 0 ? "0." . str_repeat(0, $v['NUMERIC_SCALE'] - 1) . "1" : 0;
  417. $attrArr = ['id' => "c-{$field}"];
  418. $cssClassArr = ['form-control'];
  419. $fieldName = "row[{$field}]";
  420. $defaultValue = $v['COLUMN_DEFAULT'];
  421. $editValue = "{\$row.{$field}}";
  422. // 如果默认值非null,则是一个必选项
  423. if ($v['IS_NULLABLE'] == 'NO')
  424. {
  425. $attrArr['data-rule'] = 'required';
  426. }
  427. if ($inputType == 'select')
  428. {
  429. $cssClassArr[] = 'selectpicker';
  430. $attrArr['class'] = implode(' ', $cssClassArr);
  431. if ($v['DATA_TYPE'] == 'set')
  432. {
  433. $attrArr['multiple'] = '';
  434. $fieldName .= "[]";
  435. }
  436. $attrArr['name'] = $fieldName;
  437. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  438. $itemArr = $this->getLangArray($itemArr, FALSE);
  439. //添加一个获取器
  440. $this->getAttr($getAttrArr, $field, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
  441. if ($v['DATA_TYPE'] == 'set')
  442. {
  443. $this->setAttr($setAttrArr, $field, $inputType);
  444. }
  445. $this->appendAttr($appendAttrList, $field);
  446. $formAddElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  447. $formEditElement = $this->getReplacedStub('html/select', ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  448. }
  449. else if ($inputType == 'datetime')
  450. {
  451. $cssClassArr[] = 'datetimepicker';
  452. $attrArr['class'] = implode(' ', $cssClassArr);
  453. $format = "YYYY-MM-DD HH:mm:ss";
  454. $phpFormat = "Y-m-d H:i:s";
  455. $fieldFunc = '';
  456. switch ($v['DATA_TYPE'])
  457. {
  458. case 'year';
  459. $format = "YYYY";
  460. $phpFormat = 'Y';
  461. break;
  462. case 'date';
  463. $format = "YYYY-MM-DD";
  464. $phpFormat = 'Y-m-d';
  465. break;
  466. case 'time';
  467. $format = "HH:mm:ss";
  468. $phpFormat = 'H:i:s';
  469. break;
  470. case 'timestamp';
  471. $fieldFunc = 'datetime';
  472. case 'datetime';
  473. $format = "YYYY-MM-DD HH:mm:ss";
  474. $phpFormat = 'Y-m-d H:i:s';
  475. break;
  476. default:
  477. $fieldFunc = 'datetime';
  478. $this->getAttr($getAttrArr, $field, $inputType);
  479. $this->setAttr($setAttrArr, $field, $inputType);
  480. $this->appendAttr($appendAttrList, $field);
  481. break;
  482. }
  483. $defaultDateTime = "{:date('{$phpFormat}')}";
  484. $attrArr['data-date-format'] = $format;
  485. $attrArr['data-use-current'] = "true";
  486. $fieldFunc = $fieldFunc ? "|{$fieldFunc}" : "";
  487. $formAddElement = Form::text($fieldName, $defaultDateTime, $attrArr);
  488. $formEditElement = Form::text($fieldName, "{\$row.{$field}{$fieldFunc}}", $attrArr);
  489. }
  490. else if ($inputType == 'checkbox' || $inputType == 'radio')
  491. {
  492. unset($attrArr['data-rule']);
  493. $fieldName = $inputType == 'checkbox' ? $fieldName .= "[]" : $fieldName;
  494. $attrArr['name'] = "row[{$fieldName}]";
  495. $this->getEnum($getEnumArr, $controllerAssignList, $field, $itemArr, $inputType);
  496. $itemArr = $this->getLangArray($itemArr, FALSE);
  497. //添加一个获取器
  498. $this->getAttr($getAttrArr, $field, $inputType);
  499. if ($inputType == 'checkbox')
  500. {
  501. $this->setAttr($setAttrArr, $field, $inputType);
  502. }
  503. $this->appendAttr($appendAttrList, $field);
  504. $defaultValue = $inputType == 'radio' && !$defaultValue ? key($itemArr) : $defaultValue;
  505. $formAddElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => $defaultValue]);
  506. $formEditElement = $this->getReplacedStub('html/' . $inputType, ['field' => $field, 'fieldName' => $fieldName, 'fieldList' => $this->getFieldListName($field), 'attrStr' => Form::attributes($attrArr), 'selectedValue' => "\$row.{$field}"]);
  507. }
  508. else if ($inputType == 'textarea')
  509. {
  510. $cssClassArr[] = substr($field, -7) == 'content' ? $this->editorClass : '';
  511. $attrArr['class'] = implode(' ', $cssClassArr);
  512. $attrArr['rows'] = 5;
  513. $formAddElement = Form::textarea($fieldName, $defaultValue, $attrArr);
  514. $formEditElement = Form::textarea($fieldName, $editValue, $attrArr);
  515. }
  516. else if ($inputType == 'switch')
  517. {
  518. unset($attrArr['data-rule']);
  519. if ($defaultValue === '1' || $defaultValue === 'Y')
  520. {
  521. $yes = $defaultValue;
  522. $no = $defaultValue === '1' ? '0' : 'N';
  523. }
  524. else
  525. {
  526. $no = $defaultValue;
  527. $yes = $defaultValue === '0' ? '1' : 'Y';
  528. }
  529. $formAddElement = $formEditElement = Form::hidden($fieldName, $no, array_merge(['checked' => ''], $attrArr));
  530. $attrArr['id'] = $fieldName . "-switch";
  531. $formAddElement .= sprintf(Form::label("{$attrArr['id']}", "%s {:__('Yes')}", ['class'=>'control-label']), Form::checkbox($fieldName, $yes, $defaultValue === $yes, $attrArr));
  532. $formEditElement .= sprintf(Form::label("{$attrArr['id']}", "%s {:__('Yes')}", ['class'=>'control-label']), Form::checkbox($fieldName, $yes, 0, $attrArr));
  533. $formEditElement = str_replace('type="checkbox"', 'type="checkbox" {in name="' . "\$row.{$field}" . '" value="' . $yes . '"}checked{/in}', $formEditElement);
  534. }
  535. else if ($inputType == 'citypicker')
  536. {
  537. $attrArr['class'] = implode(' ', $cssClassArr);
  538. $attrArr['data-toggle'] = "city-picker";
  539. $formAddElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $defaultValue, $attrArr));
  540. $formEditElement = sprintf("<div class='control-relative'>%s</div>", Form::input('text', $fieldName, $editValue, $attrArr));
  541. }
  542. else
  543. {
  544. $search = $replace = '';
  545. //特殊字段为关联搜索
  546. if ($this->isMatchSuffix($field, $this->selectpageSuffix))
  547. {
  548. $inputType = 'text';
  549. $defaultValue = '';
  550. $attrArr['data-rule'] = 'required';
  551. $cssClassArr[] = 'selectpage';
  552. $selectpageController = str_replace('_', '/', substr($field, 0, strripos($field, '_')));
  553. $attrArr['data-source'] = $selectpageController . "/index";
  554. //如果是类型表需要特殊处理下
  555. if ($selectpageController == 'category')
  556. {
  557. $attrArr['data-source'] = 'category/selectpage';
  558. $attrArr['data-params'] = '##replacetext##';
  559. $search = '"##replacetext##"';
  560. $replace = '\'{"custom[type]":"' . $table . '"}\'';
  561. }
  562. if ($this->isMatchSuffix($field, $this->selectpagesSuffix))
  563. {
  564. $attrArr['data-multiple'] = 'true';
  565. }
  566. foreach ($this->fieldSelectpageMap as $m => $n)
  567. {
  568. if (in_array($field, $n))
  569. {
  570. $attrArr['data-field'] = $m;
  571. break;
  572. }
  573. }
  574. }
  575. //因为有自动完成可输入其它内容
  576. $step = array_intersect($cssClassArr, ['selectpage']) ? 0 : $step;
  577. $attrArr['class'] = implode(' ', $cssClassArr);
  578. $isUpload = false;
  579. if ($this->isMatchSuffix($field, array_merge($this->imageField, $this->fileField)))
  580. {
  581. $isUpload = true;
  582. }
  583. //如果是步长则加上步长
  584. if ($step)
  585. {
  586. $attrArr['step'] = $step;
  587. }
  588. //如果是图片加上个size
  589. if ($isUpload)
  590. {
  591. $attrArr['size'] = 50;
  592. }
  593. $formAddElement = Form::input($inputType, $fieldName, $defaultValue, $attrArr);
  594. $formEditElement = Form::input($inputType, $fieldName, $editValue, $attrArr);
  595. if ($search && $replace)
  596. {
  597. $formAddElement = str_replace($search, $replace, $formAddElement);
  598. $formEditElement = str_replace($search, $replace, $formEditElement);
  599. }
  600. //如果是图片或文件
  601. if ($isUpload)
  602. {
  603. $formAddElement = $this->getImageUpload($field, $formAddElement);
  604. $formEditElement = $this->getImageUpload($field, $formEditElement);
  605. }
  606. }
  607. //构造添加和编辑HTML信息
  608. $addList[] = $this->getFormGroup($field, $formAddElement);
  609. $editList[] = $this->getFormGroup($field, $formEditElement);
  610. }
  611. //过滤text类型字段
  612. if ($v['DATA_TYPE'] != 'text')
  613. {
  614. //主键
  615. if ($v['COLUMN_KEY'] == 'PRI' && !$priDefined)
  616. {
  617. $priDefined = TRUE;
  618. $javascriptList[] = "{checkbox: true}";
  619. }
  620. //构造JS列信息
  621. $javascriptList[] = $this->getJsColumn($field, $v['DATA_TYPE'], $inputType && in_array($inputType, ['select', 'checkbox', 'radio']) ? '_text' : '', $itemArr);
  622. //排序方式,如果有指定排序字段,否则按主键排序
  623. $order = $field == $this->sortField ? $this->sortField : $order;
  624. }
  625. }
  626. $relationPriKey = 'id';
  627. $relationFieldArr = [];
  628. foreach ($relationColumnList as $k => $v)
  629. {
  630. $relationField = $v['COLUMN_NAME'];
  631. $relationFieldArr[] = $field;
  632. $relationField = strtolower($relationModelName) . "." . $relationField;
  633. // 语言列表
  634. if ($v['COLUMN_COMMENT'] != '')
  635. {
  636. $langList[] = $this->getLangItem($relationField, $v['COLUMN_COMMENT']);
  637. }
  638. //过滤text类型字段
  639. if ($v['DATA_TYPE'] != 'text')
  640. {
  641. //构造JS列信息
  642. $javascriptList[] = $this->getJsColumn($relationField, $v['DATA_TYPE']);
  643. }
  644. }
  645. //JS最后一列加上操作列
  646. $javascriptList[] = str_repeat(" ", 24) . "{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}";
  647. $addList = implode("\n", array_filter($addList));
  648. $editList = implode("\n", array_filter($editList));
  649. $javascriptList = implode(",\n", array_filter($javascriptList));
  650. $langList = implode(",\n", array_filter($langList));
  651. //表注释
  652. $tableComment = $tableInfo['Comment'];
  653. $tableComment = mb_substr($tableComment, -1) == '表' ? mb_substr($tableComment, 0, -1) . '管理' : $tableComment;
  654. $appNamespace = Config::get('app_namespace');
  655. $moduleName = 'admin';
  656. $controllerNamespace = "{$appNamespace}\\{$moduleName}\\controller" . ($controllerDir ? "\\" : "") . str_replace('/', "\\", $controllerDir);
  657. $modelNamespace = "{$appNamespace}\\" . ($local ? $moduleName : "common") . "\\model";
  658. $validateNamespace = "{$appNamespace}\\" . $moduleName . "\\validate";
  659. $validateName = $modelName;
  660. $modelInit = '';
  661. if ($priKey != $order)
  662. {
  663. $modelInit = $this->getReplacedStub('mixins' . DS . 'modelinit', ['order' => $order]);
  664. }
  665. $data = [
  666. 'controllerNamespace' => $controllerNamespace,
  667. 'modelNamespace' => $modelNamespace,
  668. 'validateNamespace' => $validateNamespace,
  669. 'controllerUrl' => $controllerUrl,
  670. 'controllerDir' => $controllerDir,
  671. 'controllerName' => $controllerName,
  672. 'controllerAssignList' => implode("\n", $controllerAssignList),
  673. 'modelName' => $modelName,
  674. 'validateName' => $validateName,
  675. 'tableComment' => $tableComment,
  676. 'iconName' => $iconName,
  677. 'pk' => $priKey,
  678. 'order' => $order,
  679. 'table' => $table,
  680. 'tableName' => $tableName,
  681. 'addList' => $addList,
  682. 'editList' => $editList,
  683. 'javascriptList' => $javascriptList,
  684. 'langList' => $langList,
  685. 'modelAutoWriteTimestamp' => in_array('createtime', $fieldArr) || in_array('updatetime', $fieldArr) ? "'int'" : 'false',
  686. 'createTime' => in_array('createtime', $fieldArr) ? "'createtime'" : 'false',
  687. 'updateTime' => in_array('updatetime', $fieldArr) ? "'updatetime'" : 'false',
  688. 'modelTableName' => $modelTableName,
  689. 'modelTableType' => $modelTableType,
  690. 'relationModelTableName' => $relationModelTableName,
  691. 'relationModelTableType' => $relationModelTableType,
  692. 'relationModelName' => $relationModelName,
  693. 'relationWith' => '',
  694. 'relationMethod' => '',
  695. 'relationModel' => '',
  696. 'relationForeignKey' => '',
  697. 'relationPrimaryKey' => '',
  698. 'relationSearch' => $relation ? 'true' : 'false',
  699. 'controllerIndex' => '',
  700. 'appendAttrList' => implode(",\n", $appendAttrList),
  701. 'getEnumList' => implode("\n\n", $getEnumArr),
  702. 'getAttrList' => implode("\n\n", $getAttrArr),
  703. 'setAttrList' => implode("\n\n", $setAttrArr),
  704. 'modelInit' => $modelInit,
  705. 'modelRelationMethod' => '',
  706. ];
  707. //如果使用关联模型
  708. if ($relation)
  709. {
  710. //需要构造关联的方法
  711. $data['relationMethod'] = strtolower($relationModelName);
  712. //预载入的方法
  713. $data['relationWith'] = "->with('{$data['relationMethod']}')";
  714. //需要重写index方法
  715. $data['controllerIndex'] = $this->getReplacedStub('controllerindex', $data);
  716. //关联的模式
  717. $data['relationMode'] = $mode == 'hasone' ? 'hasOne' : 'belongsTo';
  718. //关联字段
  719. $data['relationForeignKey'] = $relationForeignKey;
  720. $data['relationPrimaryKey'] = $relationPrimaryKey ? $relationPrimaryKey : $priKey;
  721. //构造关联模型的方法
  722. $data['modelRelationMethod'] = $this->getReplacedStub('mixins' . DS . 'modelrelationmethod', $data);
  723. }
  724. // 生成控制器文件
  725. $result = $this->writeToFile('controller', $data, $controllerFile);
  726. // 生成模型文件
  727. $result = $this->writeToFile('model', $data, $modelFile);
  728. if ($relation && !is_file($relationModelFile))
  729. {
  730. // 生成关联模型文件
  731. $result = $this->writeToFile('relationmodel', $data, $relationModelFile);
  732. }
  733. // 生成验证文件
  734. $result = $this->writeToFile('validate', $data, $validateFile);
  735. // 生成视图文件
  736. $result = $this->writeToFile('add', $data, $addFile);
  737. $result = $this->writeToFile('edit', $data, $editFile);
  738. $result = $this->writeToFile('index', $data, $indexFile);
  739. // 生成JS文件
  740. $result = $this->writeToFile('javascript', $data, $javascriptFile);
  741. // 生成语言文件
  742. if ($langList)
  743. {
  744. $result = $this->writeToFile('lang', $data, $langFile);
  745. }
  746. }
  747. catch (\think\exception\ErrorException $e)
  748. {
  749. throw new Exception("Code: " . $e->getCode() . "\nLine: " . $e->getLine() . "\nMessage: " . $e->getMessage() . "\nFile: " . $e->getFile());
  750. }
  751. //继续生成菜单
  752. if ($menu)
  753. {
  754. exec("php think menu -c {$controllerUrl}");
  755. }
  756. $output->info("Build Successed");
  757. }
  758. protected function getEnum(&$getEnum, &$controllerAssignList, $field, $itemArr = '', $inputType = '')
  759. {
  760. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  761. return;
  762. $fieldList = $this->getFieldListName($field);
  763. $methodName = 'get' . ucfirst($fieldList);
  764. foreach ($itemArr as $k => &$v)
  765. {
  766. $v = "__('" . mb_ucfirst($v) . "')";
  767. }
  768. unset($v);
  769. $itemString = $this->getArrayString($itemArr);
  770. $getEnum[] = <<<EOD
  771. public function {$methodName}()
  772. {
  773. return [{$itemString}];
  774. }
  775. EOD;
  776. $controllerAssignList[] = <<<EOD
  777. \$this->view->assign("{$fieldList}", \$this->model->{$methodName}());
  778. EOD;
  779. }
  780. protected function getAttr(&$getAttr, $field, $inputType = '')
  781. {
  782. if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
  783. return;
  784. $attrField = ucfirst($this->getCamelizeName($field));
  785. $getAttr[] = $this->getReplacedStub("mixins" . DS . $inputType, ['field' => $field, 'methodName' => "get{$attrField}TextAttr", 'listMethodName' => "get{$attrField}List"]);
  786. }
  787. protected function setAttr(&$setAttr, $field, $inputType = '')
  788. {
  789. if (!in_array($inputType, ['datetime', 'checkbox', 'select']))
  790. return;
  791. $attrField = ucfirst($this->getCamelizeName($field));
  792. if ($inputType == 'datetime')
  793. {
  794. $return = <<<EOD
  795. return \$value && !is_numeric(\$value) ? strtotime(\$value) : \$value;
  796. EOD;
  797. }
  798. else if (in_array($inputType, ['checkbox', 'select']))
  799. {
  800. $return = <<<EOD
  801. return is_array(\$value) ? implode(',', \$value) : \$value;
  802. EOD;
  803. }
  804. $setAttr[] = <<<EOD
  805. protected function set{$attrField}Attr(\$value)
  806. {
  807. $return
  808. }
  809. EOD;
  810. }
  811. protected function appendAttr(&$appendAttrList, $field)
  812. {
  813. $appendAttrList[] = <<<EOD
  814. '{$field}_text'
  815. EOD;
  816. }
  817. protected function getModelName($model, $table)
  818. {
  819. if (!$model)
  820. {
  821. $modelarr = explode('_', strtolower($table));
  822. foreach ($modelarr as $k => &$v)
  823. $v = ucfirst($v);
  824. unset($v);
  825. $modelName = implode('', $modelarr);
  826. }
  827. else
  828. {
  829. $modelName = ucfirst($model);
  830. }
  831. return $modelName;
  832. }
  833. /**
  834. * 写入到文件
  835. * @param string $name
  836. * @param array $data
  837. * @param string $pathname
  838. * @return mixed
  839. */
  840. protected function writeToFile($name, $data, $pathname)
  841. {
  842. $content = $this->getReplacedStub($name, $data);
  843. if (!is_dir(dirname($pathname)))
  844. {
  845. mkdir(strtolower(dirname($pathname)), 0755, true);
  846. }
  847. return file_put_contents($pathname, $content);
  848. }
  849. /**
  850. * 获取替换后的数据
  851. * @param string $name
  852. * @param array $data
  853. * @return string
  854. */
  855. protected function getReplacedStub($name, $data)
  856. {
  857. $search = $replace = [];
  858. foreach ($data as $k => $v)
  859. {
  860. $search[] = "{%{$k}%}";
  861. $replace[] = $v;
  862. }
  863. $stubname = $this->getStub($name);
  864. if (isset($this->stubList[$stubname]))
  865. {
  866. $stub = $this->stubList[$stubname];
  867. }
  868. else
  869. {
  870. $this->stubList[$stubname] = $stub = file_get_contents($stubname);
  871. }
  872. $content = str_replace($search, $replace, $stub);
  873. return $content;
  874. }
  875. /**
  876. * 获取基础模板
  877. * @param string $name
  878. * @return string
  879. */
  880. protected function getStub($name)
  881. {
  882. return __DIR__ . DS . 'Crud' . DS . 'stubs' . DS . $name . '.stub';
  883. }
  884. protected function getLangItem($field, $content)
  885. {
  886. if ($content || !Lang::has($field))
  887. {
  888. $itemArr = [];
  889. $content = str_replace(',', ',', $content);
  890. if (stripos($content, ':') !== false && stripos($content, ',') && stripos($content, '=') !== false)
  891. {
  892. list($fieldLang, $item) = explode(':', $content);
  893. $itemArr = [$field => $fieldLang];
  894. foreach (explode(',', $item) as $k => $v)
  895. {
  896. $valArr = explode('=', $v);
  897. if (count($valArr) == 2)
  898. {
  899. list($key, $value) = $valArr;
  900. $itemArr[$field . ' ' . $key] = $value;
  901. }
  902. }
  903. }
  904. else
  905. {
  906. $itemArr = [$field => $content];
  907. }
  908. $resultArr = [];
  909. foreach ($itemArr as $k => $v)
  910. {
  911. $resultArr[] = " '" . mb_ucfirst($k) . "' => '{$v}'";
  912. }
  913. return implode(",\n", $resultArr);
  914. }
  915. else
  916. {
  917. return '';
  918. }
  919. }
  920. /**
  921. * 读取数据和语言数组列表
  922. * @param array $arr
  923. * @param boolean $withTpl
  924. * @return array
  925. */
  926. protected function getLangArray($arr, $withTpl = TRUE)
  927. {
  928. $langArr = [];
  929. foreach ($arr as $k => $v)
  930. {
  931. $langArr[$k] = is_numeric($k) ? ($withTpl ? "{:" : "") . "__('" . mb_ucfirst($v) . "')" . ($withTpl ? "}" : "") : $v;
  932. }
  933. return $langArr;
  934. }
  935. /**
  936. * 将数据转换成带字符串
  937. * @param array $arr
  938. * @return string
  939. */
  940. protected function getArrayString($arr)
  941. {
  942. if (!is_array($arr))
  943. return $arr;
  944. $stringArr = [];
  945. foreach ($arr as $k => $v)
  946. {
  947. $is_var = in_array(substr($v, 0, 1), ['$', '_']);
  948. if (!$is_var)
  949. {
  950. $v = str_replace("'", "\'", $v);
  951. $k = str_replace("'", "\'", $k);
  952. }
  953. $stringArr[] = "'" . $k . "' => " . ($is_var ? $v : "'{$v}'");
  954. }
  955. return implode(",", $stringArr);
  956. }
  957. protected function getItemArray($item, $field, $comment)
  958. {
  959. $itemArr = [];
  960. $comment = str_replace(',', ',', $comment);
  961. if (stripos($comment, ':') !== false && stripos($comment, ',') && stripos($comment, '=') !== false)
  962. {
  963. list($fieldLang, $item) = explode(':', $comment);
  964. $itemArr = [];
  965. foreach (explode(',', $item) as $k => $v)
  966. {
  967. $valArr = explode('=', $v);
  968. if (count($valArr) == 2)
  969. {
  970. list($key, $value) = $valArr;
  971. $itemArr[$key] = $field . ' ' . $key;
  972. }
  973. }
  974. }
  975. else
  976. {
  977. foreach ($item as $k => $v)
  978. {
  979. $itemArr[$v] = is_numeric($v) ? $field . ' ' . $v : $v;
  980. }
  981. }
  982. return $itemArr;
  983. }
  984. protected function getFieldType(& $v)
  985. {
  986. $inputType = 'text';
  987. switch ($v['DATA_TYPE'])
  988. {
  989. case 'bigint':
  990. case 'int':
  991. case 'mediumint':
  992. case 'smallint':
  993. case 'tinyint':
  994. $inputType = 'number';
  995. break;
  996. case 'enum':
  997. case 'set':
  998. $inputType = 'select';
  999. break;
  1000. case 'decimal':
  1001. case 'double':
  1002. case 'float':
  1003. $inputType = 'number';
  1004. break;
  1005. case 'longtext':
  1006. case 'text':
  1007. case 'mediumtext':
  1008. case 'smalltext':
  1009. case 'tinytext':
  1010. $inputType = 'textarea';
  1011. break;
  1012. case 'year';
  1013. case 'date';
  1014. case 'time';
  1015. case 'datetime';
  1016. case 'timestamp';
  1017. $inputType = 'datetime';
  1018. break;
  1019. default:
  1020. break;
  1021. }
  1022. $fieldsName = $v['COLUMN_NAME'];
  1023. // 指定后缀说明也是个时间字段
  1024. if ($this->isMatchSuffix($fieldsName, $this->intDateSuffix))
  1025. {
  1026. $inputType = 'datetime';
  1027. }
  1028. // 指定后缀结尾且类型为enum,说明是个单选框
  1029. if ($this->isMatchSuffix($fieldsName, $this->enumRadioSuffix) && $v['DATA_TYPE'] == 'enum')
  1030. {
  1031. $inputType = "radio";
  1032. }
  1033. // 指定后缀结尾且类型为set,说明是个复选框
  1034. if ($this->isMatchSuffix($fieldsName, $this->setCheckboxSuffix) && $v['DATA_TYPE'] == 'set')
  1035. {
  1036. $inputType = "checkbox";
  1037. }
  1038. // 指定后缀结尾且类型为char或tinyint且长度为1,说明是个Switch复选框
  1039. if ($this->isMatchSuffix($fieldsName, $this->switchSuffix) && ($v['COLUMN_TYPE'] == 'tinyint(1)' || $v['COLUMN_TYPE'] == 'char(1)') && $v['COLUMN_DEFAULT'] !== '' && $v['COLUMN_DEFAULT'] !== null)
  1040. {
  1041. $inputType = "switch";
  1042. }
  1043. // 指定后缀结尾城市选择框
  1044. if ($this->isMatchSuffix($fieldsName, $this->citySuffix) && ($v['DATA_TYPE'] == 'varchar' || $v['DATA_TYPE'] == 'char'))
  1045. {
  1046. $inputType = "citypicker";
  1047. }
  1048. return $inputType;
  1049. }
  1050. /**
  1051. * 判断是否符合指定后缀
  1052. * @param string $field 字段名称
  1053. * @param mixed $suffixArr 后缀
  1054. * @return boolean
  1055. */
  1056. protected function isMatchSuffix($field, $suffixArr)
  1057. {
  1058. $suffixArr = is_array($suffixArr) ? $suffixArr : explode(',', $suffixArr);
  1059. foreach ($suffixArr as $k => $v)
  1060. {
  1061. if (preg_match("/{$v}$/i", $field))
  1062. {
  1063. return true;
  1064. }
  1065. }
  1066. return false;
  1067. }
  1068. /**
  1069. * 获取表单分组数据
  1070. * @param string $field
  1071. * @param string $content
  1072. * @return string
  1073. */
  1074. protected function getFormGroup($field, $content)
  1075. {
  1076. $langField = mb_ucfirst($field);
  1077. return<<<EOD
  1078. <div class="form-group">
  1079. <label for="c-{$field}" class="control-label col-xs-12 col-sm-2">{:__('{$langField}')}:</label>
  1080. <div class="col-xs-12 col-sm-8">
  1081. {$content}
  1082. </div>
  1083. </div>
  1084. EOD;
  1085. }
  1086. /**
  1087. * 获取图片模板数据
  1088. * @param string $field
  1089. * @param string $content
  1090. * @return array
  1091. */
  1092. protected function getImageUpload($field, $content)
  1093. {
  1094. $uploadfilter = $selectfilter = '';
  1095. if ($this->isMatchSuffix($field, $this->imageField))
  1096. {
  1097. $uploadfilter = ' data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp"';
  1098. $selectfilter = ' data-mimetype="image/*"';
  1099. }
  1100. $multiple = substr($field, -1) == 's' ? ' data-multiple="true"' : ' data-multiple="false"';
  1101. $preview = $uploadfilter ? ' data-preview-id="p-' . $field . '"' : '';
  1102. $previewcontainer = $preview ? '<ul class="row list-inline plupload-preview" id="p-' . $field . '"></ul>' : '';
  1103. return <<<EOD
  1104. <div class="input-group">
  1105. {$content}
  1106. <div class="input-group-addon no-border no-padding">
  1107. <span><button type="button" id="plupload-{$field}" class="btn btn-danger plupload" data-input-id="c-{$field}"{$uploadfilter}{$multiple}{$preview}><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
  1108. <span><button type="button" id="fachoose-{$field}" class="btn btn-primary fachoose" data-input-id="c-{$field}"{$selectfilter}{$multiple}><i class="fa fa-list"></i> {:__('Choose')}</button></span>
  1109. </div>
  1110. <span class="msg-box n-right" for="c-{$field}"></span>
  1111. </div>
  1112. {$previewcontainer}
  1113. EOD;
  1114. }
  1115. /**
  1116. * 获取JS列数据
  1117. * @param string $field
  1118. * @param string $datatype
  1119. * @param string $extend
  1120. * @param array $itemArr
  1121. * @return string
  1122. */
  1123. protected function getJsColumn($field, $datatype = '', $extend = '', $itemArr = [])
  1124. {
  1125. $lang = mb_ucfirst($field);
  1126. $formatter = '';
  1127. foreach ($this->fieldFormatterSuffix as $k => $v)
  1128. {
  1129. if (preg_match("/{$k}$/i", $field))
  1130. {
  1131. if (is_array($v))
  1132. {
  1133. if (in_array($datatype, $v['type']))
  1134. {
  1135. $formatter = $v['name'];
  1136. break;
  1137. }
  1138. }
  1139. else
  1140. {
  1141. $formatter = $v;
  1142. break;
  1143. }
  1144. }
  1145. }
  1146. if ($formatter)
  1147. {
  1148. $extend = '';
  1149. }
  1150. $html = str_repeat(" ", 24) . "{field: '{$field}{$extend}', title: __('{$lang}')";
  1151. //$formatter = $extend ? '' : $formatter;
  1152. if ($extend)
  1153. {
  1154. $html .= ", operate:false";
  1155. if ($datatype == 'set')
  1156. {
  1157. $formatter = 'label';
  1158. }
  1159. }
  1160. foreach ($itemArr as $k => &$v)
  1161. {
  1162. if (substr($v, 0, 3) !== '__(')
  1163. $v = "__('" . $v . "')";
  1164. }
  1165. unset($v);
  1166. $searchList = json_encode($itemArr, JSON_FORCE_OBJECT);
  1167. $searchList = str_replace(['":"', '"}', ')","'], ['":', '}', '),"'], $searchList);
  1168. if ($itemArr && !$extend)
  1169. {
  1170. $html .= ", searchList: " . $searchList;
  1171. }
  1172. if (in_array($datatype, ['date', 'datetime']) || $formatter === 'datetime')
  1173. {
  1174. $html .= ", operate:'RANGE', addclass:'datetimerange'";
  1175. }
  1176. else if (in_array($datatype, ['float', 'double', 'decimal']))
  1177. {
  1178. $html .= ", operate:'BETWEEN'";
  1179. }
  1180. if ($formatter)
  1181. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1182. else
  1183. $html .= "}";
  1184. if ($extend)
  1185. {
  1186. $origin = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}'), visible:false";
  1187. if ($searchList)
  1188. {
  1189. $origin .= ", searchList: " . $searchList;
  1190. }
  1191. $origin .= "}";
  1192. $html = $origin . ",\n" . $html;
  1193. }
  1194. return $html;
  1195. }
  1196. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1197. {
  1198. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1199. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1200. }
  1201. protected function getFieldListName($field)
  1202. {
  1203. return $this->getCamelizeName($field) . 'List';
  1204. }
  1205. }