twig form in modal window not submitting data

落爺英雄遲暮 提交于 2021-02-11 12:30:15

问题


I'm attempting to submit a form which appears in a modal window. I know that the form works if I run it as a separate window, however in the modal it appears to be submitting nothing and returning no errors or anything in Symfony.

Here is how I call it in the twig:

    <button data-toggle="modal" href="{{ path('new_ingredient') }}" data-target="#ingredient_new">Add a new ingredient</button>


<div class="modal fade" id="ingredient_new">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                {{ render(controller('App\\Controller\\DishController:newIngredient')) }}

            </div>
        </div>
    </div>

</div>

And here is my controller:

/**
 * @Route("/ingredient/new", name="new_ingredient")
 */
public function newIngredient(Request $request)
{

    $ingredient = new Ingredient();

    $form = $this->createForm(NewIngredientType::class, $ingredient);

    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {
        $ingredient = $form->getData();
        $em = $this->getDoctrine()->getManager();

        $em->persist($ingredient);
        $em->flush();


        return $this->redirectToRoute('dashboard');

    }

    return $this->render('ingredients/new.html.twig', array(
            'form' => $form->createView())
    );
}

I feel like there's something missing in the twig here. Is there something obvious I'm missing? Like I mentioned, the form itself works if I call it separately, but after submitting it does nothing in the modal.

Edit Here's the form itself; it's quite simple, only one field and a submit

class NewIngredientType extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        parent::buildForm($builder, $options); // TODO: Change the autogenerated stub

        $ingredient = new Ingredient();

        $builder

            ->add('name', TextType::class, array(
                'attr' => array('class' => 'form-control'),

            ))


            ->add('save', SubmitType::class, array(
                'label' => 'Save',
                'attr' => array('class' => 'btn btn-primary mt-3')
            ))
            ->getForm();

    }

}

The twig that is used to create the modal window is this:

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

回答1:


okay, after some searching and with the help of @msg above, I came up with a solution.

I needed to explicitly define the action for the generated form in the window, and it worked.

This is a variation on what I used

{{ form_start(form, {'action' : path('new_ingredient')}) }}
{{ form_widget(form) }}
{{ form_end(form) }}


来源:https://stackoverflow.com/questions/61296151/twig-form-in-modal-window-not-submitting-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!