2012-04-11 72 views
2

背景:我使用的Symfony表單和Symfony的驗證組件來呈現在我的應用程序的註冊頁面在我的Silex使用形式。如何在一個silex應用程序中使用Symfony 2驗證組件顯示Symfony 2表單錯誤?

我有如下形式正常工作,渲染,客戶端驗證和數據綁定到我的實體。我向驗證方法添加了一個驗證方法,可以正確驗證實體並生成預期的錯誤。

問題:我現在想要得到的錯誤出返回ConstraintValidationList並返回到窗體上使用樹枝{{form_errors}}視圖助手前端顯示它們。

我在諮詢了API文檔:http://api.symfony.com/2.0/Symfony/Component/Form/Form.html並不能看到這樣做的正確方法。有誰知道如何實現我在找的東西?

這裏是我的Silex控制器關閉代碼:

$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. 

}); 

回答

2

在綁定請求階段驗證應在數據上運行,所以你不應該需要自己使用的驗證服務。 (來自Sf2而不是Silex,驗證器服務與表單關聯,我不知道您是否必須爲Silex手動執行此操作)

除非在每個字段上啓用了錯誤冒泡,否則錯誤將保留在字段中兒童)使用{{form_errors()}}顯示錯誤

儘管如果您確實需要將constraintViolationList轉換爲表單錯誤,您可以將它們轉換爲Symfony \ Component \ Form \ FormError對象並添加它們使用$ form-> addError(FormError $ formError);