Skip to content

Commit

Permalink
[SonataImportBundle] support doctrine toOne relation update (#253)
Browse files Browse the repository at this point in the history
  • Loading branch information
mpoiriert authored Apr 23, 2024
1 parent 20a45fa commit df9359a
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
5 changes: 5 additions & 0 deletions app/src/DataFixtures/AppFixtures.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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();
Expand Down

0 comments on commit df9359a

Please sign in to comment.