我有一个 Vehicle 类型的元素列表,我使用 Sonata Admin 显示这些元素。我允许通过“状态”字段过滤这些元素,但我希望,当显示列表时,仅显示活动车辆,如果有人想查看非活动车辆,请使用过滤器并选择非活动状态。我想知道是否有人知道如何使用 Sonata Admin 默认对元素列表应用过滤器。
这是我的代码:
public function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('name')
->add('status')
;
}
protected function configureDatagridFilters(DatagridMapper $mapper)
{
$mapper
->add('name')
->add('status')
;
}
是否可以在configureDatagridFilters()中的状态字段中添加任何选项来实现此目标?还有其他选择吗?
提前致谢。
您必须重写
$datagridValues
属性,如下所示(对于 status > 0
,如果它是整数):
/**
* 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'.
);
你也可以用这个方法
public function getFilterParameters()
{
$this->datagridValues = array_merge(
array(
'status' => array (
'type' => 1,
'value' => 0
),
// exemple with date range
'updatedAt' => array(
'type' => 1,
'value' => array(
'start' => array(
'day' => date('j'),
'month' => date('m'),
'year' => date('Y')
),
'end' => array(
'day' => date('j'),
'month' => date('m'),
'year' => date('Y')
)
),
)
),
$this->datagridValues
);
return parent::getFilterParameters();
}
使用上述两种建议的方法将破坏过滤器的“重置”行为,因为我们总是强制过滤器按默认值进行过滤。对我来说,我认为最好的方法是使用 getFilterParameters 函数(因为我们可以在其中添加逻辑而不是静态添加值)并检查用户是否单击了“重置按钮”
/**
* {@inheritdoc}
*/
public function getFilterParameters()
{
// build the values array
if ($this->hasRequest()) {
$reset = $this->request->query->get('filters') === 'reset';
if (!$reset) {
$this->datagridValues = array_merge(array(
'status' => array (
'type' => 1,
'value' => 0
),
),
$this->datagridValues
);
}
}
return parent::getFilterParameters();
}
自 sonata-admin 4.0 起,函数
getFilterParameters()
被标记为最终函数,并且 $datagridValues 不再存在。
所以你需要重写
configureDefaultFilterValues()
函数
protected function configureDefaultFilterValues(array &$filterValues): void
{
$filterValues['foo'] = [
'type' => ContainsOperatorType::TYPE_CONTAINS,
'value' => 'bar',
];
}
更多详细信息:https://symfony.com/bundles/SonataAdminBundle/current/reference/action_list.html#default-filters
另一种方法是使用 createQuery 和 getPercientParameters 来强制执行不可见过滤器。这种方法最好有完全可定制的过滤器。在这里查看我的文章:
http://www.theodo.fr/blog/2016/09/sonata-for-symfony-hide-your-filters/