symfony form

Создадим форму симфони.
Понадобятся всего 4 зависимости.


      "require": {
        "symfony/form": "^3.3",
		"symfony/twig-bridge": "^3.3",
		"symfony/translation": "^3.3",
		"symfony/security-csrf": "^3.3"
      }

Далее подключаем классы формы, твига, переводчика и защиту от Csrf атак.


require "vendor/autoload.php";

use Symfony\Component\Form\Forms;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;

use Symfony\Bridge\Twig\Extension\FormExtension;
use Symfony\Bridge\Twig\Form\TwigRenderer;
use Symfony\Bridge\Twig\Form\TwigRendererEngine;


use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\Loader\XliffFileLoader;
use Symfony\Bridge\Twig\Extension\TranslationExtension;

use Symfony\Component\Security\Csrf\CsrfTokenManager;

//1 TWIG

$viewsDir = realpath(__DIR__.'/views');
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable');
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName());

$twig = new Twig_Environment(new Twig_Loader_Filesystem(array(
    $viewsDir,
    $vendorTwigBridgeDir.'/Resources/views/Form',
)));

//2 FORM

$formFactory = Forms::createFormFactory();
$form = $formFactory->createBuilder()
    ->add('task', TextType::class)
    ->add('dueDate', DateType::class)
    ->getForm();


// 3 Translator
$translator = new Translator('ru');
// somehow load some translations into it
$translator->addLoader('xlf', new XliffFileLoader());

// add the TranslationExtension (gives us trans and transChoice filters)
$twig->addExtension(new TranslationExtension($translator));

define('DEFAULT_FORM_THEME', 'form_div_layout.html.twig');
$csrfTokenManager = new CsrfTokenManager();
// $csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);

$formEngine = new TwigRendererEngine(array(DEFAULT_FORM_THEME));
$formEngine->setEnvironment($twig);
$twig->addExtension(
    new FormExtension(new TwigRenderer($formEngine, $csrfTokenManager))
);

$twig->addRuntimeLoader(new \Twig_FactoryRuntimeLoader(array(
    TwigRenderer::class => function () use ($formEngine, $csrfTokenManager) {
        return new TwigRenderer($formEngine, $csrfTokenManager);
    },
)));

echo $twig->render('new.html.twig', array(
    'form' => $form->createView(), 'var1' => 'var1'
));

И сама форма new.html.twig


{{ form_start(form) }}
    {{ form_widget(form) }}
    <input type="submit" />
{{ form_end(form) }}

Получаем вот такую формочку

Leave a comment

Your email address will not be published.


*