Selaa lähdekoodia

修复Form::select使用表单联动功能时select2组件无效问题

jqh 4 vuotta sitten
vanhempi
commit
cd8f98326d

+ 2 - 0
resources/views/form/select-script.blade.php

@@ -25,6 +25,8 @@
     @else
     $this.select2(configs);
     @endif
+
+    {!! $cascadeScript !!}
 </script>
 
 @if(isset($loads))

+ 20 - 7
src/Form/Field/CanCascadeFields.php

@@ -112,12 +112,27 @@ trait CanCascadeFields
         return sprintf('cascade-%s-%s-%s', $this->getElementClassString(), $value, $map[$operator]);
     }
 
+    protected function addCascadeScript()
+    {
+        if (! $script = $this->getCascadeScript()) {
+            return;
+        }
+
+        Admin::script(
+            <<<JS
+Dcat.init('{$this->getElementClassSelector()}', function (\$this) {
+    {$script}
+});
+JS
+        );
+    }
+
     /**
      * Add cascade scripts to contents.
      *
-     * @return void
+     * @return string
      */
-    protected function addCascadeScript()
+    protected function getCascadeScript()
     {
         if (empty($this->conditions)) {
             return;
@@ -131,8 +146,8 @@ trait CanCascadeFields
             ];
         })->toJson();
 
-        $script = <<<JS
-Dcat.init('{$this->getElementClassSelector()}', function (\$this) {
+        return <<<JS
+(function () {
     var compare = function (a, b, o) {
         if (! $.isArray(b)) {
             return operator_table[o](a, b)
@@ -194,10 +209,8 @@ Dcat.init('{$this->getElementClassSelector()}', function (\$this) {
             }
         });
     }).trigger(event);
-});
+})();
 JS;
-
-        Admin::script($script);
     }
 
     /**

+ 4 - 5
src/Form/Field/Select.php

@@ -281,14 +281,13 @@ class Select extends Field
             ],
         ]);
 
-        $this->addCascadeScript();
-
         $this->formatOptions();
 
         $this->addVariables([
-            'options' => $this->options,
-            'groups'  => $this->groups,
-            'configs' => $this->config,
+            'options'       => $this->options,
+            'groups'        => $this->groups,
+            'configs'       => $this->config,
+            'cascadeScript' => $this->getCascadeScript(),
         ]);
 
         $this->attribute('data-value', implode(',', Helper::array($this->value())));