技术控

    今日:0| 主题:63445
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Sonata for Symfony: Hide Your Filters!

[复制链接]
初吻给了香烟 发表于 2016-10-1 06:30:19
162 6
How to enforce and hide filters on a Sonata’s list view

  Sonata provides you with a robust and easy to implement interface administration for your Symfony projects.
  We have been using and loving it on my projects for 19 weeks now. Every day we are amazed with the time we save thanks to Sonata.
  However, there are some features that our client wants that are missing. One of them is the possibility to hide filters.
  Imagine you want your users to see a pre-filtered Sonata list and do not display the filters.
  In our case we receive applications. Each application has a status and a at certain point we have a button “View pending application”. This button of course is supposed to list only the “pending” applications and we don’t want the users to be able to change this filter.
  This solution is really straight-forward and easy to implement, give us 5 minutes and 30 lines of code!
  Note: this tutorial is written for Symfony 2.8 and Sonata 2.3. Let me know in the comments if you tested it on other configurations.
  The easy solution : createQuery

  When you search for a solution online you easily find examples of people using the createQuery function of Sonata:
  In your admin class:
  1. class ApplicationAdmin extends SonataAdmin
  2. {
  3.     public function createQuery($context = 'list')
  4.     {
  5.         $query = parent::createQuery($context);
  6.         $rootAlias = $query->getRootAliases()[0];
  7.         $query
  8.             ->andWhere($query->expr()->eq($rootAlias . '.status', ':statusPending'))
  9.             ->setParameter('statusPending', Application::STATUS_PENDING)
  10.             ;
  11.             
  12.         return $query;
  13.     }
  14. }
复制代码
This works great but we had one major issue with that solution:
  
       
  • The filter is always enforced and there is no way to display the same list without it.  
  The better solution : hiddenFilters

  In our project we had to display the same list, sometimes with hidden filters enforced, sometimes not.
  That’s why we went a step further and created a “HiddenFilters” mechanism.
  
       
  • Use URL parameters to define which filters to set up  
  1. class ApplicationAdmin extends SonataAdmin
  2. {
  3.     // This array will contain our filters, filters are an object with a unique key and a value
  4.     private $hiddenFilters;
  5.    
  6.     // This function reads the filters from the URL
  7.     private function readHiddenFilters()
  8.     {
  9.         return $this->getRequest()->query->get('hiddenFilters');
  10.     }
  11.    
  12.     // CreateQuery is called to generate the list before the admin list view is rendered
  13.     public function createQuery($context = 'list')
  14.     {
  15.         $query = parent::createQuery($context);
  16.         $rootAlias = $query->getRootAliases()[0];

  17.         // Make sure we have the last filters in memory
  18.         $this->hiddenFilters = $this->readHiddenFilters();

  19.         // Do any kind of check on those filters, here we check that "statusPendingFilter: true" was set
  20.         if (is_array($this->hiddenFilters) && array_key_exists('statusPendingFilter', $this->hiddenFilters) && $this->hiddenFilters['statusPendingFilter']) {
  21.             $query
  22.                 ->andWhere($query->expr()->eq($rootAlias . '.status', ':statusPending'))
  23.                 ->setParameter('statusPending', 'PENDING')
  24.                 ;
  25.         }
  26.         
  27.         return $query;
  28.     }
  29. }
复制代码
Now, when you want to activate a hidden filter on your list, call it with the correct parameters in the URL:
  1. <a href="{{ path('admin_application_list', {'hiddenFilters' : {'statusPendingFilter' : true}}) }}">
复制代码
  1. $this->router->generate('admin_application_list', array('hiddenFilters[statusPendingFilter]' => true));
