dpjw67160 2019-03-25 13:55
浏览 69
已采纳

Symfony 4表格 - 阿贾克斯选择人口

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:

enter image description here

enter image description here

  • 写回答

1条回答 默认 最新

  • doujun1495 2019-03-25 16:19
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置