Crud.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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 = "__('" . 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[] = " '" . 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 ? "{:" : "") . "__('" . 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 = 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="form-inline">
  1079. {$content}
  1080. <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>
  1081. <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>
  1082. <span class="msg-box n-right" for="c-{$field}"></span>
  1083. {$previewcontainer}
  1084. </div>
  1085. EOD;
  1086. }
  1087. /**
  1088. * 获取JS列数据
  1089. * @param string $field
  1090. * @return string
  1091. */
  1092. protected function getJsColumn($field, $datatype = '', $extend = '')
  1093. {
  1094. $lang = ucfirst($field);
  1095. $formatter = '';
  1096. foreach ($this->fieldFormatterSuffix as $k => $v)
  1097. {
  1098. if (preg_match("/{$k}$/i", $field))
  1099. {
  1100. if (is_array($v))
  1101. {
  1102. if (in_array($datatype, $v['type']))
  1103. {
  1104. $formatter = $v['name'];
  1105. break;
  1106. }
  1107. }
  1108. else
  1109. {
  1110. $formatter = $v;
  1111. break;
  1112. }
  1113. }
  1114. }
  1115. if ($formatter)
  1116. {
  1117. $extend = '';
  1118. }
  1119. $html = str_repeat(" ", 24) . "{field: '{$field}{$extend}', title: __('{$lang}')";
  1120. //$formatter = $extend ? '' : $formatter;
  1121. if ($extend)
  1122. {
  1123. $html .= ", operate:false";
  1124. if ($datatype == 'set')
  1125. {
  1126. $formatter = 'label';
  1127. }
  1128. }
  1129. if ($formatter)
  1130. $html .= ", formatter: Table.api.formatter." . $formatter . "}";
  1131. else
  1132. $html .= "}";
  1133. return $html;
  1134. }
  1135. protected function getCamelizeName($uncamelized_words, $separator = '_')
  1136. {
  1137. $uncamelized_words = $separator . str_replace($separator, " ", strtolower($uncamelized_words));
  1138. return ltrim(str_replace(" ", "", ucwords($uncamelized_words)), $separator);
  1139. }
  1140. protected function getFieldListName($field)
  1141. {
  1142. return $this->getCamelizeName($field) . 'List';
  1143. }
  1144. }