Javascript 来自AJAX呈现的Symfony表单验证
我是symfony的新手,我在整个JSON中呈现表单,因此每当我单击图标时,它都会显示不同的表单(要更改firstname、lastname…)。 我将这些表单作为JSON返回:Javascript 来自AJAX呈现的Symfony表单验证,javascript,ajax,forms,symfony,validation,Javascript,Ajax,Forms,Symfony,Validation,我是symfony的新手,我在整个JSON中呈现表单,因此每当我单击图标时,它都会显示不同的表单(要更改firstname、lastname…)。 我将这些表单作为JSON返回: public function profileSettings() { $user = $this->getUser(); // Formulaire d'informations concernant le compte $formAccountSettings = $thi
public function profileSettings()
{
$user = $this->getUser();
// Formulaire d'informations concernant le compte
$formAccountSettings = $this->createForm(AccountSettingsType::class, $user, [
'userEmail' => $user->getEmail(),
'userUsername' => $user->getUsername(),
]);
// Formulaire d'informations personnel
$formPersonnalSettings = $this->createForm(PersonnalSettingsType::class, $user, [
'userFirstname' => $user->getFirstname(),
'userLastname' => $user->getLastname(),
]);
// Retour en format JSON des 3 requêtes sous tableau
return $this->json(
[
'formAccountSettingsView' =>
$this->render('user/_accountSettings.html.twig', [
'form' => $formAccountSettings->createView(),
]),
'currentUser' => $user,
'formPersonnalSettingsView' => $this->render('user/_accountSettings.html.twig', [
'form' => $formPersonnalSettings->createView(),
]),
]
);
}
下面是我如何显示的:
$('#settings-user li').on('click', function (e) {
$.ajax({
type: 'GET',
url: "/website-skeleton/public/index.php/json/profile",
success: function (response) {
if ($(e.target).hasClass('profile')) {
$('.display').empty().append(
`
<p id="welcome">Bonjour, <em><strong>${response['currentUser']['username']}</strong></em> vous êtes enregistré sous le nom de <strong>${response['currentUser']['firstname']} ${response['currentUser']['lastname']}</strong>.
<br>
Votre adresse email est : <strong>${response['currentUser']['email']}</strong>.
<br>
Pour modifiez vos informations veuillez cliquez sur le menu de navigation.
</p>`);
} else if ($(e.target).hasClass('security')) {
$('.display').empty().append(response['formAccountSettingsView']['content']);
} else if ($(e.target).hasClass('informations')) {
$('.display').empty().append(response['formPersonnalSettingsView']['content'])
}
}
})
});
这是一个好方法吗?我应该用ajax处理所有事情吗?谢谢你的时间 您应该使用
HandlerRequest
,它会在表单提交后自动将表单中的值设置为添加到表单中的实体
$form = $this->createCreateForm($entity); // private function to create the form
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
}
}
return $response;
一旦处理完毕,您只需要返回一个ok响应,或者在出现问题时将表单返回到视图
如果我记得清楚的话,在实体上设置的断言也会通过handleRequest()
自动处理,这取决于您如何声明它们
您也可以在提交后添加其他错误,只需将它们添加到issummitted()
和isValid()
之间即可
我在这里给你留下一些可能有用的文件
$form = $this->createCreateForm($entity); // private function to create the form
$form->handleRequest($request);
if ($form->isSubmitted()) {
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
}
}
return $response;