自定义Symfony filter(过滤器)

更多内容在[url]http://www.onepie.org[/url]

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

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

1. 关联表字段查询

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

在[b]sfFormFilterDoctrine[/b]中有方法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方法即可以自定义每个字段的查询,所以只要添加如下代码
[code]
public function addUsernameColumnQuery(Doctrine_Query $query, $field, $value)
{
$query->leftJoin('r.User u');
if(!empty($value)){
$query->andWhere('u.name like ?', "%$value%");
}
}
[/code]
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值