Symfony: generate-admin filters customization

In this post we will see how to customize the generate-admin filters to get more customized filters adapted to our needs.

If some time we used the Symfony generate-admin we could see that we have the ability to filter what data to show. These filters allow us to filter by whatever existing field in the entity. Now, we will see how to add a customized field to the filters, so we can filter according to our needs.

Let’s suppose we have an User and Phonenumber objects and in the phonenumbers list we want to filter by user. To do that we can modify the generator.yml file in the phonenumber module. In phonenumber/config/generator.yml:

1
2
3
config:
  filter:
    display: [ another, field, user_by_name]

Also, we need to define the widget and validator to this new field in lib/filter/doctrine/PhonenumberFormFilter.class.php:

1
2
3
4
5
6
7
8
9
<?php
public function configure()
{
    //...
    $this->setWidget('user_by_name', new sfWidgetFormFilterInput(array('with_empty' => false));
 
    //...
    $this->setValidator('user_by_name', new sfValidatorPass(array('required' => false));
}

In the same form class we need to overwrite the getFields() method with the new added field:

1
2
3
4
5
6
7
8
<?php
public function getFields()
{
    $fields = parent::getFields();
    $fields['user_by_name'] = 'custom';
   
    return $fields;
}

And last, we need to add the method which does the filtering, this field follows the convention addColumnNameColumnCriteria:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
public function addUserByNameColumnQuery($query, $field, $value)
{
    $text = $value['text'];
    if ($text) {
        $query->leftJoin($query->getRootAlias().'.User u')->andWhere('(u.first_name LIKE ?
            OR u.last_name LIKE ?
            OR u.username LIKE ?)'
, array("%$text%", "%$text%", "%$text%"));
    }
   
    return $query;
}

Done. We have a customized filter.