如何在一个过滤器中过滤多个字段?

时间:2013-01-31 09:43:05

标签: php symfony sonata-admin

是否可以创建搜索过滤器,从而不是从一个字段进行搜索,而是从CONCAT(name, description)

进行搜索
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper->add('search');
}

3 个答案:

答案 0 :(得分:5)

我找到了doctrine_orm_callback类型的解决方案

protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{


    $datagridMapper
        ->add( 'text', 'doctrine_orm_callback', array(
            'callback' => array($this, 'getSearchFilter'),
            'field_type' => 'text'
        ) );
}

public function getSearchFilter($queryBuilder, $alias, $field, $value) {
    if (!$value['value']) {
        return;
    }

    $exp = new \Doctrine\ORM\Query\Expr();
    $queryBuilder->andWhere($exp->like($exp->concat($alias.'.name', $alias.'.description'), $exp->literal('%' . $value['value'] . '%')));

    return true;
}    

答案 1 :(得分:2)

@Liutas的绝佳解决方案!

如果您只想使用 concat 作为搜索多个字段的变通方法,则可以使用以下代码:

public function getFullTextFilter($queryBuilder, $alias, $field, $value)
{
    if (!$value['value']) {
        return;
    }

    $queryBuilder->andWhere($queryBuilder->expr()->orX(
        $queryBuilder->expr()->like($alias.'.name', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
        $queryBuilder->expr()->like($alias.'.description', $queryBuilder->expr()->literal('%' . $value['value'] . '%')),
        $queryBuilder->expr()->like($alias.'.anotherfield', $queryBuilder->expr()->literal('%' . $value['value'] . '%'))
    ));

    return true;
}

答案 2 :(得分:1)

基于@webDEVILopers'回答,这是一个可以在任何领域使用的泛型类:

use Doctrine\ORM\Query\Expr;
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface;
use Sonata\DoctrineORMAdminBundle\Filter\BooleanFilter;

class MultiStringFilter extends BooleanFilter
{
    /**
     * @param string $field should be in the form field1-field2-…-fieldn
     */
    public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data)
    {
        $fields = explode('-', $field);
        $filterActive = $data['value'];
        if ($filterActive === null) {
            return;
        }

        $subConditions = [];
        foreach ($fields as $field) {

            $subConditions[] = $queryBuilder->expr()->like(
                "LOWER($alias.$field)",
                $queryBuilder->expr()->literal('%' . strtolower($data['value']) . '%')
            );
        }

        if (count($subConditions) > 1) {
            $queryBuilder->andWhere(new Expr\Orx($subConditions));
        }
    }
}