Silex + Twig:找不到form_widget(),即使安装了Symfony Bridge也是如此

时间:2012-06-22 17:17:50

标签: symfony twig symfony-forms silex

我一直在关注以下资源的文档

http://silex.sensiolabs.org/doc/providers/form.html

但是我收到以下错误

Twig_Error_Syntax: The function "form_widget" does not exist in "layout.html.twig"

我多次查看文档和我的来源,我仍然看不到我哪里出错了,我错过了什么?我安装了Symfony Twig Bridge。

<?php
require_once __DIR__.'/vendor/autoload.php';

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Yaml\Parser;

use Silex\Provider\FormServiceProvider;

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path'     => __DIR__. '/src/views',
    'twig.options'  => array(
        'debug' => true,
        'cache' => false
    ),
));

$app['twig']->addExtension(new Twig_Extension_Debug());

$app['yaml'] = new Parser();



//.....

$app->register(new FormServiceProvider());

$app->register(new Silex\Provider\ValidatorServiceProvider());



$site['name']  = 'My Site';
// More definitions for $site

$app->match('/', function() use($app, $site) { 
    return $app['twig']->render('layout.html.twig', $site);
})->method('POST|GET');


$app->match('/form/', function(Request $request) use($app, $site) { 

    $data = array(
        'name' => 'Your name',
        'email' => 'Your email',
    );

    $form = $app['form.factory']->createBuilder('form', $data)
        ->add('name')
        ->getForm();

    if ('POST' == $request->getMethod()) {
        $form->bindRequest($request);

        if ($form->isValid()) {
            $data = $form->getData();

            // do something with the data - I haven't got that far yet

            // redirect somewhere
            return $app->redirect('/');
        }
    }

    $site['form'] = $form->createView();

    return $app['twig']->render('form.html.twig', $site);

})->method('POST|GET');

$app->run();

编辑:composer.json文件

{
    "require": {
        "silex/silex"       : "dev-master",
         "symfony/config"   : "dev-master",
         "symfony/yaml"     : "dev-master",
         "doctrine/common"  : ">=2.1,<2.3-dev",
         "doctrine/dbal"    : ">=2.1,<2.3-dev",
         "symfony/dependency-injection": "dev-master",
         "symfony/console"  : "dev-master",
         "monolog/monolog"  : ">=1.0.0",
         "twig/twig"        : ">=1.2.0",
         "symfony/form"     : "2.1.*",
         "symfony/translation": "2.1.*",
         "symfony/twig-bridge": "2.1.*",
         "symfony/validator": "2.1.*"
    }
}

1 个答案:

答案 0 :(得分:9)

您需要先注册表单提供程序,然后再注册twig提供程序。

树枝提供程序checks if the form provider is registered,只在必要时启用与表单相关的树枝扩展名。