在Symfony中提交和验证表单后确认表单



>我有一个预约表格,一旦提交,你就会得到你填写的数据的确认,确认有一个按钮,按下它时应该将数据插入数据库。

我的问题是,如何实现确认上的按钮以便插入?


我正在考虑做一个if语句,如下所示:

if ($form->isSubmitted() && $form->isValid()) {
}
在该 if 语句

中,另一个 if 语句将检查确认上的按钮是否已提交,以便我可以使用实体管理器将其插入数据库中。

if ($form->isSubmitted() && $form->isValid()) {
if () {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($appointment);
$entityManager->persist($customer);
$entityManager->flush();
}
}

预约表格: 预约表格

确认模板: 确认模板


预约表格:

{% block body %}
<p>new appointment</p>
{{ form_start(form) }}
{{ form_widget(form) }}
<button class="btn">{{ button_label|default('Plan In') }}</button>
{{ form_end(form) }}
{% endblock %}

确认模板

{% block body %}
<p>confirm appointment</p>
<p>{{ customer_name }}</p>
<p>{{ customer_phone }}</p>
<p>{{ customer_email }}</p>
<hr>
<p>{{ barber_name }}</p>
<p>{{ treatment_name }}</p>
<p>{{ appointment_date|date('d-m-Y') }}</p>
<p>{{ appointment_time|date('H:i') }}</p>
<button class="btn">{{ button_label|default('Confirm') }}</button>
{% endblock %}

如果我的问题中有任何混淆,请要求澄清,如果您认为有更好的方法可以实现我想要实现的目标,请提出建议。

任何帮助不胜感激,提前感谢。

如果您的确认模板不是表单,则将数据发送到控制器的最佳方法可能是使用 Ajax 请求发送数据。单击按钮时,发送请求:

$('#button').click(function(e) {
// guetting all the data you want to send
$.ajax({
type: 'POST',
// url is the route of your controller action 
url: url,
processData: true,
data: objectYouWantToSend
beforeSend: function(request) {console.log('sending someting');},
success: function (data) {
console.log("nailed it");
// some logic you want to do
},
error: function(xhr, textStatus, thrownError) {
console.log('ooops, sometin went wrong');
}
});
}
});

然后,在控制器中,您可以使用以下内容获取数据:

if($request->isXmlHttpRequest()) {
if($request->isMethod('POST')) {
// getting data from request
$data = $request->request;
// symfo logic you want to do

return new JsonResponse(array($status => $message));
}
}

我们可以在不使用javascript的情况下解决这个问题。 我们将通过将表单转发到确认操作来处理提交

/**
* @Route("/submit", name="form-submit")
*/
public function submitApp(){
if ($form->isSubmitted() && $form->isValid()) {
return $this->redirectToRoute('confirm',[form])
}
return $this->render('appo.html.twig', [
'form' => 'form',
]);    
}

单击确认后,我们将保留该值。

/**
* @Route("/confirm", name="form-confirm")
*/
public function confirmApp()
{
if ($form->isSubmitted() && $form->isValid()) {
// if configrm is pressed 
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($appointment);
$entityManager->persist($customer);
$entityManager->flush();
}
}

在视图中

{{ form_widget(myFieldName, { ‘disabled’:’disabled’ }) }}

显示表单限制ReadOnly的值

如果您确实想在不使用form的情况下在确认页面中实现自定义模板,则可以从form中获取值,如下所示:

$data = $form->getData();

像这样将带有资源库的值分配给对象中

$app = new Apportionment();
$app->setCustomer_name($form->get('customer_name')->getData());

然后,如果按下确认,则保留该值。

$entityManager->persist($appointment);
$entityManager->flush();

希望对您有所帮助。

最新更新