Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
9 changes: 8 additions & 1 deletion src/Factory/FieldFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Field\ArrayField;
use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateField;
use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;
Expand Down Expand Up @@ -187,7 +188,13 @@ private function replaceGenericFieldsWithSpecificFields(FieldCollection $fields,
}
/** @phpstan-ignore-next-line function.alreadyNarrowedType */
$fieldType = property_exists($fieldMapping, 'type') ? $fieldMapping->type : $fieldMapping['type'];
$guessedFieldFqcn = self::$doctrineTypeToFieldFqcn[$fieldType] ?? null;

// Special handling for enums, that are represented as string or as a simple array of strings
if ((Types::STRING === $fieldType || Types::SIMPLE_ARRAY === $fieldType) && isset($fieldMapping['enumType'])) {
$guessedFieldFqcn = ChoiceField::class;
} else {
$guessedFieldFqcn = self::$doctrineTypeToFieldFqcn[$fieldType] ?? null;
}
if (null === $guessedFieldFqcn) {
throw new \RuntimeException(sprintf('The Doctrine type of the "%s" field is "%s", which is not supported by EasyAdmin. For Doctrine\'s Custom Mapping Types have a look at EasyAdmin\'s field docs.', $fieldDto->getProperty(), $fieldType));
}
Expand Down
22 changes: 14 additions & 8 deletions src/Field/Configurator/ChoiceConfigurator.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$choicesSupportTranslatableInterface = false;
$isExpanded = true === $field->getCustomOption(ChoiceField::OPTION_RENDER_EXPANDED);
$isMultipleChoice = true === $field->getCustomOption(ChoiceField::OPTION_ALLOW_MULTIPLE_CHOICES);
$isIndexOrDetail = \in_array($context->getCrud()->getCurrentPage(), [Crud::PAGE_INDEX, Crud::PAGE_DETAIL], true);

$choices = $this->getChoices($field->getCustomOption(ChoiceField::OPTION_CHOICES), $entityDto, $field);

Expand Down Expand Up @@ -60,18 +61,24 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
}

if ($allChoicesAreEnums && array_is_list($choices) && \count($choices) > 0) {
$processedEnumChoices = [];
foreach ($choices as $choice) {
$processedEnumChoices[$choice->name] = $choice;
}

$choices = $processedEnumChoices;

// Update form type to be EnumType if current form type is still ChoiceType
// Leave the form type as is if user set something else explicitly
if (ChoiceType::class === $field->getFormType()) {
$field->setFormType(EnumType::class);
}

// When dealing with enums that implement TranslatableInterface, they are now translated by Symfony only if
// the keys of the choices are integers in forms.
// So, keep choices with integer keys if using EnumType with translatable enum, otherwise set name as key.
if ($isIndexOrDetail || !$choicesSupportTranslatableInterface || EnumType::class !== $field->getFormType()) {
$processedEnumChoices = [];
foreach ($choices as $choice) {
$processedEnumChoices[$choice->name] = $choice;
}

$choices = $processedEnumChoices;
}

$field->setFormTypeOptionIfNotSet('class', $enumTypeClass);
}

Expand Down Expand Up @@ -110,7 +117,6 @@ public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $c
$field->setFormTypeOption('attr.data-ea-autocomplete-render-items-as-html', true === $field->getCustomOption(ChoiceField::OPTION_ESCAPE_HTML_CONTENTS) ? 'false' : 'true');

$fieldValue = $field->getValue();
$isIndexOrDetail = \in_array($context->getCrud()->getCurrentPage(), [Crud::PAGE_INDEX, Crud::PAGE_DETAIL], true);
if (null === $fieldValue || !$isIndexOrDetail) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Controller\Synthetic;

use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Field\ChoiceField;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Entity\BlogPost;

/**
* @extends AbstractCrudController<BlogPost>
*/
class FormEnumTranslationController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return BlogPost::class;
}

