简体   繁体   中英

sonata admin custom list field (not from entity)

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; } ]); } 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM