MylesK
MylesK

Reputation: 4359

Sonata default filter value

I have a property in my method configureDatagridFilters() called assignee. When the list view of my admin is first loaded, I'd like to set the value of this property to the current user.

I have tried:

public function getFilterParameters()
{
    $parameters = parent::getFilterParameters();

    $parameters['assignee'] = [
        'value' => $this->getUser(),
    ];

    return $parameters;
}

as well as an array_merge instead. None of them achieved what I'm after, it still just shows me the default/entire list.

I have tried adding a type, bit unclear as to what the type is as some examples I've seen are like EntityType::class and others just a number 3.

Upvotes: 0

Views: 1734

Answers (2)

Andrew Zhilin
Andrew Zhilin

Reputation: 1708

Accepted answer is kind of wrong. You will not be able to change "asignee" filter - so its not a "default", but "forced filter" behavior. You should add array_key_exists checks to code like

public function getFilterParameters()
{
    $parameters = parent::getFilterParameters();

    if (!array_key_exists('assignee', parameters)) {        
        $parameters['assignee'] = [
             'value' => $this->getUser()->getId(),
        ];
    }

    return $parameters;
}

Upvotes: 0

MylesK
MylesK

Reputation: 4359

So I figured out how to set the filter by default to the current user.

My filter is an EntityType::class with the class of User::class. In order for the code snippet above to work, you must set the value to the user ID and not the user object like so: 'value' => $this->getUser()->getId().

So the full method would be:

public function getFilterParameters()
{
    $parameters = parent::getFilterParameters();

    $parameters['assignee'] = [
        'value' => $this->getUser()->getId(),
    ];

    return $parameters;
}

Upvotes: 3

Related Questions