Silex表单验证,无需翻译


Silex form validation without translation

我想使用Silex的服务提供商来构建一个简单的验证联系表单,但它似乎只与翻译服务提供商合作,因为当我呈现视图时,我有一个Twig_Error_Syntax'过滤器"trans"不存在',我想这是因为我必须自定义(覆盖)'form_div_layout.html.twit'并删除trans-filter?我不需要翻译。

我还没有实现验证。

这是我的代码:

use Symfony'Component'HttpFoundation'Request ;
use Symfony'Component'HttpFoundation'Response ;
require_once __DIR__ . '/bootstrap.php' ;
$app = new Silex'Application() ;
require __DIR__ . '/../config/conf.php';
$app->register(new Silex'Provider'SymfonyBridgesServiceProvider(), array(
      'symfony_bridges.class_path' => __DIR__ . '/../vendor/symfony/src',
)) ;
$app->register(new Silex'Provider'HttpCacheServiceProvider(), array(
      'http_cache.cache_dir' => __DIR__ . '/../cache/',
)) ;
$app->register(new Silex'Provider'FormServiceProvider(), array(
      'form.class_path' => __DIR__ . '/../vendor/symfony/src'
)) ;
$app->register(new Silex'Provider'ValidatorServiceProvider(), array(
      'validator.class_path' => __DIR__ . '/../vendor/symfony/src',
)) ;
$app->register(new Silex'Provider'TwigServiceProvider(), array(
      'twig.path' => __DIR__ . '/../src/views/frontend/',
      'twig.class_path' => __DIR__ . '/../vendor/twig/lib',
      'twig.options' => array('cache' => $app['http_cache.cache_dir'] . 'twig.cache'),
)) ;
$app->get('/contact', function (Silex'Application $app) use ($navigation) {
       $form = $app['form.factory']->createBuilder('form')
               ->add('name', 'text')
               ->add('surname', 'text')
               ->add('email', 'email')
               ->add('message', 'textarea')
               ->getForm() ;
       $response = new Response() ;
       $page = $app['twig']->render('contact.html.twig', array('navigation' => $navigation, 'form' => $form->createView())) ;
       $response->setContent($page) ;
       return $response ;
    }) ;

在联系页面中:

<form class="form-horizontal" action="/contact" method="post">
 <fieldset class="control-group">
                <legend>Contact</legend>
                  {{ form_errors(form) }}
                  {{ form_row(form.name) }
                  {{ form_row(form.surname) }}
                  {{ form_row(form.email) }}
                  {{ form_row(form.message) }}
    <button type="submit" class="btn btn-info">Send</button>
 </fieldset>
</form>

遇到了同样的问题,我可以通过添加来解决它

$app->register(new Silex'Provider'TranslationServiceProvider(), array(
    'translator.messages' => array(),
));

另一种方法是为Twig提供过滤器。。。

function dummy_trans($str) {
    return $str;
}
$app['twig']->addFilter('trans*', new Twig_Filter_Function('dummy_trans'));

(N.B)星号表示动态Twig过滤器,本质上是一个通配符。

我只是简单地测试了一下,但似乎能胜任。

Silex文档中有说明:

如果您不想创建自己的表单布局,也可以:将使用默认布局。但是你必须注册翻译提供商,因为默认的表单布局需要它

因此,如果你想使用默认布局,你所要做的就是:

$app->register(new Silex'Provider'TranslationServiceProvider());

解决方案是通过删除trans-filters 来自定义表单布局

我可以通过以下操作绕过翻译错误:

$app = new Silex'Application();
$app['translator.messages'] = array();