Is there a way to populate form ChoiceType (dropdown) asynchronously using ajax?
Basically what I'm trying to do:
Short description: Simple booking system.
Long description:
When user selects a date by using datepicker (or whatever) in "preferredDate", ajax call will check if there is an available time slot for selected date and populates the "availableTimes" ChoiceType (dropdown) with times (for example: 10:00, 10:30, 11:00, 11:30, etc..).
Available times are not in database.
My form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('preferredDate', DateType::class, [
'widget' => 'single_text',
'input' => 'datetime',
'format' => 'dd.MM.yyyy',
])
->add('availableTimes', ChoiceType::class, ['required' => false]);
}
My JS:
$(".reservation-date").change(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "{{URL}}",
data: {},
success: function (data) {
$(".reservation-times").empty();
$.each(data, function (key, value) {
//populate availabletimes dropdown
let disabled = (value.disabled === true ? "disabled" : '');
$(".reservation-times").append('<option ' + disabled + ' value=' + value.time + '>' + value.time + '</option>');
})
}
,
error: function (error) {
console.log(error);
}
});
})
It works bu when I send selected time It throws an error "This value is not valid"
What I'm doing wrong?
How would you do it differently?
EDIT: There is no validation set but for some reason it still wants to validate that ChoiceType ... EDIT2: Read all the old SF2 answers but all of them are about sending form 2+ times using the events..
EDIT3: Errors from _profiler:


I finally made it. Added EventListener, everything else is basically the same.
My form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('preferredDate', DateType::class, [
'widget' => 'single_text',
'input' => 'datetime',
'format' => 'dd.MM.yyyy',
])
->add('availableTimes', ChoiceType::class)
->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
// get the form from the event
$form = $event->getForm();
$formOptions = $form->getConfig()->getOptions();
//helpers
$availableTimeHandler = $formOptions['availableTimeHelper'];
// get the form data, that got submitted by the user with this request / event
$data = $event->getData();
//get date
$preferredDate = $data['preferredDate'];
// get the availableTimes element and its options
$fieldConfig = $form->get('availableTimes')->getConfig();
$fieldOptions = $fieldConfig->getOptions();
/**
* Getting available times logic is here,
* not showing because it's irrelevant to the issue.
*
* $times array example:
* [
* ['time' => '10:00', 'disabled' => false],
* ['time' => '11:00', 'disabled' => true],
* ['time' => '12:00', 'disabled' => true],
* ]
*/
$choices = [];
foreach ($times as $time) {
$choices[] = [$time['time'] => $time['time']];
}
//update choices
$form->add('availableTimes', ChoiceType::class,
array_replace(
$fieldOptions, [
'choices' => $choices
]
)
);
});
}
My JS:
$(".reservation-date").change(function () {
$.ajax({
type: "GET",
dataType: "json",
url: "{{URL}}",
data: {},
success: function (data) {
$(".reservation-times").empty();
$.each(data, function (key, value) {
//populate availabletimes dropdown
let disabled = (value.disabled === true ? "disabled" : '');
$(".reservation-times").append('<option ' + disabled + ' value=' + value.time + '>' + value.time + '</option>');
})
}
,
error: function (error) {
console.log(error);
}
});
})
Suggestions or tips would be appreciated.
In case of another stuck developpers in this case , the solution that worked for me is explained here : https://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms
I did something similar , and use two events PRE_SET_DATA & POST_SUBMIT , i'm not using doctrine so my code can be strange for some :
//The form
$builder
->add('Pays', ChoiceType::class, [
'choices' => $this->paysRepository,
'attr' => ['class' => 'select2'],
'mapped' => false,//Pays don't exist in Panneau Entity
'constraints' => [
new NotBlank([
'message' => 'Veuillez choisir un pays'
])
]
])
->add('NumVille', ChoiceType::class, [
'attr' => ['class' => 'select2'],
'placeholder' => 'Villes',
'constraints' => [
new NotBlank([
'message' => 'Veuillez choisir une ville'
])
]
]);
Now The event saver :
//The function that fill the dropdown
$formModifier = function (FormInterface $form,String $pays) {
//$choices = null === $ville ? [] : $ville->getAvailablePositions();
if( !empty($pays) ){
$choices = $this->villeRepository->findCities($pays);//findcities is a function that bring data , cuz i'm not using doctrine
}else{
$choices = [];
}
$form->add('NumVille', ChoiceType::class, [
'choices' => $choices,
]);
};
//PRE SET DATA EVENT
$builder->get('Pays')->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifier) {
//Get Form DATA
$data = $event->getData();
if ($data) {
$formModifier($event->getForm(), $data);
}
}
);
//POST SUBMIT EVENT
$builder->get('Pays')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier) {
$data = $event->getForm()->getData();
$formModifier($event->getForm()->getParent(), $data);
}
);
The NumVille Dropdown is filled by ajax in the front.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With