我有一个带有注册表的页面。该表单包含地址字段,电子邮件,密码和一个单选按钮,用于选择用户是否要注册或登录。选择“登录”后,地址字段将通过JS / CSS隐藏,并且在提交时仅将电子邮件和密码发送到后端。
后端将登录用户,并使用来自数据库的数据加载用户表单类。在Symfony中,这很好且容易实现。但是现在我想对照来自数据库的数据来验证表格。我已经这样做了,但我认为必须有一种更简单的方法:
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use App\Form\UserType;
use App\Entity\User;
// and more use ...
class RegisterController extends Controller
{
/**
* @Route("/{_locale}/register/", name="register", requirements={"_locale"="%app.locales%"})
*
* @param Request $request
* @param UserPasswordEncoderInterface $encoder
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function index(Request $request, UserPasswordEncoderInterface $encoder)
{
$isValid = true;
$doAccountLoginValue = 2;
$isUserLoggedIn = $this->isGranted('IS_AUTHENTICATED_FULLY');
$accountForm = $this->getAccountForm();
$accountForm->handleRequest($request);
// check if the user wants to login
if ($accountForm->isSubmitted() &&
$accountForm->isValid() &&
intval($accountForm->get('login')->getData()) === $doAccountLoginValue &&
!$isUserLoggedIn
) {
if ($this->userLogin($request, $encoder)) {
$isUserLoggedIn = true;
} else {
$this->addFlash(
'error',
'Login incorrect. Invalid email or password.'
);
}
}
// create the user form. When the user is logged in pass the user object to the UserType
if ($this->getUser()) {
$user = $this->getUser();
} else {
$user = new User();
}
$form = $this->createForm(UserType::class, $user, [
'action' => $this->generateUrl('register'),
]);
if ($isUserLoggedIn) {
// validate manually when the user is logged in
$form->submit([], false);
$violationList = $this->get('validator')->validate($form);
$isValid = (empty($violationList)) ? true : false;
$this->addViolationMessagesToForm($violationList, $form);
} else {
// not logged in, so handle the request with its POST data
$form->handleRequest($request);
if ($form->isSubmitted()) {
$isValid = $form->isValid();
}
}
return $this->render('register/index.html.twig', [
'form' => $form->createView(),
'accountForm' => $accountForm->createView(),
'isValid' => $isValid,
]);
}
private function addViolationMessagesToForm(ConstraintViolationList $violationList, FormInterface &$form)
{
$violationListArray = (array) $violationList;
$violationListViolations = array_pop($violationListArray);
foreach ($violationListViolations as $violation) {
$property = str_replace('data.', '', $violation->getPropertyPath());
$form->get($property)->addError(new FormError($violation->getMessage()));
}
}
}
这让我的代码烦恼的是这一部分:
// validate manually when the user is logged in
$form->submit([], false);
$violationList = $this->get('validator')->validate($form);
$isValid = (empty($violationList)) ? true : false;
$this->addViolationMessagesToForm($violationList, $form);
没有简单的方法吗?为什么$form->submit([], false);
还不够?所有数据已经在子元素形式中。