php - 如何在 silex 应用程序中使用 Symfony 2 验证组件显示 Symfony 2 表单错误?

标签 php symfony symfony-forms silex

背景:我正在使用 Symfony Forms 和 Symfony Validation 组件在 Silex 应用程序的应用程序注册页面中呈现表单。

我的表单正常工作、呈现、客户端验证并将数据绑定(bind)到我的实体。我已向实体添加了一个验证方法,该方法可以正确验证实体并产生预期的错误。

问题:我现在想从返回的 ConstraintValidationList 中获取错误并返回到表单中,以便使用 twig {{ form_errors }} View 助手将它们显示在前端。

我查阅了 API 文档:http://api.symfony.com/2.0/Symfony/Component/Form/Form.html并且看不到执行此操作的正确方法。有谁知道如何实现我正在寻找的东西?

这是我的 Silex Controller 闭包中的代码:

$app->post('/register-handler', function(Request $request) use($app)
{
    // Empty domain object 
    $user = new MppInt\Entity\User();

    // Create the form, passing in a new form object and the empty domain object
    $form = $app['form.factory']->create(new MppInt\Form\Type\RegisterType(), $user);

    // Bind the request data to the form which puts it into the underlying domain object
    $form->bindRequest($request);   

    // Validate the domain object using a set of validators.
    // $violations is a ConstraintValidationList
    $violations = $app['validator']->validate($user);

    // Missing step - How do I get a ConstraintValidationList back into the 
    // form to render the errors in the twig template using the {{ form_errors() }}
    // Helper. 

});

最佳答案

在绑定(bind)请求阶段,验证器应该在数据上运行,因此您不需要自己使用验证服务。 (来自 Sf2 而不是 Silex,验证器服务与 Form 关联,我不知道您是否必须为 Silex 手动执行此操作)

除非在每个字段上启用错误冒泡,否则错误将保留在表单的字段(子项)中,以便使用 {{ form_errors() }} 显示错误

虽然如果你确实需要将constraintViolationList获取到表单错误中,你可以将它们转换为Symfony\Component\Form\FormError对象并使用$form->addError(FormError $formError);将它们添加到表单中

关于php - 如何在 silex 应用程序中使用 Symfony 2 验证组件显示 Symfony 2 表单错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10103971/

相关文章:

php - 如何将密码编码器附加到 Silex 中的用户界面?

php - Symfony3 缓存(警告 : rename) after update

php - 在 wordpress 的子主题 functions.php 中禁用主题功能

php - 删除 while 循环中的最后一个逗号 - PHP

使用 .htaccess 处理 PHP 错误并写入 php_error.log 文本文件

doctrine-orm - 命名 Symfony2/Doctrine 主键的最佳实践

jquery - 范围 slider 基础 5 bug

php - Symfony2 FOSUserBundle 文件上传(个人资料图片)提示?

symfony-forms - Symfony 2.8/3.0 升级 : how to deal with form types with variable parameters?

php - 提交后动态隐藏表单,所有用户