public function configureFields(string $pageName): iterable
{
// Test translating enums in forms. When enums implement TranslatableInterface, this should be done by Symfony
// automagically.
return [
ChoiceField::new('state', 'State'),
];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Entity\Synthetic\SortTestRelatedEntity;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Entity\Website;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Enum\BlogPostStateEnum;

class AppFixtures extends Fixture
{
Expand Down Expand Up @@ -59,7 +60,8 @@ public function load(ObjectManager $manager): void
->setCreatedAt(new \DateTimeImmutable('2020-11-'.($i + 1).' 09:00:00'))
->setPublishedAt(new \DateTimeImmutable('2020-11-'.($i + 1).' 11:00:00'))
->addCategory($this->getReference('category'.($i % 10), Category::class))
->setAuthor($this->getReference('user'.($i % 5), User::class));
->setAuthor($this->getReference('user'.($i % 5), User::class))
->setState(BlogPostStateEnum::cases()[$i % \count(BlogPostStateEnum::cases())]);

if ($i < 10) {
$blogPost->setPublisher(
Expand Down
23 changes: 22 additions & 1 deletion tests/Functional/Apps/DefaultApp/src/Entity/BlogPost.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Enum\BlogPostStateEnum;

#[ORM\Entity]
class BlogPost
Expand Down Expand Up @@ -39,6 +40,9 @@ class BlogPost
#[ORM\ManyToOne(targetEntity: User::class)]
private $publisher;

#[ORM\Column(enumType: BlogPostStateEnum::class)]
private ?BlogPostStateEnum $state = BlogPostStateEnum::Draft;

public function __construct()
{
$this->categories = new ArrayCollection();
Expand Down Expand Up @@ -150,8 +154,25 @@ public function getPublisher()
return $this->publisher;
}

public function setPublisher(?User $publisher): void
public function setPublisher(?User $publisher): self
{
$this->publisher = $publisher;

return $this;
}

public function getState(): ?BlogPostStateEnum
{
return $this->state;
}

public function setState(string|BlogPostStateEnum|null $state): self
{
if (!$state instanceof BlogPostStateEnum) {
$state = BlogPostStateEnum::tryFrom($state);
}
$this->state = $state;

return $this;
}
}
22 changes: 22 additions & 0 deletions tests/Functional/Apps/DefaultApp/src/Enum/BlogPostStateEnum.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Enum;

use Symfony\Contracts\Translation\TranslatableInterface;
use Symfony\Contracts\Translation\TranslatorInterface;

enum BlogPostStateEnum: string implements TranslatableInterface
{
case Draft = 'draft';
case Published = 'published';
case Deleted = 'deleted';

public function trans(TranslatorInterface $translator, ?string $locale = null): string
{
return match ($this) {
self::Draft => $translator->trans('BlogPostStateEnum.draft', locale: $locale),
self::Published => $translator->trans('BlogPostStateEnum.published', locale: $locale),
self::Deleted => $translator->trans('BlogPostStateEnum.deleted', locale: $locale),
};
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\Controller;

use Doctrine\ORM\EntityRepository;
use EasyCorp\Bundle\EasyAdminBundle\Test\AbstractCrudTestCase;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Controller\DashboardController;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Controller\Synthetic\FormEnumTranslationController;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Entity\BlogPost;
use EasyCorp\Bundle\EasyAdminBundle\Tests\Functional\Apps\DefaultApp\Enum\BlogPostStateEnum;
use Symfony\Contracts\Translation\TranslatorInterface;

class FormEnumTranslationControllerTest extends AbstractCrudTestCase
{
protected EntityRepository $blogPosts;

protected function setUp(): void
{
parent::setUp();
$this->client->followRedirects();

$this->blogPosts = $this->entityManager->getRepository(BlogPost::class);
}

protected function getControllerFqcn(): string
{
return FormEnumTranslationController::class;
}

protected function getDashboardFqcn(): string
{
return DashboardController::class;
}

public function testFieldsFormatValue()
{
$translator = static::getContainer()->get(TranslatorInterface::class);
static::assertInstanceOf(TranslatorInterface::class, $translator);
$this->client->request('GET', $this->generateNewFormUrl());

foreach (BlogPostStateEnum::cases() as $case) {
self::assertAnySelectorTextSame('option', $case->trans($translator, locale: 'en'));
}
}
}
Loading