Crud.php 50 KB

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