Crud.php 48 KB

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