zeroku
zeroku

Reputation: 33

Bootstrap modal form disappears when submitted with errors

I've just converted a form to a Bootstrap modal and it works fine except when submitted with errors the modal just disappears. Clicking on the modal trigger button brings the modal back up with the user's data and error messages.

Here's my code:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" 
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-body">
                <form method='POST' action=''>
                    {% csrf_token %}
                    {{ form.as_p }}
                    <input id='submit-button' type="submit" value="Submit">
                </form>
            </div> <!-- modal-body -->
        </div>
    </div>
</div>

<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">Apply now</button>

I'm using Django but I don't think that's got anything to do with it because everything worked until I wrapped the form in a modal. Here's my view.py:

def homepage(request):
    form = MyForm(request.POST or None)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.user = request.user
        instance.save()
        return HttpResponseRedirect(reverse('success'))
    context = {
        "form": form,
    }
    return render(request, 'home.html', context)

Can someone tell me what I'm doing wrong?

Upvotes: 3

Views: 973

Answers (1)

Exik
Exik

Reputation: 218

After submit there is no information about modal, it's hidden like on the first time when you open the page. You can add some condition to open modal if there is an error.

I don't know Django, but the idea is to add some param to model:

if (bindingResult.hasErrors()) {
    model.addAttribute("formErrors", true);
}

And then check (I use Thymeleaf in this example):

<th:block th:if="${formErrors}">
    <script>$('#myModal').modal('show');</script>
</th:block>

Upvotes: 1

Related Questions