Skip to content

Instantly share code, notes, and snippets.

@mac2000
Created September 2, 2013 07:51
Show Gist options
  • Save mac2000/6410251 to your computer and use it in GitHub Desktop.
Save mac2000/6410251 to your computer and use it in GitHub Desktop.
Silex Reusing Forms Example
{
"require": {
"silex/silex": "1.*",
"twig/twig": "1.*",
"symfony/twig-bridge": "2.*",
"symfony/form": "2.*",
"symfony/validator": "2.*",
"symfony/config": "2.*",
"symfony/translation": "2.*"
},
"autoload": {
"psr-0": {"": "src/"}
}
}
<?php // src/Acme/Form/Type/ExampleForm.php
namespace Acme\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints as Assert;
class ExampleForm extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('email', 'email', array(
'constraints' => array(
new Assert\NotBlank(),
new Assert\Email()
)
));
$builder->add('first_name', 'text', array(
'constraints' => array(
new Assert\NotBlank(),
new Assert\Length(array('min' => 5))
)
));
$builder->add('last_name', 'text', array(
'constraints' => array(
new Assert\NotBlank(),
new Assert\Length(array('min' => 5))
)
));
$builder->add('gender', 'choice', array(
'choices' => array(1 => 'male', 2 => 'female'),
'expanded' => true,
'constraints' => new Assert\Choice(array(1, 2)),
));
$builder->add('Save', 'submit');
}
public function getName()
{
return 'example';
}
}
{# templates/home.twig #}
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Silex Reusing Forms Example</title>
</head>
<body>
{{ form(form) }}
</body>
</html>
<?php // index.php
use Acme\Form\Type\ExampleForm;
use Silex\Application;
use Silex\Provider\FormServiceProvider;
use Silex\Provider\TranslationServiceProvider;
use Silex\Provider\TwigServiceProvider;
use Silex\Provider\ValidatorServiceProvider;
use Symfony\Component\HttpFoundation\Request;
require_once 'vendor/autoload.php';
$app = new Application();
$app['debug'] = true;
$app->register(new TranslationServiceProvider());
$app->register(new ValidatorServiceProvider());
$app->register(new FormServiceProvider());
$app->register(new TwigServiceProvider(), array('twig.path' => __DIR__ . '/templates'));
$app->match('/', function(Request $request) use($app){
$form = $app['form.factory']->create(new ExampleForm());
$form->handleRequest($request);
if($form->isValid()) {
return 'VALID';
}
return $app['twig']->render('home.twig', array(
'form' => $form->createView()
));
});
$app->run();
@getbyid
Copy link

getbyid commented Oct 2, 2013

Thanks a lot, this example is very useful!

Copy link

ghost commented Mar 30, 2015

Thanks for the tips, gonna use it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment