Symfony2 - Give a default filter in a list of elements of Sonata Admin

Airam picture Airam · Apr 25, 2013 · Viewed 14.6k times · Source

I have a list of elements of type Vehicle and I show these elements with Sonata Admin. I allow to filter these elements by the "status" field, but I want that, when the list is showed, only the active vehicles are showed, and if somebody wants to see the inactive vehicles, uses the filter and select the inactive status. I would like to know if somebody Knows the way to apply filters by default for a list of elements using Sonata Admin.

Here is my code:

public function configureListFields(ListMapper $listMapper)
{
    $listMapper
        ->addIdentifier('name')
        ->add('status')
    ;
}

protected function configureDatagridFilters(DatagridMapper $mapper)
 {
     $mapper
         ->add('name')
         ->add('status')
     ;
 }

Is there any option that can be added to the status field in configureDatagridFilters() to achieve this goal? Other options?

Thanks in advance.

Answer

AlterPHP picture AlterPHP · Apr 25, 2013

You have to override $datagridValues property as following (for status > 0 if it's an integer) :

   /**
    * Default Datagrid values
    *
    * @var array
    */
   protected $datagridValues = array (
           'status' => array ('type' => 2, 'value' => 0), // type 2 : >
           '_page' => 1, // Display the first page (default = 1)
           '_sort_order' => 'DESC', // Descendant ordering (default = 'ASC')
           '_sort_by' => 'id' // name of the ordered field (default = the model id field, if any)
      // the '_sort_by' key can be of the form 'mySubModel.mySubSubModel.myField'.
   );

source: Configure the default page and ordering in the list view