CRUD新增获取器功能

如果字段是enum,set,select等类型字段会自动在Model生成获取器
新增int日期型字段的获取器和修改器
移除Traits中add/edit方法自动修改日期的功能
修复Form.api.bindevent单次绑定多个form时的BUG
修复特殊情况下刷新不显示边栏的BUG
修复特殊情况下使用addtabsit进行控制器间切换时的BUG
pull/323483/MERGE
Karson 2017-06-01 22:13:03 +08:00
parent d21aad24d5
commit e816d8538b
6 changed files with 151 additions and 14 deletions

View File

@ -217,6 +217,9 @@ class Crud extends Command
try try
{ {
Form::setEscapeHtml(false); Form::setEscapeHtml(false);
$setAttrArr = [];
$getAttrArr = [];
$appendAttrList = [];
//循环所有字段,开始构造视图的HTML和JS信息 //循环所有字段,开始构造视图的HTML和JS信息
foreach ($columnList as $k => $v) foreach ($columnList as $k => $v)
@ -257,6 +260,7 @@ class Crud extends Command
//如果状态类型不是enum或set //如果状态类型不是enum或set
$itemArr = !$itemArr ? ['normal', 'hidden'] : $itemArr; $itemArr = !$itemArr ? ['normal', 'hidden'] : $itemArr;
$inputType = 'radio'; $inputType = 'radio';
$this->getAttr($getAttrArr, $field);
} }
if ($inputType == 'select') if ($inputType == 'select')
{ {
@ -270,6 +274,10 @@ class Crud extends Command
$attrStr = $this->getArrayString($attrArr); $attrStr = $this->getArrayString($attrArr);
$itemArr = $this->getLangArray($itemArr, FALSE); $itemArr = $this->getLangArray($itemArr, FALSE);
$itemString = $this->getArrayString($itemArr); $itemString = $this->getArrayString($itemArr);
//添加一个获取器
$this->getAttr($getAttrArr, $field, $itemArr, $v['DATA_TYPE'] == 'set' ? 'multiple' : 'select');
$this->appendAttr($appendAttrList, $field);
$formAddElement = "{:build_select('{$fieldName}', [{$itemString}], '{$defaultValue}', [{$attrStr}])}"; $formAddElement = "{:build_select('{$fieldName}', [{$itemString}], '{$defaultValue}', [{$attrStr}])}";
$formEditElement = "{:build_select('{$fieldName}', [{$itemString}], \$row.{$field}, [{$attrStr}])}"; $formEditElement = "{:build_select('{$fieldName}', [{$itemString}], \$row.{$field}, [{$attrStr}])}";
} }
@ -302,6 +310,9 @@ class Crud extends Command
break; break;
default: default:
$fieldFunc = 'datetime'; $fieldFunc = 'datetime';
$this->getAttr($getAttrArr, $field, '', $inputType);
$this->setAttr($setAttrArr, $field, '', $inputType);
$this->appendAttr($appendAttrList, $field);
break; break;
} }
$defaultDateTime = "{:date('{$phpFormat}')}"; $defaultDateTime = "{:date('{$phpFormat}')}";
@ -316,6 +327,9 @@ class Crud extends Command
$fieldName .= "[]"; $fieldName .= "[]";
$itemArr = $this->getLangArray($itemArr, FALSE); $itemArr = $this->getLangArray($itemArr, FALSE);
$itemString = $this->getArrayString($itemArr); $itemString = $this->getArrayString($itemArr);
//添加一个获取器
$this->getAttr($getAttrArr, $field, $itemArr, $inputType);
$this->appendAttr($appendAttrList, $field);
$formAddElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], '{$defaultValue}')}"; $formAddElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], '{$defaultValue}')}";
$formEditElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], \$row.{$field})}"; $formEditElement = "{:build_checkboxs('{$fieldName}', [{$itemString}], \$row.{$field})}";
} }
@ -324,6 +338,9 @@ class Crud extends Command
$itemArr = $this->getLangArray($itemArr, FALSE); $itemArr = $this->getLangArray($itemArr, FALSE);
$itemString = $this->getArrayString($itemArr); $itemString = $this->getArrayString($itemArr);
$defaultValue = $defaultValue ? $defaultValue : key($itemArr); $defaultValue = $defaultValue ? $defaultValue : key($itemArr);
//添加一个获取器
$this->getAttr($getAttrArr, $field, $itemArr, $inputType);
$this->appendAttr($appendAttrList, $field);
$formAddElement = "{:build_radios('{$fieldName}', [{$itemString}], '{$defaultValue}')}"; $formAddElement = "{:build_radios('{$fieldName}', [{$itemString}], '{$defaultValue}')}";
$formEditElement = "{:build_radios('{$fieldName}', [{$itemString}], \$row.{$field})}"; $formEditElement = "{:build_radios('{$fieldName}', [{$itemString}], \$row.{$field})}";
} }
@ -477,6 +494,9 @@ class Crud extends Command
'relationPrimaryKey' => '', 'relationPrimaryKey' => '',
'relationSearch' => $relation ? 'true' : 'false', 'relationSearch' => $relation ? 'true' : 'false',
'controllerIndex' => '', 'controllerIndex' => '',
'appendAttrList' => implode(",\n", $appendAttrList),
'getAttrList' => implode("\n\n", $getAttrArr),
'setAttrList' => implode("\n\n", $setAttrArr),
'modelMethod' => '', 'modelMethod' => '',
]; ];
@ -526,6 +546,79 @@ class Crud extends Command
$output->writeln("<info>Build Successed</info>"); $output->writeln("<info>Build Successed</info>");
} }
protected function getAttr(&$getAttr, $field, $itemArr = '', $inputType = '')
{
if (!in_array($inputType, ['datetime', 'select', 'multiple', 'checkbox', 'radio']))
return;
$attrField = ucfirst($field);
if ($inputType == 'datetime')
{
$return = <<<EOD
\$value = \$data['{$field}'];
return is_numeric(\$value) ? date("Y-m-d H:i:s", \$value) : \$value;
EOD;
}
else if (in_array($inputType, ['multiple', 'checkbox']))
{
$itemString = $this->getArrayString($itemArr);
$return = <<<EOD
\$value = \$data['{$field}'];
\$valueArr = explode(',', \$value);
\$arr = [{$itemString}];
\$resultArr = [];
foreach (\$valueArr as \$k => \$v)
{
if (isset(\$arr[\$v]))
{
\$resultArr[] = \$arr[\$v];
}
}
return implode(',', \$resultArr);
EOD;
}
else
{
$itemString = $this->getArrayString($itemArr);
$return = <<<EOD
\$value = \$data['{$field}'];
\$arr = [{$itemString}];
return isset(\$arr[\$value]) ? \$arr[\$value] : '';
EOD;
}
$getAttr[] = <<<EOD
protected function get{$attrField}TextAttr(\$value, \$data)
{
$return
}
EOD;
}
protected function setAttr(&$setAttr, $field, $itemArr = '', $inputType = '')
{
if ($inputType != 'datetime')
return;
$field = ucfirst($field);
if ($inputType == 'datetime')
{
$return = <<<EOD
return is_numeric(\$value) ? strtotime(\$value) : \$value;
EOD;
}
$setAttr[] = <<<EOD
protected function set{$field}TextAttr(\$value)
{
$return
}
EOD;
}
protected function appendAttr(&$appendAttrList, $field)
{
$appendAttrList[] = <<<EOD
'{$field}_text'
EOD;
}
protected function getModelName($model, $table) protected function getModelName($model, $table)
{ {
if (!$model) if (!$model)
@ -747,7 +840,7 @@ EOD;
{ {
$lang = ucfirst($field); $lang = ucfirst($field);
$html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')"; $html = str_repeat(" ", 24) . "{field: '{$field}', title: __('{$lang}')";
$field = substr($field, stripos($field, '.') + 1); $field = stripos($field, ".") !== false ? substr($field, stripos($field, '.') + 1) : $field;
$formatter = ''; $formatter = '';
if ($field == 'status') if ($field == 'status')
$formatter = 'status'; $formatter = 'status';

View File

@ -16,5 +16,14 @@ class {%modelName%} extends Model
protected $createTime = {%createTime%}; protected $createTime = {%createTime%};
protected $updateTime = {%updateTime%}; protected $updateTime = {%updateTime%};
// 追加属性
protected $append = [
{%appendAttrList%}
];
{%getAttrList%}
{%setAttrList%}
{%modelMethod%} {%modelMethod%}
} }

View File

@ -23,6 +23,7 @@ trait Backend
->order($sort, $order) ->order($sort, $order)
->limit($offset, $limit) ->limit($offset, $limit)
->select(); ->select();
$result = array("total" => $total, "rows" => $list); $result = array("total" => $total, "rows" => $list);
return json($result); return json($result);
@ -44,10 +45,27 @@ trait Backend
foreach ($params as $k => &$v) foreach ($params as $k => &$v)
{ {
$v = is_array($v) ? implode(',', $v) : $v; $v = is_array($v) ? implode(',', $v) : $v;
$v = substr($k, -4) == 'time' && !is_numeric($v) ? strtotime($v) : $v;
} }
$this->model->create($params); try
$this->code = 1; {
$result = $this->model->create($params);
if ($result !== false)
{
$this->code = 1;
}
else
{
$this->msg = $this->model->getError();
}
}
catch (think\Exception $e)
{
$this->msg = $e->getMessage();
}
}
else
{
$this->msg = __('Parameter %s can not be empty', '');
} }
return; return;
@ -72,10 +90,27 @@ trait Backend
foreach ($params as $k => &$v) foreach ($params as $k => &$v)
{ {
$v = is_array($v) ? implode(',', $v) : $v; $v = is_array($v) ? implode(',', $v) : $v;
$v = substr($k, -4) == 'time' && !is_numeric($v) ? strtotime($v) : $v;
} }
$row->save($params); try
$this->code = 1; {
$result = $row->save($params);
if ($result !== false)
{
$this->code = 1;
}
else
{
$this->msg = $row->getError();
}
}
catch (think\Exception $e)
{
$this->msg = $e->getMessage();
}
}
else
{
$this->msg = __('Parameter %s can not be empty', '');
} }
return; return;
@ -126,7 +161,7 @@ trait Backend
} }
else else
{ {
$this->code = 1; $this->msg = __('Parameter %s can not be empty', '');
} }
} }

