<?php
use Symfony\Bridge\Twig\Form\TwigRendererEngine;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Forms;
use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormRenderer;
use Symfony\Component\Security\Csrf\CsrfTokenManager;
$formLayout = <<<'NOW'
{%- block text_widget -%}
<label for="{{ id }}">{{ label }}</label>
<input type="text" id="{{ id }}" name="{{ name }}"/>
{%- endblock text_widget -%}
{%- block button_widget -%}
<input type="button" id="{{ id }}" value="{{ label }}"/>
{%- endblock button_widget -%}
{%- block form -%}
<form name="{{ name }}" method="post">
{% for child in form %}
{{- form_widget(child) -}}
{% endfor %}
</form>
{%- endblock form -%}
NOW;
$templates = [
'form_layout' => $formLayout,
'form' => '{{ form(form) }}',
];
$loader = new Twig\Loader\ArrayLoader($templates);
$twig = new Twig\Environment($loader);
$formEngine = new TwigRendererEngine(['form_layout'], $twig);
$formRenderer = new FormRenderer($formEngine, new CsrfTokenManager());
$twig->addExtension(new FormExtension());
$runtimeLoader = new \Twig\RuntimeLoader\FactoryRuntimeLoader([
FormRenderer::class => function () use ($formRenderer) {
return $formRenderer;
},
]);
$twig->addRuntimeLoader($runtimeLoader);
$form = Forms::createFormFactory()
->createBuilder()
->add('my_text', TextType::class, [
'label' => 'My text',
])
->add('my_other_text', TextType::class, [
'label' => 'My other text',
])
->add('button', ButtonType::class, [
'label' => 'Submit data',
])
->getForm();
echo $twig->render('form', [
'form' => $form->createView(),
]);