Last active
July 18, 2023 18:04
-
-
Save dbu/9524776 to your computer and use it in GitHub Desktop.
Case insensitive filtering with sonata admin in postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Liip\AcmeBundle\Filter; | |
use Sonata\AdminBundle\Form\Type\Filter\ChoiceType; | |
use Sonata\AdminBundle\Datagrid\ProxyQueryInterface; | |
use Sonata\DoctrineORMAdminBundle\Filter\StringFilter; | |
class CaseInsensitiveStringFilter extends StringFilter | |
{ | |
/** | |
* {@inheritdoc} | |
*/ | |
public function filter(ProxyQueryInterface $queryBuilder, $alias, $field, $data) | |
{ | |
if (!$data || !is_array($data) || !array_key_exists('value', $data)) { | |
return; | |
} | |
$data['value'] = trim($data['value']); | |
if (strlen($data['value']) == 0) { | |
return; | |
} | |
$data['type'] = !isset($data['type']) ? ChoiceType::TYPE_CONTAINS : $data['type']; | |
$operator = $this->getOperator((int) $data['type']); | |
if (!$operator) { | |
$operator = 'LIKE'; | |
} | |
// c.name > '1' => c.name OPERATOR :FIELDNAME | |
$parameterName = $this->getNewParameterName($queryBuilder); | |
// This is the first difference | |
// | | |
// V | |
$this->applyWhere($queryBuilder, sprintf('lower(%s.%s) %s :%s', $alias, $field, $operator, $parameterName)); | |
if ($data['type'] == ChoiceType::TYPE_EQUAL) { | |
// This is the second difference | |
// | | |
// V | |
$queryBuilder->setParameter($parameterName, strtolower($data['value'])); | |
} else { | |
$queryBuilder->setParameter($parameterName, sprintf($this->getOption('format'), strtolower($data['value']))); | |
} | |
} | |
/** | |
* exact copy-paste because private method | |
*/ | |
private function getOperator($type) | |
{ | |
$choices = array( | |
ChoiceType::TYPE_CONTAINS => 'ILIKE', | |
ChoiceType::TYPE_NOT_CONTAINS => 'NOT LIKE', | |
ChoiceType::TYPE_EQUAL => '=', | |
); | |
return isset($choices[$type]) ? $choices[$type] : false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is updated version for sonata admin v3
replace this two methods with above code