diff --git a/app/src/DataFixtures/AppFixtures.php b/app/src/DataFixtures/AppFixtures.php index 276f0bc3..30d602f3 100644 --- a/app/src/DataFixtures/AppFixtures.php +++ b/app/src/DataFixtures/AppFixtures.php @@ -7,6 +7,7 @@ use App\Entity\Tag; use App\Entity\User; use App\Entity\UserAddress; +use App\Entity\UserTag; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use Draw\Component\Application\Configuration\Entity\Config; @@ -82,6 +83,10 @@ private function loadUsers(): iterable ->setLevel(User::LEVEL_ADMIN) ->setRoles(['ROLE_SUPER_ADMIN']) ->setTags([$this->getObjectReference(Tag::class, 'admin')]) + ->addUserTag( + (new UserTag()) + ->setTag($this->getObjectReference(Tag::class, 'admin')) + ) ->setAddress( (new Address()) ->setStreet('200 Acme') diff --git a/packages/sonata-import-bundle/Column/MappedToOptionBuilder/DoctrineMappedToOptionBuilder.php b/packages/sonata-import-bundle/Column/MappedToOptionBuilder/DoctrineMappedToOptionBuilder.php index d04d4cae..71ab2f66 100644 --- a/packages/sonata-import-bundle/Column/MappedToOptionBuilder/DoctrineMappedToOptionBuilder.php +++ b/packages/sonata-import-bundle/Column/MappedToOptionBuilder/DoctrineMappedToOptionBuilder.php @@ -6,6 +6,8 @@ use Doctrine\ORM\Mapping\ClassMetadataInfo; use Doctrine\Persistence\ManagerRegistry; use Draw\Bundle\SonataImportBundle\Entity\Column; +use Draw\Bundle\SonataImportBundle\Event\AttributeImportEvent; +use Symfony\Component\EventDispatcher\Attribute\AsEventListener; class DoctrineMappedToOptionBuilder implements MappedToOptionBuilderInterface { @@ -14,6 +16,38 @@ public function __construct( ) { } + #[AsEventListener] + public function handleAttributeImportEvent(AttributeImportEvent $event): void + { + $column = $event->getColumn(); + + if (!str_contains($column->getMappedTo(), '.')) { + return; + } + + $class = $column->getImport()->getEntityClass(); + + $metadata = $this->managerRegistry->getManagerForClass($class)->getClassMetadata($class); + + [$relation, $field] = explode('.', $column->getMappedTo()); + + if (!isset($metadata->associationMappings[$relation])) { + return; + } + + $targetEntityClass = $metadata->associationMappings[$relation]['targetEntity']; + + $targetEntity = $this->managerRegistry->getRepository($targetEntityClass)->findOneBy([$field => $event->getValue()]); + + if (null === $targetEntity) { + return; + } + + $event->getEntity()->{'set'.ucfirst($relation)}($targetEntity); + + $event->stopPropagation(); + } + public function getOptions(Column $column, array $options): array { $class = $column->getImport()->getEntityClass();