Procházet zdrojové kódy

Hide filters with a default value (#4059)

Christian Gripp před 8 roky
rodič
revize
25bf7c0a08

+ 50 - 0
Admin/AbstractAdmin.php

@@ -778,6 +778,7 @@ abstract class AbstractAdmin implements AdminInterface, DomainObjectInterface
             $parameters = array_merge(
                 $this->getModelManager()->getDefaultSortValues($this->getClass()),
                 $this->datagridValues,
+                $this->getDefaultFilterValues(),
                 $filters
             );
 
@@ -2936,6 +2937,25 @@ EOT;
         return;
     }
 
+    /**
+     * Checks if a filter type is set to a default value.
+     *
+     * @param string $name
+     *
+     * @return bool
+     */
+    final public function isDefaultFilter($name)
+    {
+        $filter = $this->getFilterParameters();
+        $default = $this->getDefaultFilterValues();
+
+        if (!array_key_exists($name, $filter) || !array_key_exists($name, $default)) {
+            return false;
+        }
+
+        return $filter[$name] == $default[$name];
+    }
+
     /**
      * Check object existence and access, without throw Exception.
      *
@@ -2949,6 +2969,27 @@ EOT;
         return $object && $this->id($object) && $this->hasAccess($action, $object);
     }
 
+    /**
+     * Returns a list of default filters.
+     *
+     * @return array
+     */
+    final protected function getDefaultFilterValues()
+    {
+        $defaultFilterValues = array();
+
+        $this->configureDefaultFilterValues($defaultFilterValues);
+
+        foreach ($this->getExtensions() as $extension) {
+            // NEXT_MAJOR: remove method check in next major release
+            if (method_exists($extension, 'configureDefaultFilterValues')) {
+                $extension->configureDefaultFilterValues($this, $defaultFilterValues);
+            }
+        }
+
+        return $defaultFilterValues;
+    }
+
     /**
      * {@inheritdoc}
      */
@@ -3219,6 +3260,15 @@ EOT;
         return $access;
     }
 
+    /**
+     * Returns a list of default filters.
+     *
+     * @param array $filterValues
+     */
+    protected function configureDefaultFilterValues(array &$filterValues)
+    {
+    }
+
     /**
      * Build all the related urls to the current admin.
      */

+ 10 - 0
Admin/AbstractAdminExtension.php

@@ -186,4 +186,14 @@ abstract class AbstractAdminExtension implements AdminExtensionInterface
     {
         return $list;
     }
+
+    /**
+     * Returns a list of default filters.
+     *
+     * @param AdminInterface $admin
+     * @param array          $filterValues
+     */
+    public function configureDefaultFilterValues(AdminInterface $admin, array &$filterValues)
+    {
+    }
 }

+ 10 - 0
Admin/AdminExtensionInterface.php

@@ -194,4 +194,14 @@ interface AdminExtensionInterface
      */
     // TODO: Uncomment in next major release
     // public function configureActionButtons(AdminInterface $admin, $list, $action, $object);
+
+    /*
+     * NEXT_MAJOR: Uncomment in next major release
+     *
+     * Returns a list of default filters
+     *
+     * @param AdminInterface $admin
+     * @param array          $filterValues
+     */
+    // public function configureDefaultFilterValues(AdminInterface $admin, array &$filterValues);
 }

+ 18 - 0
Admin/AdminInterface.php

@@ -1070,4 +1070,22 @@ interface AdminInterface
 //     * @param bool $isShown
 //     */
 //    public function showMosaicButton($isShown);
+
+    /*
+     * Checks if a filter type is set to a default value
+     *
+     * @param string $name
+     *
+     * @return bool
+     */
+//    NEXT_MAJOR: uncomment this method in 4.0
+    // public function isDefaultFilter($name);
+
+    /*
+     * Returns a list of default filters.
+     *
+     * @return array
+     */
+//    NEXT_MAJOR: uncomment this method in 4.0
+    // public function getDefaultFilterValues();
 }

+ 8 - 9
Resources/doc/reference/action_list.rst

@@ -329,19 +329,18 @@ If you don't need the advanced filters, or all your ``operator_type`` are hidden
 Default filters
 ^^^^^^^^^^^^^^^
 
-Default filters can be added to the datagrid values by overriding the ``$datagridValues`` property which is also used for default sorting.
+Default filters can be added to the datagrid values by using the ``configureDefaultFilterValues`` method.
 A filter has a ``value`` and an optional ``type``. If no ``type`` is given the default type ``is equal`` is used.
 
 .. code-block:: php
 
-    protected $datagridValues = array(
-        '_page' => 1,
-        '_sort_order' => 'ASC',
-        '_sort_by' => 'id',
-        'foo' => array(
-            'value' => 'bar'
-        )
-    );
+    public function configureDefaultFilterValues(array &$filterValues)
+    {
+        $filterValues['foo'] = array(
+            'type'  => ChoiceFilter::TYPE_CONTAINS,
+            'value' => 'bar',
+        );
+    }
 
 Available types are represented through classes which can be found here:
 https://github.com/sonata-project/SonataCoreBundle/tree/master/Form/Type

+ 5 - 2
Resources/views/CRUD/base_list.html.twig

@@ -217,9 +217,10 @@ file that was distributed with this source code.
 
                 <ul class="dropdown-menu" role="menu">
                     {% for filter in admin.datagrid.filters if (filter.options['show_filter'] is same as(true) or filter.options['show_filter'] is null) %}
