在非实体类上以Symfony形式添加ChoiceType选项 [英] Add ChoiceType options in Symfony form on Non Entity Class
问题描述
我有Ajax请求提交的Symfony表单。此表单包含2个字段:日期(datepicker)和天数(choiceType)。我无法初始化表单生成的天数,因为它依赖于所选日期。使用Javascript,我更新select-picker中的选项。这非常有效。通常,选项如下所示:< option value =1> 1 jours< \option>
。
I have a Symfony form submitted by Ajax request. This form contains 2 fields : a date (datepicker) and a number of days (a choiceType). I can't initialize the number of days when the form is built since it relies on the date selected. Using Javascript, I update the options in select-picker. That works very well. Typically, an option looks like this : <option value="1">1 jours<\option>
.
现在,提交表单时,我需要在choiceType中添加这些字段。
Now, when the form is submitted, I need to add those fields in the choiceType.
我使用了isXmlHttpRequest方法,因为表单是用Ajax请求提交的,等待答案。 如果表单有效,我需要通知Ajax调用(我不想渲染另一个模板)。
我在Controller中执行以下操作:
I used isXmlHttpRequest method because the form is submitted with an Ajax request, waiting for an answer. If the form is valid, I need to inform the Ajax call (I dont want to render another template). I do the following in the Controller:
/**
* @param Request $request
* @return Response
* @Route("/ajout_favoris", name="ajoutFavoris")
*/
public function ajoutFavoris(Request $request){
$form = $this->creerFormulaire()->getForm();
$form->handleRequest($request);
if ($request->isXmlHttpRequest()){
if ($form->isValid() ) {
// actions ...
$reponse = ['statut' => 'success'];
}else {
$reponse = ['statut' => 'form-invalid'];
}
$reponse = new Response(json_encode($reponse));
$reponse->headers->set('Content-Type', 'application/json');
return $reponse;
}
return $this->render('@Carte/Reservation/reservation.html.twig', array(
"form" => $form->createView() ));
以下是我构建表格的方式:
Here is how I build the form :
public function creerFormulaire(){
$formulaire = $this->createFormBuilder()
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
$optionList = $this->getValidChoicesForNbJours($data["nbJours"]);
$form->add('nbJours', 'choice', array(
'attr' => [ 'placeholder' => 'nombre de jours',
'class' => 'selectpicker',
],
'choices' => $optionsList,
));
})
->add('dateDebut', DateTimeType::class, [
'widget' => 'single_text',
'format' => 'dd/MM/yyyy',
'input' => 'datetime',
'label' => 'Date début',
'required' => true,
'attr' => ['class' => 'datepicker input-date',
'type' => 'text',
'placeholder' => 'JJ/MM/AAAA',
'readonly' => true,
'required' => true,]
])
->add('nbJours', 'choice', [
'label' => 'Nombre de jours',
'choices' => [],
'attr' => [ 'placeholder' => 'nombre de jours',
'class' => 'selectpicker',
'title' => 'Nombre de jours',
'readonly' => true,
'required' => false,]
])
->add('ajoutFavoris', SubmitType::class, [
'label' => 'Ajouter aux favoris',
'attr' => [ 'class' => 'btn btn-primary reserver' ]
]);
return $formulaire;
}
在这里我如何填写选项:
And here how I fill the options :
public function getValidChoicesForNbJours($range){
$liste = [];
for ($i = 1; $i <= $range; $i++){
$liste[$i.' jours'] = strval($i);
}
return $liste;
}
这里是ajax电话:
path_to_add_fav = ...
idPlan = ...
$("#form_ajoutFavoris").click(function (e) {
let dateDebut = document.getElementById('form_dateDebut').value;
let nbJours = document.getElementById('form_nbJours').value;
if (dateDebut && nombreJours){
let data = {
poste_id: idPoste,
plan_id: idPlan,
nbJours: nbJours ,
};
$.ajax({
url: path_to_add_fav,
type: "post",
data: JSON.stringify(data),
dataType: "json",
success: function (data) {
console.log(data.statut);
if (data.statut === "success") {
window.parent.$.fancybox.close();
}
}
});
}
});
Chrome控制台中没有错误。在fisrt提交时,它总是显示 form-invalid
,对于以下内容,有时会显示 form-invalid
,什么都没有...
There is no error in Chrome console. At the fisrt submit, it always display form-invalid
, on the following, sometimes display form-invalid
, sometines nothing...
我读过很多类似帖子,但未能实现我的。这篇文章与这个一个相关,但问题现在不同了。
I read a lot of "similar post" but haven't been able the achieve mine. This post is related to this one but the question is now different.
感谢您阅读!
编辑:添加HTML
EDIT : Add HTML
{{ form_start(form) }}
<div class="card-deck maxheight">
{% include '@Carte/Carte/poste_card.html.twig' with {'poste':poste, 'connected':connected, 'showbtn':false } %}
<div class="card card-form" id="card-reserv">
<div class="card-body">
{{ form_errors(form) }}
<div id="warning-pecheurs" class="alert alert-warning padding alert-dismissible"
role="alert">
<button type="button" class="close float-right" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
warning message
</div>
<table id="table" class="largeur">
<colgroup>
<col span="1" class="col1">
<col span="1" class="col2">
</colgroup>
<tbody>
<tr>
<td>
<div class="input-group">
{{ form_label(form.dateDebut) }}
</div>
</td>
<td class="date">
{{ form_widget(form.dateDebut) }}
</td>
</tr>
<tr>
<td colspan="2">
{{ form_errors(form.dateDebut) }}
</td>
</tr>
<tr>
<td>
<div class="input-group">
{{ form_label(form.nbJours) }}
</div>
</td>
<td>
{{ form_widget(form.nbJours) }}
</td>
</tr>
<tr>
<td colspan="2">
{{ form_errors(form.nbJours) }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="row margin0">
<button type="button" class="btn btn-secondary" data-dismiss="modal"
onclick="window.parent.$.fancybox.close()" value="CloseFB">
Annuler
</button>
{{ form_widget(form.ajoutFavoris) }}
</div>
{{ form_end(form) }}
这里我如何填充JS中的select-picker:
And here how I populate the select-picker in JS:
let new_options = "";
for (i = 0; i < nbOptions; i++, j++)
new_options += "<option value=" + j + ">" + j + " jours</option>";
$("#form_nbJours").html(new_options).selectpicker('refresh');
编辑:解决方案
Ajax方法调用是有罪的!通过这个电话,它完美无缺!
EDIT : Solution The Ajax method call is the guilty ! With this call, it works perfectly !
$('form').submit(function (e) {
console.log("ok");
e.preventDefault();
let formSerialize = $(this).serialize();
$.post(path_to_add_fav, formSerialize, function(response) {
console.log(response.statut);
if (response.statut === "success") {
console.log("Réponse correcte !");
window.parent.$.fancybox.close();
}
}, 'JSON');
}
推荐答案
您可以通过调用禁用表单验证添加字段后 $ builder-> get('nbJours') - > resetViewTransformers();
you can disable form validation by calling $builder->get('nbJours')->resetViewTransformers();
after you have added the field
这篇关于在非实体类上以Symfony形式添加ChoiceType选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!