Skip to main content

Using Live Components in Sylius Twig Hooks

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

Twig Hooks are a robust and powerful alternative to the Sonata Block Events and the old Sylius Template Events system.

Twig Hooks work not only with Twig templates out-of-the-box, but you can also hook in Live Components quite easily.

Given you have a Live component like this:

<?php

declare(strict_types=1);

namespace BitExpert\MySyliusPlugin\Twig\Component;

use Sylius\Bundle\UiBundle\Twig\Component\LiveCollectionTrait;
use Sylius\Bundle\UiBundle\Twig\Component\ResourceFormComponentTrait;
use Sylius\Bundle\UiBundle\Twig\Component\TemplatePropTrait;
use Sylius\Resource\Doctrine\Persistence\RepositoryInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\ComponentToolsTrait;

#[AsLiveComponent]
class MyEntityComponent
{
use ComponentToolsTrait;
use LiveCollectionTrait;
use TemplatePropTrait;
use ResourceFormComponentTrait;

public function __construct(
RepositoryInterface $productRepository,
FormFactoryInterface $formFactory,
string $resourceClass,
string $formClass
) {
$this->initialize($productRepository, $formFactory, $resourceClass, $formClass);
}
}

As well as the corresponding service configuration:

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="bitexpert_my_plugin.twig.component.my_entity.form" class="\BitExpert\MySyliusPlugin\Twig\Component\MyEntityComponent">
<argument type="service" id="bitexpert_my_plugin.repository.my_entity" />
<argument type="service" id="form.factory" />
<argument>%bitexpert_my_plugin.model.my_entity.class%</argument>
<argument>BitExpert\MySyliusPlugin\Form\Type\MyEntityType</argument>

<call method="setLiveResponder">
<argument type="service" id="ux.live_component.live_responder"/>
</call>

<tag name="sylius.live_component.admin" key="bitexpert_my_plugin:my_entity:form" />
</service>
</services>
</container>

We can use the Live Component identifier bitexpert_my_plugin:my_entity:form directly to reference the component in our Twig Hooks configuration:

sylius_twig_hooks:
hooks:
'sylius_admin.my_entity.create.content':
form:
component: 'bitexpert_my_plugin:my_entity:form'
props:
form: '@=_context.form'
resource: '@=_context.resource'
template: '@BitExpertMyPlugin/admin/my_entity/form.html.twig'
priority: 0