2012-01-31 78 views
5

我正試圖在Symfony 2項目中實現更改密碼功能。 我有實體User帶有驗證規則validation.yml文件。在User實體中,我有字段「password」,其驗證約束條件爲validation.yml
我創建了2個字段'password'和'confirmPasswod'的表單。我想對「密碼」字段使用我的實體驗證約束,並檢查'​​passwod'和'confirmPassword'字段之間是否相等。在我contronller我寫Symfony 2中的等效字段驗證

$form = $this->createForm(new SymfonyForm\ChangePasswordType(), new Entity\User()); 
if ($form->isValid()) 
    {..............} 

在「用戶」的實體,我沒有「confirmPasswod」字段。所以,我得到錯誤:

Neither property "confirmPassword" nor method "getConfirmPassword()" nor method "isConfirmPassword()" exists in class 

有沒有辦法使用某種形式的領域基於實體的表單驗證,而不是基於實體的驗證爲其他? 在此先感謝。

回答

16

SymfonyForm\ChangePasswordType你可以使用這樣的事情:

$builder->add('password', 'repeated', array(
    'type' => 'password', 
    'first_name' => 'Password', 
    'second_name' => 'Password confirmation', 
    'invalid_message' => 'Passwords are not the same', 
)); 

由於Symfony的2.1,您可以配置選項來避免斷元素的名稱(如在評論中提及)

$builder->add('password', 'repeated', array(
    // … the same as before 
    'first_name' => 'passwd', 
    'second_name' => 'passwd_confirm', 
    // new since 2.1 
    'first_options' => array('label' => 'Password'), 
    'second_options' => array('label' => 'Password confirmation'),  
)); 
+0

謝謝,這是非常很有幫助。 – Ris90 2012-01-31 13:52:37

+1

這也適用於我。謝謝。但有一件事我改變了。我使用'password'和'password_confirmation'而不是'Password'和'Password confirmation'。如果你使用後者,你最終會遇到一些尷尬的元素名稱,比如'vnn_pressboxbundle_preferencestype_password_Confirm password'。 – 2012-04-01 14:32:59