+                        {% set filterActive = ((filter.isActive() or filter.options['show_filter']) and not admin.isDefaultFilter(filter.formName)) %}
                         <li>
                             <a href="#" class="sonata-toggle-filter sonata-ba-action" filter-target="filter-{{ admin.uniqid }}-{{ filter.name }}" filter-container="filter-container-{{ admin.uniqid() }}">
-                                <i class="fa {{ (filter.isActive() or filter.options['show_filter']) ? 'fa-check-square-o' : 'fa-square-o' }}"></i>{{ admin.trans(filter.label, {}, filter.translationDomain) }}
+                                <i class="fa {{ filterActive ? 'fa-check-square-o' : 'fa-square-o' }}"></i>{{ admin.trans(filter.label, {}, filter.translationDomain) }}
                             </a>
                         </li>
                     {% endfor %}
@@ -243,7 +244,9 @@ file that was distributed with this source code.
                             <div class="col-sm-9">
                                 {% set withAdvancedFilter = false %}
                                 {% for filter in admin.datagrid.filters %}
-                                    <div class="form-group {% block sonata_list_filter_group_class %}{% endblock %}" id="filter-{{ admin.uniqid }}-{{ filter.name }}" sonata-filter="{{ (filter.options['show_filter'] is same as(true) or filter.options['show_filter'] is null) ? 'true' : 'false' }}" style="display: {% if (filter.isActive() and filter.options['show_filter'] is null) or (filter.options['show_filter'] is same as(true)) %}block{% else %}none{% endif %}">
+                                    {% set filterActive = ((filter.isActive() and filter.options['show_filter'] is null) or (filter.options['show_filter'] is same as(true))) and not admin.isDefaultFilter(filter.formName) %}
+                                    {% set filterVisible = filter.options['show_filter'] is same as(true) or filter.options['show_filter'] is null %}
+                                    <div class="form-group {% block sonata_list_filter_group_class %}{% endblock %}" id="filter-{{ admin.uniqid }}-{{ filter.name }}" sonata-filter="{{ filterVisible ? 'true' : 'false' }}" style="display: {% if filterActive %}block{% else %}none{% endif %}">
                                         {% if filter.label is not same as(false) %}
                                             <label for="{{ form.children[filter.formName].children['value'].vars.id }}" class="col-sm-3 control-label">{{ admin.trans(filter.label, {}, filter.translationDomain) }}</label>
                                         {% endif %}

+ 56 - 0
Tests/Admin/AdminTest.php

@@ -19,6 +19,7 @@ use Sonata\AdminBundle\Route\RoutesCache;
 use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentAdmin;
 use Sonata\AdminBundle\Tests\Fixtures\Admin\CommentWithCustomRouteAdmin;
 use Sonata\AdminBundle\Tests\Fixtures\Admin\FieldDescription;
+use Sonata\AdminBundle\Tests\Fixtures\Admin\FilteredAdmin;
 use Sonata\AdminBundle\Tests\Fixtures\Admin\ModelAdmin;
 use Sonata\AdminBundle\Tests\Fixtures\Admin\PostAdmin;
 use Sonata\AdminBundle\Tests\Fixtures\Admin\PostWithCustomRouteAdmin;
@@ -1763,6 +1764,61 @@ class AdminTest extends \PHPUnit_Framework_TestCase
         $this->assertArrayHasKey('create', $admin->getDashboardActions());
     }
 
+    public function testDefaultFilters()
+    {
+        $admin = new FilteredAdmin('sonata.post.admin.model', 'Application\Sonata\FooBundle\Entity\Model', 'SonataFooBundle:ModelAdmin');
+
+        $subjectId = uniqid();
+
+        $request = $this->getMock('Symfony\Component\HttpFoundation\Request', array('get'));
+        $request->query->set('filter', array(
+            'a' => array(
+                'value' => 'b',
+            ),
+            'foo' => array(
+                'type' => '1',
+                'value' => 'bar',
+            ),
+            'baz' => array(
+                'type' => '5',
+                'value' => 'test',
+            ),
+        ));
+
+        $request->expects($this->any())
+            ->method('get')
+            ->will($this->returnValue($subjectId));
+
+        $admin->setRequest($request);
+
+        $modelManager = $this->getMock('Sonata\AdminBundle\Model\ModelManagerInterface');
+        $modelManager->expects($this->any())
+            ->method('getDefaultSortValues')
+            ->will($this->returnValue(array()));
+
+        $admin->setModelManager($modelManager);
+
+        $this->assertEquals(array(
+            'foo' => array(
+                'type' => '1',
+                'value' => 'bar',
+            ),
+            'baz' => array(
+                'type' => '5',
+                'value' => 'test',
+            ),
+            '_page' => 1,
+            '_per_page' => 32,
+            'a' => array(
+                'value' => 'b',
+            ),
+        ), $admin->getFilterParameters());
+
+        $this->assertTrue($admin->isDefaultFilter('foo'));
+        $this->assertFalse($admin->isDefaultFilter('bar'));
+        $this->assertFalse($admin->isDefaultFilter('a'));
+    }
+
     /**
      * @group legacy
      */

+ 20 - 0
Tests/Fixtures/Admin/FilteredAdmin.php

@@ -0,0 +1,20 @@
+<?php
+
+namespace Sonata\AdminBundle\Tests\Fixtures\Admin;
+
+use Sonata\AdminBundle\Admin\AbstractAdmin;
+
+class FilteredAdmin extends AbstractAdmin
+{
+    protected function configureDefaultFilterValues(array &$filterValues)
+    {
+        $filterValues['foo'] = array(
+            'type' => '1',
+            'value' => 'bar',
+        );
+        $filterValues['baz'] = array(
+            'type' => '2',
+            'value' => 'test',
+        );
+    }
+}