-->

sonata admin custom list field (not from entity)

2020-06-28 07:30发布

问题:

Sonata admin bundle documentation seems scarce and I did not find a way implement this.

Goal: display boolean value in field list. Value should calculated for each object from other properties.

I managed to implement this for datagridFilter as doctrine_orm_callback but not for listFields.

Working code for configureDatagridFilters():

// LicenceAdmin.php
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
    $datagridMapper->add('isValid', 'doctrine_orm_callback', [
            'callback' => [$this, 'isValidFilterCallback'],
            'field_type' => 'checkbox',
        ]);
}
public function isValidFilterCallback($queryBuilder, $alias, $field, $value)
{
    // if no value or value == false means unchecked checkbox - show all instances
    if (!$value || empty($value['value'])) {
        return;
    }
    // if checked, display only by active logic
    $dateNow = new \DateTime();
    $queryBuilder
        ->andWhere("{$alias}.isActive = 1")
        ->andWhere("{$alias}.validFrom <= :date")
        ->andWhere("{$alias}.validTo > :date")
        ->setParameter('date', $dateNow)
    ;
}

Questions

  1. How would I this implement this for configureListFields()? Tried several ways using same logic from working configureDatagridFilters() with no success.
  2. Is this possible without queryBuilder and DQL? I would rather use entity object and its properties for logic. Something like:

    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper->add('isValid', 'callback', [
            'callback' => function($object) { <-- IMAGINARY FUNCTIONALITY
                if ($object->getIsValid()) return true;
                else return false;
            }
        ]);
    }
    

回答1:

I believe the answer is easier than what you are looking for, unless I did not get what you are after.

In your entity, create the following method

public function isValid()
{
// do your business logic here
}

In your admin form listing then

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper->add('isValid', 'boolean');
}

Hope this helps.