php - Symfony 4 Form - Ajax 选择人口

标签 php ajax forms symfony

有没有办法使用 ajax 异步填充表单 ChoiceType(下拉)?

基本上我想做的是:

简短描述:简单的预订系统。

详细描述:

当用户在“preferredDate”中使用日期选择器(或其他)选择日期时, ajax 调用将检查所选日期是否有可用的时间段,并使用时间填充“availableTimes”ChoiceType(下拉列表)(例如:10:00、10:30、11:00、11:30 等) .

可用时间不在数据库中。

我的表单:

 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]);
    }

我的 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);
            }
        });
    })

当我发送选定的时间时它起作用了它抛出一个错误“这个值无效”

我做错了什么?

你会怎么做?

编辑:没有验证集,但出于某种原因它仍然想验证 ChoiceType ... EDIT2:阅读所有旧的 SF2 答案,但所有答案都是关于使用事件发送表单 2 次以上。

EDIT3:来自 _profiler 的错误:

enter image description here

enter image description here

最佳答案

我终于成功了。添加了EventListener,其他基本一样。

我的表单:

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
                        ]
                    )
                );
            });


    }

我的 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);
            }
        });
    })

建议或提示将不胜感激。

关于php - Symfony 4 Form - Ajax 选择人口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55339452/

相关文章:

php如何从exe文件接收多个cout?

php - 创建 PHP 多用户登录

php - 浏览器挂起执行运行 Powershell 的 PHP

javascript - Ajax代码问题

html - 更正 CSS 以按特定顺序显示 html 表单元素?

javascript - JQuery 字符串干净的 html

javascript - redux 形式错误 : Element type is invalid: expected a string or function

javascript - 本地主机路由在实时环境中有效吗?

javascript - ReactJS 表单渲染问题

javascript - ajax表单: success doesn't work as expected