Created
April 26, 2016 04:27
-
-
Save LeoOnTheEarth/b7f8bc60ce16c33a4183302036d09c0c to your computer and use it in GitHub Desktop.
Symfony Form Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Part of sf-form project. | |
* | |
* @copyright Copyright (C) 2011 - 2016 SMS Taiwan, Inc. All rights reserved. | |
* @license GNU General Public License version 2 or later; see LICENSE | |
*/ | |
require __DIR__ . '/vendor/autoload.php'; | |
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension; | |
use Symfony\Component\Form\Forms; | |
use Symfony\Bridge\Twig\Extension\FormExtension; | |
use Symfony\Bridge\Twig\Form\TwigRenderer; | |
use Symfony\Bridge\Twig\Form\TwigRendererEngine; | |
use Symfony\Component\Form\Extension\Core\Type\TextType; | |
use Symfony\Component\Form\Extension\Core\Type\DateType; | |
use Symfony\Component\Translation\Translator; | |
use Symfony\Bridge\Twig\Extension\TranslationExtension; | |
// the Twig file that holds all the default markup for rendering forms | |
// this file comes with TwigBridge | |
$defaultFormTheme = 'form_div_layout.html.twig'; | |
$vendorDir = realpath(__DIR__ . '/vendor'); | |
// the path to TwigBridge library so Twig can locate the | |
// form_div_layout.html.twig file | |
$appVariableReflection = new \ReflectionClass('\Symfony\Bridge\Twig\AppVariable'); | |
$vendorTwigBridgeDir = dirname($appVariableReflection->getFileName()); | |
// the path to your other templates | |
$viewsDir = realpath(__DIR__ . '/views'); | |
$twig = new Twig_Environment(new Twig_Loader_Filesystem(array( | |
$viewsDir, | |
$vendorTwigBridgeDir.'/Resources/views/Form', | |
))); | |
$formEngine = new TwigRendererEngine(array($defaultFormTheme)); | |
$formEngine->setEnvironment($twig); | |
// add the FormExtension to Twig | |
$twig->addExtension( | |
new FormExtension(new TwigRenderer($formEngine)) | |
); | |
// create the Translator | |
$translator = new Translator('en'); | |
// add the TranslationExtension (gives us trans and transChoice filters) | |
$twig->addExtension(new TranslationExtension($translator)); | |
// create your form factory as normal | |
$formFactory = Forms::createFormFactoryBuilder() | |
->addExtension(new HttpFoundationExtension()) | |
->getFormFactory(); | |
$form = $formFactory->createBuilder() | |
->add('task', TextType::class) | |
->add('dueDate', DateType::class) | |
->getForm(); | |
$form->submit(['task' => 'foo', 'dueDate' => new DateTime('2015-01-01')]); | |
if ($form->isValid()) | |
{ | |
$data = $form->getData(); | |
var_dump($data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment