如何在 Symfony 中提交表单后关闭 Window 选项卡?
How to close Window Tab After Submitting a Form in Symfony?
我正在 window 选项卡中提交一个 symfony 表单。提交按钮应在提交表单后关闭 window 并刷新打开页面。所以我用 jquery 来做这部分。
$('#submitAndClose').on('submit', function () {
setTimeout(
function () {
opener.location.reload(true);
window.close();
}
, 3000);
})
但我猜是因为 symfony 在提交后刷新了页面,预计 jquery 没有工作。
这是我在 SymfonForm 中的提交按钮:
->add('saveAndClose', SubmitType::class, [
'label' => 'Save and close',
])
这是树枝部分:
{{ form_widget(form.saveAndClose, {
attr: {
id: 'submitAndClose',
}
}) }}
这是控制器部分,因为 Nico Hasse 请求了更多信息:
/**
* @param Request $request
* @param int $id
*
* @return Response
*
* @Route("/{id}", methods={"GET", "POST"})
*/
public function editAction(
Request $request,
int $id
): Response {
$user = $this->em->getRepository(User::class)->find($id);
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->flush();
}
return $this->render('user/edit.html.twig', [
'form' => $form->createView(),
]);
}
现在,当我提交表单时,它可以工作,但不会关闭 Window。
setTimeout只是为了测试,没有必要。
有什么想法吗?
为什么要重新加载页面?由于您重新加载页面,它不会关闭,您可以使用普通的 JavaScript.
document.getElementById('saveAndClose').onclick = () => window.close();
但是你的情况可能像this picture.
您不应使用超时来关闭选项卡。
您可以在处理完表单后传递一个变量,例如close_window
,来查看。在视图中,您可以执行以下操作而不是超时:
{% if close_window|default %}
<script>window.close();</script>
{% endif %}
我正在 window 选项卡中提交一个 symfony 表单。提交按钮应在提交表单后关闭 window 并刷新打开页面。所以我用 jquery 来做这部分。
$('#submitAndClose').on('submit', function () {
setTimeout(
function () {
opener.location.reload(true);
window.close();
}
, 3000);
})
但我猜是因为 symfony 在提交后刷新了页面,预计 jquery 没有工作。
这是我在 SymfonForm 中的提交按钮:
->add('saveAndClose', SubmitType::class, [
'label' => 'Save and close',
])
这是树枝部分:
{{ form_widget(form.saveAndClose, {
attr: {
id: 'submitAndClose',
}
}) }}
这是控制器部分,因为 Nico Hasse 请求了更多信息:
/**
* @param Request $request
* @param int $id
*
* @return Response
*
* @Route("/{id}", methods={"GET", "POST"})
*/
public function editAction(
Request $request,
int $id
): Response {
$user = $this->em->getRepository(User::class)->find($id);
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->em->flush();
}
return $this->render('user/edit.html.twig', [
'form' => $form->createView(),
]);
}
现在,当我提交表单时,它可以工作,但不会关闭 Window。
setTimeout只是为了测试,没有必要。 有什么想法吗?
为什么要重新加载页面?由于您重新加载页面,它不会关闭,您可以使用普通的 JavaScript.
document.getElementById('saveAndClose').onclick = () => window.close();
但是你的情况可能像this picture.
您不应使用超时来关闭选项卡。
您可以在处理完表单后传递一个变量,例如close_window
,来查看。在视图中,您可以执行以下操作而不是超时:
{% if close_window|default %}
<script>window.close();</script>
{% endif %}