Skip to content
Open
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion doc/fields/ChoiceField.rst
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,15 @@ pages (``index`` and ``detail``)::

The built-in badge styles are the same as Bootstrap: ``'success'``,
``'warning'``, ``'danger'``, ``'info'``, ``'primary'``, ``'secondary'``,
``'light'``, ``'dark'``.
``'light'``, ``'dark'``, but you can also pass a custom
``EasyCorp\Bundle\EasyAdminBundle\Field\Style\BadgeStyle`` instance::

yield ChoiceField::new('...')->renderAsBadges([
// $value => $badgeStyleName
'paid' => BadgeStyle::new()->withBgColor('#00FF00'),
'pending' => BadgeStyle::new()->withBgColor('#FFFF00'),
'refunded' => BadgeStyle::new()->withBgColor('#FF0000'),
]);

renderAsNativeWidget
~~~~~~~~~~~~~~~~~~~~
Expand Down
18 changes: 13 additions & 5 deletions src/Field/ChoiceField.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace EasyCorp\Bundle\EasyAdminBundle\Field;

use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\Style\BadgeStyle;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Contracts\Translation\TranslatableInterface;

Expand All @@ -22,7 +23,8 @@ final class ChoiceField implements FieldInterface
public const OPTION_WIDGET = 'widget';
public const OPTION_ESCAPE_HTML_CONTENTS = 'escapeHtml';

public const VALID_BADGE_TYPES = ['success', 'warning', 'danger', 'info', 'primary', 'secondary', 'light', 'dark'];
/** @deprecated use BadgeStyle::VALID_BADGE_TYPES instead */
public const VALID_BADGE_TYPES = BadgeStyle::VALID_BADGE_TYPES;

public const WIDGET_AUTOCOMPLETE = 'autocomplete';
public const WIDGET_NATIVE = 'native';
Expand Down Expand Up @@ -116,7 +118,7 @@ public function setTranslatableChoices($choiceGenerator): self
*
* Possible badge types: 'success', 'warning', 'danger', 'info', 'primary', 'secondary', 'light', 'dark'
*
* @param array<string>|bool|callable $badgeSelector
* @param array<BadgeStyle|string>|bool|callable $badgeSelector
*/
public function renderAsBadges($badgeSelector = true): self
{
Expand All @@ -125,11 +127,17 @@ public function renderAsBadges($badgeSelector = true): self
}

if (\is_array($badgeSelector)) {
foreach ($badgeSelector as $badgeType) {
if (!\in_array($badgeType, self::VALID_BADGE_TYPES, true)) {
throw new \InvalidArgumentException(sprintf('The values of the array passed to the "%s" method must be one of the following valid badge types: "%s" ("%s" given).', __METHOD__, implode(', ', self::VALID_BADGE_TYPES), $badgeType));
$badges = [];
foreach ($badgeSelector as $key => $badge) {
if ($badge instanceof BadgeStyle) {
$badges[$key] = $badge;
} elseif (\in_array($badge, BadgeStyle::VALID_BADGE_TYPES, true)) {
$badges[$key] = BadgeStyle::new()->withType($badge);
} else {
throw new \InvalidArgumentException(sprintf('The values of the array passed to the "%s" method must be an instance of "%s" or one of the following valid badge types: "%s" ("%s" given).', __METHOD__, BadgeStyle::class, implode(', ', BadgeStyle::VALID_BADGE_TYPES), $badge));
}
}
$badgeSelector = $badges;
}

$this->setCustomOption(self::OPTION_RENDER_AS_BADGES, $badgeSelector);
Expand Down
33 changes: 18 additions & 15 deletions src/Field/Configurator/ChoiceConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\Style\BadgeStyle;
use EasyCorp\Bundle\EasyAdminBundle\Translation\TranslatableChoiceMessage;
use EasyCorp\Bundle\EasyAdminBundle\Translation\TranslatableChoiceMessageCollection;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\EnumType;
use function Symfony\Component\String\u;
use function Symfony\Component\Translation\t;
use Symfony\Component\Translation\TranslatableMessage;
use Symfony\Contracts\Translation\TranslatableInterface;
Expand Down Expand Up @@ -141,10 +141,13 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
);
}

$badge = $isRenderedAsBadge ? $this->getBadgeStyle($badgeSelector, $selectedValue, $field) : null;

