`
superjavason
  • 浏览: 108929 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

自定义Symfony filter(过滤器)

阅读更多
更多内容在http://www.onepie.org

symfony自动生成的Filter有一些局限性,比如不能过滤关联表的特定字段,过滤的表单只有input和select两种,

下面介绍处理上面两个问题的解决方案。

1. 关联表字段查询

假设我们有Order和User两张表,Order中有user_id和User关联,Syfmony默认可以通过user_id来过滤,现在想通过User的name字段模糊查询获得用户的所有订单。

sfFormFilterDoctrine中有方法doBuildQuery,
 if ($this->getTable()->hasField($field))
      {
        $method = sprintf('add%sColumnQuery', self::camelize($this->getFieldName($field)));
      }
      else if (!method_exists($this, $method = sprintf('add%sColumnQuery', self::camelize($field))) && null !== $type)
      {
        throw new LogicException(sprintf('You must define a "%s" method to be able to filter with the "%s" field.', $method, $field));
      }


从上面的代码可以看出只要增加一个add%FiledName%ColumnQuery方法即可以自定义每个字段的查询,所以只要添加如下代码
public function addUsernameColumnQuery(Doctrine_Query $query, $field, $value)
  {
    $query->leftJoin('r.User u');
    if(!empty($value)){
      $query->andWhere('u.name like ?', "%$value%");
    }     
  }

2. 自定义Filter表单字段类型

假设我们有一张商品表Product, 其中有一个字段status,我们需要使用checkbox选择多个状态来过滤商品
首先在ProductFormFilter的configure函数中添加
  
  $this->widgetSchema['status'] = new sfWidgetFormChoice(array(
      'choices' => self::$STATUS_TEXT,
      'multiple' => true,
      'expanded' => true,
    ));

    $this->validatorSchema['status'] = new sfValidatorChoice(array(
      'required' => false,
      'multiple' => true,
      'choices' => array_keys(self::$STATUS_TEXT),
    ));

这和定义Form的widget一样,但是如果这样的还不行, 因为涉及到多选,但默认status是input的类型,所以我们需要让symfony知道我们现在传过来的参数可能是数组,在filter中重载getFields方法,把status字段设为ForeignKey类型
 public function getFields()
  {
    $fields = parent::getFields();
    $fields["status"] = "ForeignKey";
    return $fields;
  }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics