Search code examples
phpsymfonysonata-admin

Sonata admin bundle, how do not show any results and don't execute any query to DB if user don't select any filters?


I have typical sonata-admin list action with createQuery, configureFormFields, etc. How i can render standard page but if user don't select any filters, i show him only "select any filter for getting results"?

I can use hasFilters checked but query still executed.

{% if  admin.hasFilters() %}
    {{ parent() }}
{% else %}

I need some just like that, but without execute any query to DB.

// SomeController
public function listAction()
{
    if (!$this->admin->hasFilters()) {
        return $this->renderWithExtraParams($this->admin->getTemplate('list'), [
            'action' => 'list',
            'form' => $this->admin->getDatagrid()->getForm()->createView(),
            'csrf_token' => $this->getCsrfToken('sonata.batch'),
            'export_formats' => $this->has('sonata.admin.admin_exporter') ?
                $this->get('sonata.admin.admin_exporter')->getAvailableFormats($this->admin) :
                $this->admin->getExportFormats(),
        ], null);
    }

    return parent::listAction();
}

Solution

  • This is kludge but it's working. Just add this:

    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);
    
        if (!$this->hasFilters()) {
            $query->where('1 = 0');
    
            return $query;
        }
    
        // ...
    }