/** @var TranslatableMessage $choiceMessage */
$choiceMessages[] = new TranslatableChoiceMessage(
$choiceMessage,
$isRenderedAsBadge ? $this->getBadgeCssClass($badgeSelector, $selectedValue, $field) : null
$badge?->getClasses(),
$badge?->getStyle(),
);
}
}
Expand All @@ -170,27 +173,27 @@ private function getChoices(array|callable|null $choiceGenerator, EntityDto $ent
}

/**
* @param array<string>|bool|callable|null $badgeSelector
* @param array<BadgeStyle>|bool|callable|null $badgeSelector
*/
private function getBadgeCssClass(array|bool|callable|null $badgeSelector, mixed $value, FieldDto $field): string
private function getBadgeStyle(array|bool|callable|null $badgeSelector, mixed $value, FieldDto $field): ?BadgeStyle
{
$commonBadgeCssClass = 'badge';

$badgeType = '';
$badge = null;
if (true === $badgeSelector) {
$badgeType = 'badge-secondary';
$badge = BadgeStyle::new()->withType('secondary');
} elseif (\is_array($badgeSelector)) {
$badgeType = $badgeSelector[$value] ?? 'badge-secondary';
$badge = $badgeSelector[$value] ?? BadgeStyle::new()->withType('secondary');
} elseif (\is_callable($badgeSelector)) {
$badgeType = $badgeSelector($value, $field);
if (!\in_array($badgeType, ChoiceField::VALID_BADGE_TYPES, true)) {
throw new \RuntimeException(sprintf('The value returned by the callable passed to the "renderAsBadges()" method must be one of the following valid badge types: "%s" ("%s" given).', implode(', ', ChoiceField::VALID_BADGE_TYPES), $badgeType));
$result = $badgeSelector($value, $field);
if ($result instanceof BadgeStyle) {
$badge = $result;
} elseif (\in_array($result, BadgeStyle::VALID_BADGE_TYPES, true)) {
$badge = BadgeStyle::new()->withType($result);
} else {
throw new \RuntimeException(sprintf('The value returned by the callable passed to the "renderAsBadges()" method must be an instance of "%s" or one of the following valid badge types: "%s" ("%s" given).', BadgeStyle::class, implode(', ', BadgeStyle::VALID_BADGE_TYPES), $result));
}
}

$badgeTypeCssClass = '' === $badgeType ? '' : u($badgeType)->ensureStart('badge-')->toString();

return $commonBadgeCssClass.' '.$badgeTypeCssClass;
return $badge;
}

/**
Expand Down
107 changes: 107 additions & 0 deletions src/Field/Style/BadgeStyle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Field\Style;
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure in which namespace I should declare this class


final class BadgeStyle
{
public const VALID_BADGE_TYPES = ['success', 'warning', 'danger', 'info', 'primary', 'secondary', 'light', 'dark'];

/**
* @param array<string> $classes
* @param array<string, string> $style
*/
private function __construct(private array $classes, private array $style)
{
}

public static function new(): self
{
return new self(['badge'], []);
}

public function withBgColor(string $backgroundColor, bool $autoTextContrast = true): self
Copy link
Contributor Author

@VincentLanglet VincentLanglet Jun 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if

  • we should disable autoTextContrast by default
  • we shouldn't provide such option and let the user decide (but it require to have public addClass method

{
if ($autoTextContrast) {
$this->addClass(self::generateTextClassFromBackgroundColor($backgroundColor));
}

return $this->addStyle('background-color', $backgroundColor);
}

public function withTextColor(string $textColor): self
{
return $this->addStyle('color', $textColor);
}

/**
* @param value-of<self::VALID_BADGE_TYPES> $type
*/
public function withType(string $type): self
{
if (!\in_array($type, self::VALID_BADGE_TYPES, true)) {
throw new \InvalidArgumentException(sprintf('Invalid badge type "%s". Allowed types are: "%s".', $type, implode(', ', self::VALID_BADGE_TYPES)));
}

return $this->addClass('badge-'.$type);
}

public function asPill(): self
{
return $this->addClass('badge-pill');
}

public function getClasses(): ?string
{
if ([] === $this->classes) {
return null;
}

return implode(' ', $this->classes);
}

public function getStyle(): ?string
{
if ([] === $this->style) {
return null;
}


$style = [];
foreach ($this->style as $key => $value) {
$style[] = sprintf('%s:%s;', $key, $value);
}

return implode(' ', $style);
}

private function addClass(string $class): self
{
$this->classes[] = $class;

return $this;
}

private function addStyle(string $key, string $value): self
{
$this->style[$key] = $value;

return $this;
}

private static function generateTextClassFromBackgroundColor(string $backgroundColor): string
{
if (1 !== preg_match('/^#[0-9a-f]{6}$/iD', $backgroundColor)) {
throw new \InvalidArgumentException(sprintf('Only full 6-digit hexadecimal color are supported to generate the appropriate text color ("%s" given).', $backgroundColor));
}

[$r, $g, $b] = [
hexdec(substr($backgroundColor, 1, 2)),
hexdec(substr($backgroundColor, 3, 2)),
hexdec(substr($backgroundColor, 5, 2)),
];

$luminance = (0.299 * $r + 0.587 * $g + 0.114 * $b) / 255;

return $luminance > 0.5 ? 'text-dark' : 'text-light';
}
}
24 changes: 16 additions & 8 deletions src/Translation/TranslatableChoiceMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,26 +19,34 @@ final class TranslatableChoiceMessage implements TranslatableInterface
public function __construct(
private TranslatableInterface $message,
private ?string $cssClass,
private ?string $style = null,
) {
}

