|
|
@@ -7,6 +7,16 @@ use UCore\DcatAdmin\Traits\UserID;
|
|
|
use Dcat\Admin\Form;
|
|
|
|
|
|
|
|
|
+/**
|
|
|
+ * 表单助手类 - 自动根据类属性生成表单字段
|
|
|
+ *
|
|
|
+ * 使用示例:
|
|
|
+ * $formHelper = new FormHelper($form);
|
|
|
+ * $formHelper->embedClassFields('user', '用户信息', [User::class]);
|
|
|
+ *
|
|
|
+ * 类属性注释示例:
|
|
|
+ * @label 用户名
|
|
|
+ */
|
|
|
class FormHelper
|
|
|
{
|
|
|
|
|
|
@@ -43,9 +53,75 @@ class FormHelper
|
|
|
{
|
|
|
return $this->form->field($field);
|
|
|
}
|
|
|
- public function embedsCats($field)
|
|
|
+ public function embedsCats($field,$lable)
|
|
|
{
|
|
|
+ $modeClass = get_class($this->form->repository()->model());
|
|
|
+ $cates = $this->form->repository()->model()->getCasts();
|
|
|
+// dump($cates);
|
|
|
+ $class = $cates[$field] ?? "";
|
|
|
+ $reflectionClass = new \ReflectionClass($class);
|
|
|
+
|
|
|
+ return $this->form->embeds($field,$lable,function (\Dcat\Admin\Form\EmbeddedForm $form) use ($class,$reflectionClass){
|
|
|
+
|
|
|
+ // 从注释中提取字段标签
|
|
|
+ $getFieldLabel = function($name, $comment) {
|
|
|
+ if ($comment) {
|
|
|
+ // 优先提取@label标签
|
|
|
+ if (preg_match('/@label\s+([^\r\n]+)/', $comment, $matches)) {
|
|
|
+ return trim($matches[1]);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 处理多行注释,提取第一行描述
|
|
|
+ $lines = explode("\n", $comment);
|
|
|
+ foreach ($lines as $line) {
|
|
|
+ // 匹配描述行 (以 * 开头但不包含@标签的行)
|
|
|
+ if (preg_match('/^\s*\*\s+([^@*]+)/', $line, $matches)) {
|
|
|
+ $desc = trim($matches[1]);
|
|
|
+ if (!empty($desc) && !preg_match('/@\w+/', $desc)) {
|
|
|
+ return $desc;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 最后提取@var类型后的描述
|
|
|
+ if (preg_match('/@var\s+\S+\s+([^\r\n]+)/', $comment, $matches)) {
|
|
|
+ $desc = trim($matches[1]);
|
|
|
+ if (!empty($desc)) {
|
|
|
+ return $desc;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 默认使用字段名转换
|
|
|
+ return ucwords(str_replace(['_', '-'], ' ', $name));
|
|
|
+ };
|
|
|
+ foreach ($reflectionClass->getProperties() as $property) {
|
|
|
+ // 设置不同类型的表单
|
|
|
+ $type = $property->getType() ? $property->getType()->getName() : null;
|
|
|
+ $name = $property->getName();
|
|
|
+ $comment = $property->getDocComment();
|
|
|
+
|
|
|
+ // 根据类型设置不同表单字段
|
|
|
+ switch ($type) {
|
|
|
+ case 'string':
|
|
|
+ $form->text($name, $getFieldLabel($name, $comment));
|
|
|
+ break;
|
|
|
+ case 'int':
|
|
|
+ $form->number($name, $getFieldLabel($name, $comment));
|
|
|
+ break;
|
|
|
+ case 'float':
|
|
|
+ $form->decimal($name, $getFieldLabel($name, $comment));
|
|
|
+ break;
|
|
|
+ case 'bool':
|
|
|
+ $form->switch($name, $getFieldLabel($name, $comment));
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ $form->text($name, $getFieldLabel($name, $comment));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 返回表单对象
|
|
|
+ return $form;
|
|
|
|
|
|
+ });
|
|
|
}
|
|
|
|
|
|
|