how can I append a new field to Symfony form?

Viewed 41

I am trying to append a new input field to my symfony form using javascript, I want to pass some data with the form submission.

This what I tried to do :

var form = document.getElementById('payment-form');
form.addEventListener('submit', function (event) {
      event.preventDefault();
      var form = document.getElementById('payment-form');
      var hiddenInput = document.createElement('newInput');
      hiddenInput.setAttribute('type', 'hidden');
      hiddenInput.setAttribute('name', 'newInputName');
      hiddenInput.setAttribute('value', "newInputValue");
      form.appendChild(hiddenInput);
      form.submit();
});

But I am stuck on how to get the new submitted input.

Any help would be much appreciated.

Thanks

1 Answers

Why don't you use the Symfony form instead? It's going to be easier to use. You can call an Ajax request to the controller, create a form using the Symfony's Form System and make the request to return a template with the fields. I enclose you an easy example:

Controller:

/**
 * @Route("/myAjaxRequest", name="your_route_name", options={"expose"=true}, methods={"POST"})
 * @return Response
 */
public function myAjaxAction(Request $request)
{
    $form = $this->createForm(YourFormType::class, $yourObject, []);
    $form->handleRequest($request);

    if ($form->isSubmitted()) {
        if ($form->isValid()) {
            //Whatever you want if you submit the form 
            return new Response('1');
        }
    }

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

The Form:

    <?php

    namespace App\Form;
    
    use...

    class MyFormType extends AbstractType
    {
    /**
     * {@inheritdoc}
    */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('your_field', TextType::class, [
            'label' => 'This is my field!'
            ])
        ]);
    }
    }

The template:

{{ form_start(form) }}
{{ form_row(form.your_field) }}
//If you want to add your custom field via HTML, this will be submitted
<input type="checkbox" id="add_your_field"/>
{{ form_end(form) }}

Hope this helps

Related