Livewire form submit within template

What seems to be the problem:

When submitting a form which is placed inside a conditional template, rather than posting the form and displaying the relevant validation errors the entire page reloads with a question mark appended to the address bar.

Do you have any screenshots or code examples:

<template x-if="modal === 'regModal'">
  <form wire:submit.prevent="submit">
    <!-- omitted -->
    <button type="submit">Submit</button>
  </form>
</template>

The modal form hides/shows as expected, it’s just the form submission which doesn’t work correctly.

Update: it appears not only does the form submission no longer work but even wire:model updates, no XHR requests are being sent when typing in the form input fields.

Update 2: I’ve now placed the template tag inside a div tag and this is the root of my livewire component, still experiencing the issue.

Any ideas?

Is there a reason you’re placing the form as javascript vs using blade to parse in the proper form? If so, maybe you can move the form element to the top of the template and then use the template to handle the fields you want to pass through the form. Something like:

<form wire:submit.prevent="submit">
    <template x-if="modal === 'regModal'">
        <!-- whatever input fields you need -->
        <button type="submit">Submit</button>
    </template>
</form>

Otherwise, I’d try to stay in livewire as much as possible and use blade to parse in different forms but understand if there’s some dynamic stuff you need to do in the front end.

Hi @shortbrownman, thanks for your reply and help.

I’m doing it this way because I have multiple forms which I’m displaying inside a modal pop up window (one at a time), which is controlled by JS (Alpine) in terms of opening and closing. It was working fine until I realised using only x-show on the modal meant that all forms were rendered and I was duplicating input ID attributes which then caused me problems with other things.

So then I thought I would try using the template tag so that only one form would be present in the DOM at any one time, then started running into problems as described in my post above.

I tried what you described but does not seem to have much effect, when I watch the element using dev tools the form appears fine, but as soon as I hit submit the template tag disappears, it’s like Livewire is ignoring the template tag altogether, however the form does submit now as opposed to reloading the page altogether but wire:model updates are not firing as I type.

Do you have a single root element in your template or are you just rendering within the template tags. Try wrapping your code inside your template within a div:

<template>
    <div>
        <!-- your code here -->
    </div>
</template>

Hi, yep the root element inside template tag is a div.

I’ve also posted an issue on GitHub: https://github.com/livewire/livewire/issues/991