2014-02-28 64 views
0

我創建了一個表單類型UserBundle/form/UserType.php

$form->isValid()如果用戶名或電子郵件存在,即使其他字段爲空,也會返回true。

class UserType extends AbstractType 
{ 
    private $type; 
    const TYPE_CREATE = 1; 

    public function __construct($type) { 
     $this->type = $type; 
    } 

    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     switch ($this->type){ 
      case self::TYPE_CREATE : 
       $builder 
        ->add('email', 'email', array('label' => 'user.email')) 
        ->add('username', null, array('label' => 'user.name')) 
        ; 
       break; 
      default : 
       $builder 
        ->add('username') 
        ->add('usernameCanonical') 
        ->add('email') 
        ->add('emailCanonical') 
        ->add('enabled') 
        ->add('salt') 
        ->add('password') 
        ->add('lastLogin') 
        ->add('locked') 
        ->add('expired') 
        ->add('expiresAt') 
        ->add('confirmationToken') 
        ->add('passwordRequestedAt') 
        ->add('roles') 
        ->add('credentialsExpired') 
        ->add('credentialsExpireAt') 
       ; 
       break; 
     } 

    } 

    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'data_class' => 'Project\UserBundle\Entity\User' 
     )); 
    } 

    public function getName() 
    { 
     return 'project_userbundle_user'; 
    } 
} 

我的控制器

class UserController extends Controller 
{ 
    public function CreateAction() 
    { 
     //create user 
     $userManager = $this->get('fos_user.user_manager'); 
     $user = $userManager->createUser(); 

     //create form 
     $form = $this->createForm(new UserType(UserType::TYPE_CREATE),$user); 

     //form submit 
     $request = Request::createFromGlobals(); 
     if($request->getMethod() === "POST"){ 
      $form->submit($request); 
      //test if form is valid 
      if($form->isValid()){ 
       //generate random password 
       $password = User::randomPassword(); 
       $user->setPassword($password); 

       //save user 
       $userManager->updateUser($user); 
      } 
     } 

     return $this->render('Project:User:create.html.twig',array(
      'form' => $form->createView() 
     )); 
    } 
} 
+1

你爲什麼重新創建請求對象?在你的方法參數中詢問它有什麼問題?或者從'$ this-> getRequest()'獲取它?或者從'$ this-> get('request')'獲取它? – Touki

+0

$ form-> handleRequest($ request) –

回答

2

提示:

你不應該試圖重新創建一個Request控制器內。正如您目前所遇到的那樣,這絕對是一種不良做法,並可能導致應用程序出現意外行爲。

public function createAction(Request $request) 
{ 
    // $request is holding the current request 
} 

而且你可以從容器中的ContainerAware類像一個控制器內的當前請求:如果你將它添加爲方法參數

symfony會自動將請求傳遞給控制器​​的動作。

$request = $this->getRequest(); 
$request = $this->get('request'); 
$request = $this->container->get('request'); 

而且請堅持使用symfony coding standards。您的代碼中存在多處違規行爲。

方法名稱應該是lower camelCased not CamelCased

UserBundle/form應該是UserBundle/Form

方法的大括號/花括號屬於下一行。

public function __construct($type) // { 
{ 
    $this->type = $type; 
}