Bootstrap Modal with WTF
Asked Answered
G

2

5

I got several user input fields inside Bootstrap Modal and I'm trying to do some validation before users can submit it.

I've looked around several related articles and nothing has worked for me so far.

So the main problem that I'm having is that, everytime I press submit, the modal window closes so that users cannot see the error messages. I want the modal window to stay open until a successful submission occurs.

Below is my modal

<button type="button" class="btn btn-default" data-toggle="modal" data-target="#editModal" style="float:right">
  <span class="glyphicon glyphicon-edit"></span> Edit
</button>

<!-- Modal -->
<div class="modal fade" id="editModal" role="dialog" >
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content" >
      <div class="modal-header" >
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4>Edit Your Login Information</h4>
      </div>

      <div class="modal-body">
        <form action="{{ url_for('.profile') }}" method='post' name='edit_user' class="form-horizontal" >
          {{ user_edit_form.csrf_token }}
          <div class="form-group col-xs-12 col-md-12 col-lg-12" style="background-color:white; !important ">
            <div class="col-xs-12 col-md-12 col-lg-12" >
              {{ render_field(user_edit_form.first_name) }}
            </div>
            <div class="col-xs-12 col-md-12 col-lg-12">
              {{ render_field(user_edit_form.last_name) }}
            </div>
            <div class="col-xs-12 col-md-12 col-lg-12">
              {{ render_field(user_edit_form.email) }}
            </div>
            <div class="col-xs-12 col-md-12 col-lg-12">
              {{ render_field(user_edit_form.institute) }}
            </div>
            <div class="col-xs-12 col-md-12 col-lg-12">
              <input class='btn btn-primary' id='uform' type='submit' value='UPDATE' style="float:right"/>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

and the javascript that I'm trying to get it to work

<script>
  var formErrors = {% if user_edit_form.errors %}true{% else %}false{% endif %};
  $(document).ready(function() {
    if (formErrors) {
      $('.Modal').modal('show');
    }
  });
</script>

Any help will be really appreciated!!

Gawlas answered 18/1, 2017 at 1:7 Comment(0)
A
9

First you need to prevent the default action of your submit button which would be to send a post request and close your modal form. You can do this in the click event of the submit button by using event.preventDefault(). Next you would serialize your form data and send the post request via Ajax. If the view function returns "ok" you hide the dialog and reload your current page. Otherwise you will display the hml code with the error messages. Take the following steps:

1. Give your form an id:

<form id="editForm" action="{{ url_for('.profile') }}" method="post" name="edit_user" class="form-horizontal">

2. Add Javascript code (needs jQuery)

$('#uform').click(function(event) {
  event.preventDefault();
  $.post(url, data=$('#editForm').serialize(), function(data) {
    if (data.status == 'ok') {
      $('#editModal').modal('hide');
      location.reload();
    }
    else {
      $('#editModal .modal-content').html(data);
    }
  });
})

3. Modify your view function

@main.route('/yourroute', methods=['GET', 'POST'])
def profile():
    form = YourForm()
    if form.validate_on_submit():
        user = UserEditForm()
        user.first_name = form.first_name.data
        user.last_name = form.last_name.data
        # ...
        db.session.add(user)
        db.session.commit()
        return jsonify(status='ok')
    return render_template('yourtemplate.html', form=form)
Alleman answered 18/1, 2017 at 7:29 Comment(4)
This did not work, I don't know why but some reason it just would not do anything, but thank you for your detailed explanation, I just decided to open a new page rather than doing the edit on Modal. Its just too much hastle.Gawlas
@MrLeeh, can we do this without JS requirement?Dolly
@Alleman I think in step 3 you need to initialise the form with the args? Otherwise all values are empty because it's just an empty form. If I do this it works on my end: form = YourForm(request.args) Ah never mind, it was because I did a 'get' request. Apparently when you do a POST it magically fills the form even though it seems you instantiate it out of nothing... Magic...Gantt
I have almost same problem, but I need to display flash messages in modal window, without closing it. I've described my problem here #54231015Hairstyle
F
0

You can use "pywebio" package which integrates in Flask and works on its own route (integrate means that use WSGI server). Unfortunately its not so easy to manage return to your route but is manageable. And you'll need a way to share data between them which is also manageable. From "pywebio" you can raise messages as classic (Flask built in style) or pops like. The desined form can be real "modal" and "popup". You need to evaluate opportunity to do this work but results are excellent from functional point of view. (you can see a real example of this "combination" at http://90.84.237.32:31000/etl_admin)

Fantasize answered 30/11, 2022 at 10:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.