如何创建动态生成的表单?

时间:2017-06-30 09:25:51

标签: php jquery ajax symfony

我与分子合作,他们属于一个家庭,并且可以拥有多个分子群,具体取决于他们的家庭。我想为Family制作2个下拉列表,为动态渲染的Molecular Groups制作1个下拉列表。

我试图按照文档:http://symfony.com/doc/current/form/dynamic_form_modification.html但第二个下拉列表总是空的,perhap有人会看到什么是错的

形式:

public function buildForm(FormBuilderInterface $builder, array $options)
{
  $builder
        ->add('molFamily', EntityType::class, array(
            'class' => 'NcstoxBundle\Entity\MolFamily',
            'placeholder' => '',
            'choice_label' => 'molFamily',
            'required' => false
        ));

    $formModifier = function (FormInterface $form, MolFamily $molFamily = null) {
        $molGroup = null === $molFamily ? array() : $molFamily->getMolGroup();

        $form
            ->add('molGroup', EntityType::class, array(
                'class' => 'NcstoxBundle\Entity\MolGroup',
                'choice_label' => 'molGroup',
                'placeholder' => '',
                'required' => true,
                'choices' => $molGroup
            ));
    };

    $builder->addEventListener(
        FormEvents::PRE_SET_DATA,
        function (FormEvent $event) use ($formModifier) {
        $data = $event->getData();

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

    $builder->get('molFamily')->addEventListener(
        FormEvents::POST_SUBMIT,
        function (FormEvent $event) use ($formModifier) {
        $molFamily = $event->getForm()->getData();

        $formModifier($event->getForm()->getParent(), $molFamily);
    });

Contôler:

/**
 * @Route("/mol_group", name="molGroup")
 */
public function molGroupAction(Request $request)
{
    $molecule = new Molecule();
    $form = $this->createForm(FindMolGroupType::class, $molecule);
    $form->handleRequest($request);
    $em = $this->getDoctrine()->getManager();

    $molecules = $em->getRepository('NcstoxBundle:Molecule')->findAll();
    if ($form->isValid() && $form->isSubmitted()) {
        $data = $form->getData();
        $molecules = $em->getRepository('NcstoxBundle:Molecule')->findByMolGroup($data);

        return $this->render('NcstoxBundle:Default:molGroupResult.html.twig', [
            'form' => $form->createView(),
            'molecules' => $molecules,
        ]);
    }
    return $this->render('NcstoxBundle:Default:molGroup.html.twig', array(
        'form' => $form->createView(),
        'molecules' => $molecules,
    ));
}

查看:

{% block body %}
<div class="search">
    <h3>Make a search by Molecular Groups :</h3>
    {{ form_start(form) }}
    {{ form_row(form.molFamily, {'label' : 'Molecule Family'}) }}
    {{ form_row(form.molGroup, {'label' : 'Molecular Group'}) }}
<input type="submit" class="btn btn-primary" value="Search">
    {{ form_end(form) }}
</div>

<script>
    var $molFamily = $('#molecule_molFamily');
    // When sport gets selected ...
    $molFamily.change(function() {
        // ... retrieve the corresponding form.
        var $form = $(this).closest('form');
        // Simulate form data, but only include the selected sport value.
        var data = {};
        data[$molFamily.attr('molFamily')] = $molFamily.val();
        // Submit data via AJAX to the form's action path.
        $.ajax({
            url : $form.attr('action'),
            type: $form.attr('method'),
            data : data,
            success: function(html) {
                // Replace current position field ...
                $('#molecule_molGroup').replaceWith(
                    // ... with the returned one from the AJAX response.
                    $(html).find('#molecule_molGroup')
                );
                // Position field now displays the appropriate positions.
            }
        });
    });
</script>
{{ parent() }}
{% endblock %}

编辑: 我添加关系:molGroup实体:

/**
 * MolGroup
 *
 * @ORM\Table(name="mol_group")
 * @ORM\Entity(repositoryClass="NcstoxBundle\Repository\MolGroupRepository")
 */
class MolGroup
{ 

  /**
 * @ORM\ManyToOne(targetEntity="NcstoxBundle\Entity\MolFamily", inversedBy="molGroup")
 * @ORM\JoinColumn(nullable=false, onDelete="CASCADE")
 */
private $molFamily;

/**
 * @ORM\ManyToMany(targetEntity="NcstoxBundle\Entity\Molecule", inversedBy="molGroup")
 */
private $idMolecule;

molFamily实体:

/**
 * MolFamily
 *
 * @ORM\Table(name="mol_family")
 * @ORM\Entity(repositoryClass="NcstoxBundle\Repository\MolFamilyRepository")
 */
class MolFamily
{

  /**
 * @ORM\ManyToOne(targetEntity="NcstoxBundle\Entity\Molecule", inversedBy="molFamily")
 */
private $idMolecule;

/**
 * @ORM\OneToMany(targetEntity="NcstoxBundle\Entity\MolGroup", mappedBy="molFamily")
 */
private $molGroup;

0 个答案:

没有答案