问题
I have an entity Transaction with numerous status codes. I want the user to be able to see these status codes as strings in SonataAdmin. The user should also be able to filter on the basis of these status codes.
Entity Transaction
{
const TRANSACTION_STATUS_WAITING = 1;
const TRANSACTION_STATUS_PENDING = 2;
const TRANSACTION_STATUS_CONFIRMED = 3;
/**
* Set status
*
* @param smallint $status
*/
public function setStatus($status)
{
$this->status = $status;
}
/**
* Get status
*
* @return smallint
*/
public function getStatus()
{
return $this->status;
}
public function getStatusAsString()
{
switch($this->status){
case(self::TRANSACTION_STATUS_WAITING): return "Waiting for Merchant";
case(self::TRANSACTION_STATUS_PENDING): return "Pending Confirmation";
case(self::TRANSACTION_STATUS_CONFIRMED): return "Confirmed";
}
}
}
I have configured my Sonata List Mapper like this:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('id')
->add('statusAsString', null, array('sortable' => true, 'label' => 'Status'))
}
which works perfectly fine:
However I am unable to use the same as a Filter.
If I try this:
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('user')
->add('status') // Works well
->add('statusAsString', null, array('label' => 'Status')) // Doesn't work:
;
}
This doesn't work. It gives the following error ->
Notice: Undefined index: statusAsString in ..../Sonata\DoctrineORMAdminBundle\Guesser\FilterTypeGuesser.php
How can I make it work?
回答1:
This worked as a temporary solution for me. If anyone has a better solution, please share.
$datagridMapper
->add('status', 'doctrine_orm_string', array(),
'choice', array('choices' => Transaction::getStatusList())
);
In the entity
public static function getStatusList()
{
return array(
self::TRANSACTION_STATUS_WAITING => "Waiting",
self::TRANSACTION_STATUS_PENDING_CONFIRMATION => "Pending Confirmation",
self::TRANSACTION_STATUS_CONFIRMED => "Confirmed",
self::TRANSACTION_STATUS_PAYMENT_REQUESTED => "Payment Requested",);
}
回答2:
Something like that
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('codes', 'doctrine_orm_callback', array(
'label' => 'Код',
'callback' => array($this, 'getCodesFilter'),
'field_type' => 'genemu_jquerychosen',
'field_options' => array(
'class' => 'Mtools\ClientBundle\Entity\Client',
'widget' => 'entity',
'multiple' => false,
)
);
}
public function getCodesFilter($queryBuilder, $alias, $field, $value)
{
if (!$value) {
return;
}
$queryBuilder->leftJoin(sprintf('%s.codes', $alias), 'c');
$queryBuilder->andWhere('c.code = :code');
$queryBuilder->setParameter('code', $value['value']);
}
来源:https://stackoverflow.com/questions/10224280/how-can-i-create-a-custom-datagrid-filter-in-sonataadmin