Billizzard
Billizzard

Reputation: 518

Symfony API Platform. How properly insert complex data?

I have entities Product and Host

Product

-------------------------------------------------
id   host_id           url               name
-------------------------------------------------
1      1    http://example.com/1/2/3   product_1

Host

----------
id   host   
----------
1    example.com

When I add a Product, I need to create a host (from url) if I don’t have one yet and substitute an id in host_id

For example i send Product data

{
    url: http://exmaple2.com/2/3/4
    name: super_product
}

Those. before creating a Product i need to create a host (example2.com). And then insert id to host_id in Product.

How and where should I create correctly Host?

In that case, do I need to create Product and Host in the controller?

Upvotes: 1

Views: 754

Answers (1)

A.L
A.L

Reputation: 10513

You can create the Site while sending data:

{
    url: http://exmaple2.com/2/3/4,
    name: super_product,
    host: {"host": "example.com"}
}

Api-platform should create the host is the entites are correctly defined and the host property is writable.


Or, you can use a Doctrine event listener for that, it will be triggered automatically when a Product will be created.

Create a Subscriber class:

// src/EventListener/SearchIndexerSubscriber.php
namespace App\EventListener;

use Doctrine\Common\EventSubscriber;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use App\Entity\Product;
use Doctrine\ORM\Events;

class ProductListener implements EventSubscriber
{
    public function getSubscribedEvents()
    {
        return array(
            Events::postPersist,
        );
    }

    public function postPersist(LifecycleEventArgs $args)
    {
        $entity = $args->getObject();

        if ($entity instanceof Product) {
            // Create site
            $site = new Site();
            // Set data you need
            $site->setUrl(…);
            // Create site
            $entity->setSite($site);

            $entityManager = $args->getObjectManager();
            $entityManager->persist($product);
            $entityManager->flush();
        }
    }
}

You can find the different events on Doctrine documentation.

Tag the service with doctrine.event_subscriber tag:

    App\EventListener\ProductListener:
        tags:
            - { name: doctrine.event_subscriber }

Upvotes: 1

Related Questions