public function trans(TranslatorInterface $translator, ?string $locale = null): string
{
$message = $this->message->trans($translator, $locale);

if (null !== $this->cssClass) {
return sprintf('<span class="%s">%s</span>', $this->cssClass, $message);
}

return $message;
return $this->generateHtml($message);
}

public function __toString(): string
{
if (null !== $this->cssClass) {
return sprintf('<span class="%s">%s</span>', $this->cssClass, $this->message);
return $this->generateHtml((string) $this->message);
}

private function generateHtml(string $message): string
{
if (null !== $this->cssClass || null !== $this->style) {
return sprintf(
'<span %s%s%s>%s</span>',
null !== $this->cssClass ? sprintf('class="%s"', $this->cssClass) : '',
null !== $this->cssClass && null !== $this->style ? ' ' : '',
null !== $this->style ? sprintf('style="%s"', $this->style) : '',
$message
);
}

return (string) $this->message;
return $message;
}
}
13 changes: 13 additions & 0 deletions tests/Field/ChoiceFieldTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\ChoiceConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Style\BadgeStyle;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Field\Fixtures\ChoiceField\PriorityUnitEnum;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Field\Fixtures\ChoiceField\StatusBackedEnum;
use function Symfony\Component\Translation\t;
Expand Down Expand Up @@ -171,5 +172,17 @@ public function testBadges()

$field->setValue([1, 3])->renderAsBadges(function ($value) { return $value > 1 ? 'success' : 'primary'; });
self::assertSame('<span class="badge badge-primary">a</span><span class="badge badge-success">c</span>', (string) $this->configure($field)->getFormattedValue());

$field->setValue(1)->renderAsBadges([1 => BadgeStyle::new()->withBgColor('#123456'), '3' => BadgeStyle::new()->withBgColor('#AAAAAA')]);
self::assertSame('<span class="badge text-light" style="background-color:#123456;">a</span>', (string) $this->configure($field)->getFormattedValue());

$field->setValue([1, 3])->renderAsBadges([1 => BadgeStyle::new()->withBgColor('#123456'), '3' => BadgeStyle::new()->withBgColor('#AAAAAA')]);
self::assertSame('<span class="badge text-light" style="background-color:#123456;">a</span><span class="badge text-dark" style="background-color:#AAAAAA;">c</span>', (string) $this->configure($field)->getFormattedValue());

$field->setValue(1)->renderAsBadges(function ($value) { return $value > 1 ? BadgeStyle::new()->withBgColor('#AAAAAA') : BadgeStyle::new()->withBgColor('#123456'); });
self::assertSame('<span class="badge text-light" style="background-color:#123456;">a</span>', (string) $this->configure($field)->getFormattedValue());

$field->setValue([1, 3])->renderAsBadges(function ($value) { return $value > 1 ? BadgeStyle::new()->withBgColor('#AAAAAA') : BadgeStyle::new()->withBgColor('#123456'); });
self::assertSame('<span class="badge text-light" style="background-color:#123456;">a</span><span class="badge text-dark" style="background-color:#AAAAAA;">c</span>', (string) $this->configure($field)->getFormattedValue());
}
}