如何有默认值的过滤器与会话[Sonata管理]


How have default value in filter with session [Sonata Admin]

我想为filterParameters的默认值设置一个动态的session值

下面的代码:

/**
 * Default Datagrid values
 *
 * @var array
 */
protected $datagridValues = array(
    'applications' => array('value' => 'Sport TV'),
    '_sort_order' => 'ASC'
);
// Fields to be shown on filter forms
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper
        ->add('title')
        ->add('applications', null, array('label' => 'Chaîne'), null, array('expanded' => true, 'multiple' => true));
}

但是当我添加会话时,他不希望我在外部使用它功能:

public function getApplicationsSession()
{
    $session = new Session();
    return $session->get('applications');
}
/**
 * Default Datagrid values
 *
 * @var array
 */
protected $datagridValues = array(
    'applications' => array('value' => $this->getApplicationsSession()),
    '_sort_order' => 'ASC'
);

我有这样的错误:

Parse Error: syntax error, unexpected '$this' (T_VARIABLE)

谢谢你的帮助。

这部分代码是错误原因:

protected $datagridValues = array(
    'applications' => array('value' => $this->getApplicationsSession()),
                                         ^---- syntax error !
    '_sort_order' => 'ASC'
);

伪变量$this在对象上下文中调用方法时可用。$this是对调用对象的引用(通常是方法所属的对象)。http://php.net/manual/en/language.oop5.basic.php

要解决这个问题,应该重写getFilterParameters()方法:

public function getFilterParameters()
{
    $this->datagridValues['applications']['value'] = $this->getApplicationsSession();
    return parent::getFilterParameters();
}