Preciel
Preciel

Reputation: 2827

Supplement form on the fly

[SETTINGS]

[PROBLEM]

I would like to know how to supplement a form with data from an Ajax request.

In my main form, I can select only select the package form (form_id). Once it's selected, via an Ajax request, I will look up for every material objects which are compatible with the selected form:

Form my controller, I'm calling my form builder :

FormMaterialsType.php

public function buildSupplementForm(FormBuilderInterface $builder, array $options) {
    $builder
        ->add('material', EntityType::class, array(
            'class' => 'AppBundle\Entity\Material',
            'choice_label' => 'Material',
            'query_builder' => function(EntityRepository $er) {
                return $er->createQueryBuilder('m')
                          ->where('m.form= :form');
                          ->setParameters(array(
                              new Parameter('form', $options['form_id']),
                ))
            },
            'empty_data' => null,
            'required' => true)
        );
}

The problem is that I'm getting a full form. How can I get only the select bloc?

Upvotes: 0

Views: 78

Answers (1)

l.g.karolos
l.g.karolos

Reputation: 1142

What you actually need is this

The main steps are:

  • Listen for a change event on your package select box
  • Submit the form from javascript
  • In your FormType you need to add a subscriber and listen for a POST event on your form
  • Inside your subscriber you must create the functionality so based on the selection in package to query for the right materials
  • After all that is done in your javascript you load the new select box by replacing it with the new one

Symfony Docs Example:

$("#material_select_box_id").replaceWith($(html).find('#material_select_box_id'));

So now your material select box will be loaded with the data from the subscriber

Upvotes: 1

Related Questions