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

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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题