View File

@ -92,7 +92,7 @@ class Backend extends Controller
!defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax()); !defined('IS_AJAX') && define('IS_AJAX', $this->request->isAjax());
// 非选项卡时重定向 // 非选项卡时重定向
if (!IS_AJAX && !IS_ADDTABS && $controllername != 'index' && $actionname == 'index') if (!IS_AJAX && !IS_ADDTABS && !IS_DIALOG && $path !== "/{$modulename}/index/index" && $controllername != 'ajax')
{ {
$url = $this->request->url(); $url = $this->request->url();
$this->redirect('index/index', [], 302, ['referer' => $url]); $this->redirect('index/index', [], 302, ['referer' => $url]);

View File

@ -246,7 +246,7 @@ define(['jquery', 'bootstrap', 'toastr', 'layer', 'lang', 'moment'], function ($
}); });
}, },
addtabs: function (url, title, icon) { addtabs: function (url, title, icon) {
var dom = ".sidebar-menu li a[url='{url}']" var dom = "a[url='{url}']"
var leftlink = top.window.$(dom.replace(/\{url\}/, url)); var leftlink = top.window.$(dom.replace(/\{url\}/, url));
if (leftlink.size() > 0) { if (leftlink.size() > 0) {
leftlink.trigger("click"); leftlink.trigger("click");
@ -273,7 +273,7 @@ define(['jquery', 'bootstrap', 'toastr', 'layer', 'lang', 'moment'], function ($
var id = Math.floor(new Date().valueOf() * Math.random()); var id = Math.floor(new Date().valueOf() * Math.random());
icon = typeof icon != 'undefined' ? icon : 'fa fa-circle-o'; icon = typeof icon != 'undefined' ? icon : 'fa fa-circle-o';
title = typeof title != 'undefined' ? title : ''; title = typeof title != 'undefined' ? title : '';
top.window.$("<a />").append('<i class="' + icon + '"></i> <span>' + title + '</span>').prop("href", url).attr({url: url, addtabs: id}).appendTo(top.window.document.body).trigger("click"); top.window.$("<a />").append('<i class="' + icon + '"></i> <span>' + title + '</span>').prop("href", url).attr({url: url, addtabs: id}).addClass("hide").appendTo(top.window.document.body).trigger("click");
} }
} }
} }

View File

@ -76,9 +76,9 @@ define(['jquery', 'bootstrap', 'backend', 'toastr', 'upload', 'validator'], func
stopOnError: true, stopOnError: true,
valid: function (ret) { valid: function (ret) {
//验证通过提交表单 //验证通过提交表单
Form.api.submit(form, onBeforeSubmit, function (data) { Form.api.submit($(ret), onBeforeSubmit, function (data) {
if (typeof onAfterSubmit == 'function') { if (typeof onAfterSubmit == 'function') {
if (!onAfterSubmit.call(form, data)) { if (!onAfterSubmit.call($(ret), data)) {
return false; return false;
} }
} }
@ -239,7 +239,7 @@ define(['jquery', 'bootstrap', 'backend', 'toastr', 'upload', 'validator'], func
$(document).on('click', ".fachoose", function () { $(document).on('click', ".fachoose", function () {
var multiple = $(this).data("multiple") ? $(this).data("multiple") : false; var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : ''; var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
Backend.api.open("general/attachment/select?callback=refreshchoose&element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype="+mimetype, __('Choose')); Backend.api.open("general/attachment/select?callback=refreshchoose&element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype, __('Choose'));
return false; return false;
}); });