复制代码

       
  • Save your hidden filters as persistent parameters  
  You now have great filters you can enable and disable at will. Last issue: when you edit an element and then come back to the list your filters have disappeared.
  The fix for that is to use Sonata’s persistent parameters: it’s a really handy function that will had your filters to all the Sonata generated links.
  Add that to your admin class:
  1. public function getPersistentParameters()
  2. {
  3.     $parameters = parent::getPersistentParameters();

  4.     if (!$this->getRequest()) {
  5.         return array();
  6.     }

  7.     return array_merge($parameters, array(
  8.         'hiddenFilters' => is_array($this->hiddenFilters) ? json_encode($this->hiddenFilters) : $this->hiddenFilters,
  9.     ));
  10. }
复制代码
Notice that we had to JSON_encode our filters because persistent parameters can only be strings.
  That means we are going to have to change our readHiddenFilters function to decode the JSON:
  1. private function readHiddenFilters()
  2. {
  3.     return is_array($this->getRequest()->query->get('hiddenFilters')) ?
  4.         $this->getRequest()->query->get('hiddenFilters') :
  5.         json_decode($this->getRequest()->query->get('hiddenFilters'), true);
  6. }
复制代码
That’s it! You have fully customizable and activable hidden filters!
  The full code : 30 lines

  Here is the full code of working hidden filters:
  1. class ApplicationAdmin extends SonataAdmin
  2. {
  3.     private $hiddenFilters;
  4.    
  5.     public function __construct($code, $class, $baseControllerName)
  6.     {
  7.         parent::__construct($code, $class, $baseControllerName);
  8.         $this->hiddenFilters = $this->readHiddenFilters();
  9.     }
  10.    
  11.     private function readHiddenFilters()
  12.     {
  13.         return is_array($this->getRequest()->query->get('hiddenFilters')) ?
  14.             $this->getRequest()->query->get('hiddenFilters') :
  15.             json_decode($this->getRequest()->query->get('hiddenFilters'), true);
  16.     }
  17.    
  18.     public function getPersistentParameters()
  19.     {
  20.         $parameters = parent::getPersistentParameters();
  21.    
  22.         if (!$this->getRequest()) {
  23.             return array();
  24.         }
  25.    
  26.         return array_merge($parameters, array(
  27.             'hiddenFilters' => is_array($this->hiddenFilters) ? json_encode($this->hiddenFilters) : $this->hiddenFilters,
  28.         ));
  29.     }
  30.    
  31.     public function createQuery($context = 'list')
  32.     {
  33.         $query = parent::createQuery($context);
  34.         $rootAlias = $query->getRootAliases()[0];
  35.         
  36.         if (array_key_exists('statusPendingFilter', $this->hiddenFilters) && $this->hiddenFilters['statusPendingFilter']) {
  37.             $query
  38.                 ->andWhere($query->expr()->eq($rootAlias . '.status', ':statusPending'))
  39.                 ->setParameter('statusPending', Application::STATUS_PENDING)
  40.                 ;
  41.         }
  42.         
  43.         return $query;
  44.     }
  45. }
复制代码
     Post Views:    31  
  You liked this article? You'd probably be a good match for our ever-growing tech team at Theodo.
            Join Us
黄邦珩 发表于 2016-10-8 12:15:50
有钱就是任性
回复 支持 反对

使用道具 举报

gzteambuy 发表于 2016-10-15 10:38:58
楼下的不要小看我,我可不是吃素的。
回复 支持 反对

使用道具 举报

贾益飞 发表于 2016-10-15 10:58:51
怪事年年有,今年特别多!
回复 支持 反对

使用道具 举报

初彤 发表于 2016-10-22 22:45:17
涨姿势
回复 支持 反对

使用道具 举报

黄凯 发表于 2016-10-23 00:45:25
楼猪V5啊
回复 支持 反对

使用道具 举报

jeanb 发表于 2016-10-26 18:41:31
你瞧你吧!看背影急煞千军万马,转过头吓退百万雄狮。
回复 支持 反对

使用道具 举报

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/c.CoLaBug.com ( 粤ICP备05003221号 | 粤公网安备 44010402000842号 )

© 2001-2017 Comsenz Inc.

返回顶部 返回列表