我創建了一個表單類型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()
));
}
}
你爲什麼重新創建請求對象?在你的方法參數中詢問它有什麼問題?或者從'$ this-> getRequest()'獲取它?或者從'$ this-> get('request')'獲取它? – Touki
$ form-> handleRequest($ request) –