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 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题