Procházet zdrojové kódy

checkbox表单增加全选功能 #400

jqh před 5 roky
rodič
revize
226bc757d0

+ 6 - 1
resources/views/form/checkbox.blade.php

@@ -1,9 +1,14 @@
 <div class="{{$viewClass['form-group']}} {!! !$errors->has($column) ?: 'has-error' !!}" >
 
-    <label for="{{$id}}" class="{{$viewClass['label']}} control-label">{!! $label !!}</label>
+    <label for="{{$id}}" class="{{$viewClass['label']}} control-label pt-0">{!! $label !!}</label>
 
     <div class="{{$viewClass['field']}}" id="{{ $id }}">
 
+        @if($checkAll)
+            {!! $checkAll !!}
+            <hr style="margin-top: 10px;margin-bottom: 0;">
+        @endif
+
         @include('admin::form.error')
 
         {!! $checkbox !!}

+ 38 - 0
src/Form/Field/Checkbox.php

@@ -2,6 +2,7 @@
 
 namespace Dcat\Admin\Form\Field;
 
+use Dcat\Admin\Admin;
 use Dcat\Admin\Support\Helper;
 use Dcat\Admin\Widgets\Checkbox as WidgetCheckbox;
 
@@ -16,6 +17,8 @@ class Checkbox extends MultipleSelect
 
     protected $cascadeEvent = 'change';
 
+    protected $canCheckAll = false;
+
     /**
      * @param array|\Closure|string $options
      *
@@ -48,6 +51,18 @@ class Checkbox extends MultipleSelect
         return $this;
     }
 
+    /**
+     * Add a checkbox above this component, so you can select all checkboxes by click on it.
+     *
+     * @return $this
+     */
+    public function canCheckAll()
+    {
+        $this->canCheckAll = true;
+
+        return $this;
+    }
+
     /**
      * {@inheritdoc}
      */
@@ -78,10 +93,33 @@ class Checkbox extends MultipleSelect
 
         $this->addVariables([
             'checkbox' => $checkbox,
+            'checkAll' => $this->makeCheckAllCheckbox(),
         ]);
 
         $this->script = ';';
 
         return parent::render();
     }
+
+    protected function makeCheckAllCheckbox()
+    {
+        if (! $this->canCheckAll) {
+            return;
+        }
+
+        $this->addCheckAllScript();
+
+        return WidgetCheckbox::make('_check_all_', [__('admin.all')]);
+    }
+
+    protected function addCheckAllScript()
+    {
+        Admin::script(
+            <<<'JS'
+$('[name="_check_all_"]').on('change', function () {
+    $(this).parents('.form-field').find('input[type="checkbox"]').prop('checked', this.checked);
+});
+JS
+        );
+    }
 }