【问题标题】:Populate field dynamically based on the user choice value in the another field in Symfony 5根据 Symfony 5 中另一个字段中的用户选择值动态填充字段
【发布时间】:2020-04-03 08:47:49
【问题描述】:

我正在尝试从“https://symfony.com/doc/current/form/dynamic_form_modification.html#form-events-submitted-data”这边“根据用户在 Symfony 5 中另一个字段中的选择动态更新字段”。但是我遇到了这个异常/错误“传递给 App\Form\SportMeetupType::App\Form{closure}() 的参数 2 必须是 App\Form\Sport 的实例或 null,给出的 App\Entity\Sport 的实例,称为在 C:\Apache24\htdocs\dynamicform\src\Form\SportMeetupType.php 中的第 58 行“调用 ajax 时。

我的代码:

表格:

class SportMeetupType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')

            ->add('sport', EntityType::class, [
                'class'       => 'App\Entity\Sport',
                'placeholder' => '',
            ])

        ;


        $formModifier = function (FormInterface $form, Sport $sport = null) {
            $positions = null === $sport ? [] : $sport->getPositions();

            $form->add('position', EntityType::class, [
                'class' => 'App\Entity\Position',
                'placeholder' => '',
                'choices' => $positions,
            ]);
        };

        $builder->addEventListener(
            FormEvents::PRE_SET_DATA,
            function (FormEvent $event) use ($formModifier) {
                // this would be your entity, i.e. SportMeetup
                $data = $event->getData();

                $formModifier($event->getForm(), $data->getSport());
            }
        );

        $builder->get('sport')->addEventListener(
            FormEvents::POST_SUBMIT,
            function (FormEvent $event) use ($formModifier) {
                // It's important here to fetch $event->getForm()->getData(), as
                // $event->getData() will get you the client data (that is, the ID)
                $sport = $event->getForm()->getData();

                // since we've added the listener to the child, we'll have to pass on
                // the parent to the callback functions!
                $formModifier($event->getForm()->getParent(), $sport);  // Here line 58 and error show this line
            }
        );

    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => SportMeetup::class,
        ]);
    }
}

控制器:

/**
 * @Route("/new", name="sport_meetup_new", methods={"GET","POST"})
 */
public function new(Request $request): Response
{
    $sportMeetup = new SportMeetup();
    $form = $this->createForm(SportMeetupType::class, $sportMeetup);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($sportMeetup);
        $entityManager->flush();

        return $this->redirectToRoute('sport_meetup_index');
    }

    return $this->render('sport_meetup/new.html.twig', [
        'sport_meetup' => $sportMeetup,
        'form' => $form->createView(),
    ]);
}

树枝/视图:

{% extends 'base.html.twig' %}

{% block title %}New SportMeetup{% endblock %}

{% block body %}
    <h1>Create new SportMeetup</h1>

   {{ form_start(form) }}
    {{ form_row(form.name)}}
    {{ form_row(form.sport) }}    {# <select id="sport_meetup_sport" ... #}
    {{ form_row(form.position) }} {# <select id="sport_meetup_position" ... #}
    {# ... #}
{{ form_end(form) }}


{% endblock %}

JavaScript 代码:

var $sport = $('#sport_meetup_sport');
// When sport gets selected ...
$sport.change(function() {

  // ... retrieve the corresponding form.
  var $form = $(this).closest('form');

  // Simulate form data, but only include the selected sport value.
  var data = {};
  data[$sport.attr('name')] = $sport.val();
  // Submit data via AJAX to the form's action path.
  $.ajax({
    url : $form.attr('action'),
    type: "POST",
    data : data,
    success: function(html) {

      // Replace current position field ...
      $('#sport_meetup_position').replaceWith(
        // ... with the returned one from the AJAX response.
        $(html).find('#sport_meetup_position')
      );
      // Position field now displays the appropriate positions.
    }
  });
});

当更改运动下拉值时,调用 ajax 并在异常/错误下方显示 “传递给 App\Form\SportMeetupType::App\Form{closure}() 的参数 2 必须是 App\Form\Sport 的实例或 null,给出的 App\Entity\Sport 实例,在 C:\Apache24\htdocs 中调用\dynamicform\src\Form\SportMeetupType.php 第 58 行"

请帮帮我....

【问题讨论】:

  • 请给我看一个 var_dump($sport); $formModifier 中的 $sport ($event->getForm()->getParent(), $sport); // 这里是第 58 行,错误显示这一行

标签: symfony


【解决方案1】:

确保您的 SportMeetupType.php 中有:

use App\Entity\Sport;

我认为你使用了错误的类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    相关资源
    最近更新 更多