2017-04-06 38 views
1

我正在尋找最佳(或只是工作)的方式來解決以下問題。 我有一個標準的用戶等級和積分形式嵌套表單/映射字段到實體

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add(
      'username', 
      Type\TextType::class 
     ) 
     ->add(
      'email', 
      Type\EmailType::class 
     ) 
     ->add(
      'plainPassword', 
      Security\UserRepeatedPasswordType::class 
     ) 
     ->add(
      'roles', 
      Type\ChoiceType::class, 
      [ 
       'multiple' => true, 
       'expanded' => true, 
       'choices' => $this->getRoleChoices() 
      ] 
     ); 
} 

什麼是非標準UserRepeatedPasswordType,它看起來像這樣

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add(
      'password', 
      Type\RepeatedType::class, 
      [ 
       'type' => Type\PasswordType::class, 
       'required' => true, 
       'first_options' => [ 
        'label' => 'Password' 
       ], 
       'second_options' => [ 
        'label' => 'Repeat Password' 
       ], 
      ] 
     ); 
} 

我創造了它,因爲這兩個字段在passwordReset形式和userSettings也使用形成。現在我有兩個問題:

1)當我使用這種方式,從UserRepeatedPasswordType值不正確映射爲我User實體 - 有一個錯誤字符串預期(廢話),但它得到了數組。我嘗試使用視圖和模型變壓器,但沒有適當的結果(但我沒有太多的經驗,所以也許這樣)。我也嘗試過使用getParent(),並通過UserType,但它進入了一些無限循環,我得到了500.如果我只是將粘貼字段從UserRepeatedPasswordType複製到UserType它可以正常工作。

2)如果這是解決(或者甚至是複製粘貼,如果不能做其他的方式),另外還有一個相關的(我相信)問題:

我有這個ChangePasswordType形式,這是用於重置您的密碼。

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $builder 
     ->add(
      'confirmationToken', 
      Type\HiddenType::class, 
      [ 
       'required' => true, 
       'constraints' => [ 
        new NotBlank(), 
       ] 
      ] 
     ) 
     ->add(
      'plainPassword', 
      Type\RepeatedType::class, 
      [ 
       'type' => Type\PasswordType::class, 
       'required' => true, 
       'first_options' => [ 
        'label' => 'Password' 
       ], 
       'second_options' => [ 
        'label' => 'Repeat Password' 
       ], 
      ] 
     ) 
     ->add(
      'changePassword', 
      Type\SubmitType::class 
     ); 
} 

,它工作正常,因爲它是,但我想要做的兩件事情是 - 第一,解決了我的第一個問題,在使用它UserRepeatedPasswordType,第二 - 我在User實體部分Assert\Length做了$plainPassword它我通過UserType表單提交新用戶時正確工作。但我希望驗證有點映射到ChangePasswordType或最好是UserRepeatedPasswordType - 只是將所有規則放在一個地方。這甚至可以完成?感謝任何解決方案/提示/建議。

回答

0

好吧,不知道是否有人有興趣,但這是我如何完成這一點。如果有人有更好的答案,只是給我一個手勢(主要是第一個);)

1),因爲我以爲,通過ViewTransformer但在父窗體解決(在UserTypeUserRepeatedPasswordType

$builder->get('plainPassword') 
    ->addViewTransformer(new CallbackTransformer(
     function ($singleAsArray) { 
      return $singleAsArray; 
     }, 
     function ($arrayAsSingle) { 
      return $arrayAsSingle['password'] ?? ''; 
     } 
    )); 

2.)其實很簡單。您所要做的就是將該表單映射到UserEntity,其方式與UserType相同,並且創建自定義驗證組只是爲了讓所有的事情都很好,並在控制之下:)