Overwriting values in listing page in EasyAdmin

57 views Asked by At

I have an associatation field, whats value can be null.

On the list page, I'd like to overwrite the null badge to my bagde, write N/A instead of null.

I tried with this:

public function configureFields(string $pageName): iterable
{
    $fields = parent::configureFields($pageName);
    $learningPathField = AssociationField::new('LearningPath');
    if ($pageName === Action::INDEX) {
        $learningPathField->setTemplatePath('admin/EasyAdmin/na.html.twig');
        //$learningPathField->setTemplatePath('@EasyAdmin/crud/field/association.html.twig');
    }
    if ($pageName === Action::NEW) {
        $learningPathField->setHelp('Warning! Once you set this, you can not change when you edit Learning Path!');
    }
    if ($pageName === Action::EDIT) {
        $learningPathField->setDisabled(true);
    }
    $fields[] = $learningPathField;
    return $fields;
}

The problem is. it is always use my na.html.twig becuase at this point, I do not know anything about the value of the associated field.

So my question is, how can I change the template based on value of the associated field, but only for this index page?

Now I just created my on file like this:

{# @var ea \EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext #}
{# @var field \EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto #}
{# @var entity \EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto #}
{%  if (entity.instance.LearningPath) is null %}
    <span class="badge badge-outline">N/A</span>
{% else %}
    <a href="{{ field.customOptions.get('relatedUrl') }}">{{ field.formattedValue }}</a>
{% endif %}

Is this the right way?

1

There are 1 answers

0
Neerfix On

From what I understand, you just want to display in the listing of your entity a badge 'N/A' if the value of your Association field is null, and the link to this entity if it is not null. You can simply define your field like this:

final public function configureFields(string $pageName): iterable
{
    return [
        // Other Fields
        AssociationField::new('category')
            ->setColumns(12),
    ];
}

AssociationField will take care of the rest regarding your display in the list. For my part, by defining my field as indicated above, I have this result: enter image description here

In French, 'Aucune' is for null values, and my link 'test' is for my defined category.


If you want to assign different badge based on the values of your field, you can use ChoiceField (Documentation) with renderAsBadge to customize each badge according to its value.

ChoiceField::new('status')->renderAsBadges([
                Project::STATUS_PUBLISH => 'success',
                Project::STATUS_PENDING => 'primary',
                Project::STATUS_DELETED => 'danger',
            ])->setChoices([
                'Publié' => Project::STATUS_PUBLISH,
                'Brouillon' => Project::STATUS_PENDING,
                'Archivé - Non affiché' => Project::STATUS_DELETED,