c.bermon
c.bermon

Reputation: 79

Sonata admin: mosaic selected by default

I am using Sonata Admin and I have a list and a mosaic view. How to select the mosaic view by default?
I do not want to HIDE the list view, just select the mosaic view by default.

Upvotes: 4

Views: 765

Answers (2)

jo66
jo66

Reputation: 99

In the method getListMode we see that the list mode is called per default.

So in my opinion the simplest way is to override getListMode and to replace 'list' by 'mosaic'.

public function getListMode()
{
    if (!$this->hasRequest()) {
        return 'mosaic';
    }

    return $this->getRequest()->getSession()->get(sprintf('%s.list_mode', $this->getCode()), 'mosaic');
}

Upvotes: 1

cezar
cezar

Reputation: 12012

The Admin classes inherit from AbstractAdmin. If we have an Entity class Foo, we would create an Admin class FooAdmin extending Sonata\AdminBundle\Admin\AbstractAdmin.

Let's take a look into the source code:

public function setListMode($mode)
{
    if (!$this->hasRequest()) {
        throw new \RuntimeException(sprintf('No request attached to the current admin: %s', $this->getCode()));
    }

    $this->getRequest()->getSession()->set(sprintf('%s.list_mode', $this->getCode()), $mode);
}

public function getListMode()
{
    if (!$this->hasRequest()) {
        return 'list';
    }

    return $this->getRequest()->getSession()->get(sprintf('%s.list_mode', $this->getCode()), 'list');
}

These are the methods that set and get the list mode. There are buttons for two list modes: list and mosaic. If you hover with the mouse pointer you'll see that they point to the same URL, but with different parameters:

  • /list?_list_mode=list
  • /list?_list_mode=mosaic

In the method getListMode we see that the list mode is called per default.

The way I found out to set mosaic as default is to call the method setListMode in the Admin class:

protected function configureListFields(ListMapper $listMapper)
{
    if ($mode = $this->request->query->get('_list_mode')) {
        $this->setListMode($mode);
    } else {
        $this->setListMode('mosaic');
    }

    $listMapper
        ->addIdentifier('fooId')
        ->add('fooBar')
    ;
}

I hope it can help someone. I was looking for more elegant ways, like setting in the admin service, but couldn't find a better solution. If someone has other suggestions, I'd be happy to learn something new.

Upvotes: 4

Related Questions