Input button in modal not submitting external form - html

I have created an inline formset with Django. Once the form is filled out and the user clicks Submit I have coded in a Bootstrap modal that pops up a reminder. The footer of the modal contains an HTML input so the external form can be submitted from the modal.
The problem I am having is that the submit buttons does not submit the form so it can be saved to the database and emailed. Is there a way do accomplish this using a modal?
Template:
{% extends "reports/base.html" %}
{% load static %}
{% block body_block %}
<font color="green">
<h4 >Company</h4>
</font>
<h3>Please enter your nightly reports in the form below.</h3>
<br>
<p>If you would like to add a new line to a category, select <font color="blue">add New Line Item</font> under each category.
When finished, click on <strong><font color="gray">Save and Email to Corporate</font></strong> button at the bottom of the form.</h4>
Once the form is sent, the form will refresh with the information you have entered. If you notice an error after you sent the form, edit the error and click the <strong><font color="gray">Save and Email to Corporate</font></strong> button again to update and resend.</p>
<br>
<h5>If you would like a blank form, click <font color="green"> here</font>.</h5>
<br>
<br>
<div class="container-fluid">
<form class="form-inline" action="" method="post">
{% csrf_token %}
{{ form }}
<table class="table">
{{ formset_new.management_form }}
<div>
<br><h4><strong>New</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_new formset_class_name='new' prefix="new" %}
</div>
</table>
<table class="table">
{{ formset_renewal.management_form }}
<div>
<br><h4><strong>Renewals</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_renewal formset_class_name='renewal' prefix="renewal" %}
</div>
</table>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<br>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"><strong>Submit</strong></button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Before You Submit!!</h4>
</div>
<div class="modal-body">
<p>Please review and make sure that all line items are correct and that the <strong>"Check if No New Items"</strong> is checked if there are no new items for that catagory. If all is correct, please select the <strong>Save and Email</strong> button.</p>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary" value="Save and Email to Corporate">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}

After researching the HTML input element, I found that you can use the id attribute to id the <form> element and call the id using the form attribute in the <input> element that is coded in the Bootstrap Modal. The relevant updated code is below.
<div class="container-fluid">
<form id="formset" class="form-inline" action="" method="post"> <!--added id="formset" to the form element-->
{% csrf_token %}
{{ form }}
<table class="table">
{{ formset_new.management_form }}
<div>
<br><h4><strong>New</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_new formset_class_name='new' prefix="new" %}
</div>
</table>
<table class="table">
{{ formset_renewal.management_form }}
<div>
<br><h4><strong>Renewals</strong></h4><br>
{% include "reports/formsets.html" with formset=formset_renewal formset_class_name='renewal' prefix="renewal" %}
</div>
</table>
</div>
</form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="{% static 'js/jquery.formset.js' %}"></script>
<br>
<div class="container">
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal"><strong>Submit</strong></button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Before You Submit!!</h4>
</div>
<div class="modal-body">
<p>Please review and make sure that all line items are correct and that the <strong>"Check if No New Items"</strong> is checked if there are no new items for that catagory. If all is correct, please select the <strong>Save and Email</strong> button.</p>
</div>
<div class="modal-footer">
<input type="submit" form="formset" class="btn btn-primary" value="Save and Email to Corporate"><!--added form id, form="formset" , to input element-->
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
Hopefully this will help others who use SO as a research tool.

Related

Broken modal in flask

on my page I do cms for individual chapters that I have in the menu and on the page and I want new ones to be added and those that already exist so that they can be edited. I'm just doing it via jquery and bootstrap modal dialog but it doesn't want to work every time I click edit so my modal dialog doesn't appear and I get a 404 error. When adding chapters, nothing appears there at all, no error, no message or nothing in debug mode. I need help with that. Thank you in advance for your help.
PS: Deleting chapters works for me
HTML Code (updated):
{% extends "base.html" %} {% block content %}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>
{%if session["group"] == "Admin"%}
<div class="container">
<div class="row">
<div class="col md-12">
<h2>Kapitoly</h2>
<button type="button" class="btn btn-success pull-right" data-toggle="modal" data-target="#myModal">Přidat kapitolu</button>
<br>
<br>
{%with messages = get_flashed_messages()%}
{%if messages%}
{% for message in messages %}
<div class="alert alert-success alert-dismissable" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label ="close">
<span aria-hidden="true">×</span>
</button>
{{message}}
</div>
{%endfor%}
{%endif%}
{%endwith%}
<table class="table table-striped">
<tr>
<th>ID</th>
<th>Ročník</th>
<th>Název</th>
<th>Akce</th>
</tr>
{% for row in chapters %}
<tr>
<td>{{row.0}}</td>
<td>{{row.1}}</td>
<td>{{row.2}}</td>
<td>
<a type="button" class="btn btn-primary" data-toggle="modal" data-target="#modaledit{{row.0}}">Upravit</a>
Smazat
</td>
</tr>
<div id="modaledit{{row.0}}" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Upravit kapitolu</h4>
</div>
<div class="modal-body">
<form action="{{ url_for('update') }}" method="POST">
<div class="form-group">
<label>Ročník:</label>
<input type="hidden" name="id" value="{{row.0}}">
<input type="text" class="form-control" name="year" value="{{row.1}}">
</div>
<div class="form-group">
<label>Název:</label>
<input type="text" class="form-control" name="title" value="{{row.2}}">
</div>
<div class="form-group">
<button class="btn btn-primary" type="sbumit">Upravit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<div class="back">
Vrátit se zpátky.
</div>
</div>
</div>
</div>
{% endfor %}
</table>
</div>
</div>
<!-- Modal -->
<div id="mymodal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Vytvořit kapitolu</h4>
</div>
<div class="modal-body">
<form action = "/add_chapter" method="POST">
<div class="form-group">
<label>Ročník:</label>
<input type="text" class="form-control" name="year" required="1">
</div>
<div class="form-group">
<label>Název:</label>
<input type="text" class="form-control" name="title" required="1">
</div>
<div class="form-group">
<button class="btn btn-primary" type="submit">Vytvořit</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
{%endif%}
Flask code (updated):
#app.route("/manager_chapter")
#isLoggedIn
def manager_chapter():
cur = mysql.connection.cursor()
cur.execute("SELECT * FROM chapters")
data = cur.fetchall()
cur.close()
return render_template('manager_chapter.html', chapters=data, id_data=id)
#app.route("/add_chapter", methods=["POST"])
#isLoggedIn
def add_chapter():
if request.method == "POST":
flash("Kapitola je uspěšně přidaná.")
year = request.form['name']
title = request.form['email']
cur = mysql.connection.cursor()
cur.execute("INSERT INTO chapters (year, title) VALUES (%s, %s)", (year, title))
mysql.connection.commit()
return render_template('manager_chapter.html')
#app.route('/update_chapter/<string:id_data>', methods=['POST','GET'])
#isLoggedIn
def update(id_data):
if request.method == 'POST':
id_data = request.form['id']
year = request.form['year']
title = request.form['title']
cur = mysql.connection.cursor()
cur.execute("""
UPDATE chapters
SET year=%s, title=%s
WHERE id=%s
""", (year, title, id_data))
flash("Kapitola je uspěšně upravená.")
mysql.connection.commit()
return redirect(url_for('manager_chapter'))
#app.route('/delete_chapter/<string:id_data>', methods=['GET'])
def delete(id_data):
flash("Kapitola je uspěšně smazána.")
cur = mysql.connection.cursor()
cur.execute("DELETE FROM `chapters` WHERE id=%s", (id_data,))
mysql.connection.commit()
return render_template('manager_chapter.html')
Example 404 error after clicking edit in one of the chapters:
Next time, please translate your source code before posting it, if you are posting to English speakers. Based on your comments, I'm going to assume your edit button is this one
Upravit
You have both an href and data-target attribute. The latter is for the modal dialog. I don't believe you can have both and have them point to different urls. According to [bootstrap][1] documentation, you should use the href link and its value should be the id of your modal target. So I think your code should be
Upravit
or
<a type="button" class="btn btn-primary" data-toggle="modal" data-target="#modaledit{{row.0}}">Upravit</a>
If we assume your modal is not being triggered because it is being seen as a straight hyperlink and so the url in the href is being triggered, it opens up a second problem. Your flask route for that url has code only for a POST. You need to add code for the GET bit. In addition, your route has a variable for id_data but that variable is not part of your route i.e. you should have
#app.route('/update_chapter/<string:id_data>', methods=['POST','GET'])
#isLoggedIn
def update(id_data):
UPDATES - Based on comments by OP
Your button code now calls the modal.
The modal has a form and the form has a hidden field for the chapter id. Based on this, your route should now be
#app.route('/update_chapter', methods=['POST'])
#isLoggedIn
def update():
if request.method == 'POST':
id_data = request.values.get("id", None)
# I prefer to use request.values.get so that I don't
# have to worry about if my method is a POST or GET
[1]: https://getbootstrap.com/docs/4.1/components/modal/

Form Fields Not Fitting Bootstrap Modal

I am trying to implement a bootstrap modal form in my Django project. When I do this, everything works except the fields are running much wider than the modal window and seem strangely offset. I feel like there's an easy fix here but I can't determine exactly what I'm doing wrong. Here is my html for the modal form:
modal.html
<form method="post" action="">
{% csrf_token %}
<div class="modal-header">
<h5 class="modal-title">Create new Book</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
{{form.Reference_Number|as_crispy_field}}
{{form.Ultimate_Consignee|as_crispy_field}}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="submit-btn btn btn-primary">Create</button>
</div>
</form>
Try placing each crispy form field inside a Bootstrap form-group <div> container. Like this:
<div class="modal-body">
<div class="form-group">
{{form.Reference_Number|as_crispy_field}}
</div>
<div class="form-group">
{{form.Ultimate_Consignee|as_crispy_field}}
</div>
</div>
More on info on Bootstrap forms here

How to catch the displayed image ID in Laravel

I'm displaying a images from the database and i need to catch the image id from the controller .I'm trying to save image ID to Database
This is the image tag with contain image id
What we need to do is : When the user click the one of image and submit need to catch that selected id from the controller
$kudos->receiveuserid = $request->get('categories');
$kudos->imageid = 'how can i get image ID'
Try something like this and customize according to your requirement
#foreach($categories as $category)
<div>
<img src="{{$category->image}}" class="imgRating">
<input type="radio" value="{{$category->id}}" class="imgId" name="imageid">
</div>
#endforeach
Now in write a little jQuery
$(".imgRating").click(function(){
$(this).parent().find(".imgId").prop( "checked", true );
});
Finally, add CSS
.imgId{
display:none !important;
}
Now in your controller you will get the selected image id by $request->imageid
try this it should work. the idea here is that when you click on the image, the javascript function gets the id and assign it to a modal form then you submit. you can modify it to suit your preference.
<!-- modal to get image id store it in hidden field-->
<div id="imgModal" class="modal fade" >
<div class="modal-dialog box box-default" role="document" style="color:black;font-size:12.5px;">
<div class="modal-content">
<div class="modal-header">
<p class="modal-title">Image Form</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form class="form-horizontal" action="{{ url('img/addid/') }}" method="post" role="form">
{{ csrf_field() }}
<div class="modal-body">
<div class="form-group" style="margin: 0 10px;">
<input type="hidden" class="form-control" id="imgid" name="imgid" value="">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary btn-xs">Submit</button>
<button type="button" class="btn btn-danger btn-xs" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
<!-- display image code-->
<div class="col-sm-3">
<div class="form-group">
#foreach($category as $category)
<a onclick="imgfunc('{{ $category->id}}')"><img class="boxicon" src="{{ asset('kudosupload/badges/'. $category->image)}}" name="img" ></a>
<br>
#endforeach
</div>
</div>
<!-- javascript to get image id when click on image-->
<script type="text/javascript">
function imgfunc(r)
{
document.getElementById('imgid').value = r;
$("#imgModal").modal('show')
}
</script>
//controller to get input and store in database
public function saveImage(Request $request){
$this->validate($request, [
'imgid' => 'required|string',
]);
$imgid=$request->input('imgid');
$datasave=DB::table('imgtable')->insert([
'id'=>imgid,
]);
return redirect('url')->with('message','Image saved!');
}
//route
Route::post('img/addid','controller#saveImage');

form not rendering correctly in modal

I try to render a form with ajax and show it in a modal.
But the fom tags in the modal just appears next to eachother when i check the source code in my browser. How can I resolve this?
Here is my written code of the modal in:
<!-- Modal Edit client -->
<div id="editClient" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">&times</button>
<h4 class="modal-title">Edit Client</h4>
</div>
<div class="modal-body">
<form id="editClientForm" action="{{ path('client_details') }}" method="POST">
{{ form_widget(form) }}
<br />
<input type="submit" class="btn btn-success" value="Save changes">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</form>
</div>
</div>
</div>
</div>
The modal opens with the form fields and closes when cancel is clicked.
Here is the source code from the browser:
<div class="modal-body">
<form id="editClientForm" action="/ruben/avr_symfony/web/app_dev.php/configurator/client/details" method="POST"></form>
=> here comes all the form fields and buttons.
</div>
As you can see, it closes the form tag before putting in the form fields.
I found the problem.
I hade a closing table tag wich i typed as < table > instead of < / table > in my code above the modal code.
This solved the issue.

can't set html form input file from modal / popover

I have an html form. For the image file input, I have a modal that pops up to set the input field but also allow the user to crop. When I submit the form, it says the input field is empty.
Here is the form with modal embedded:
<form class="form-horizontal" role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<h5>First Name</h5>
<div class="form-group">
{{ form.first_name|attr:"class:form-control"|attr:"placeholder:Enter Your First Name" }}
</div>
<h5>Profile Image (Square Image)</h5>
<div class="form-group">
<button data-toggle="tk-modal-demo" data-modal-options="slide-down" class="btn btn-primary">Upload</button>
</div>
{{ form.crop_coords }}
<!-- Create the modal dynamically via Handlebars -->
<script id="tk-modal-demo" type="text/x-handlebars-template">
<div class="modal fade" >
<div class="modal-dialog">
<div class="v-cell">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Upload Profile Image</h4>
</div>
<div class="modal-body container">
<div class="max-width: 560px;">
<div>
<img style="max-width: 100%;" id="tempImg" src="{% static 'app/images/default-team-large.jpg' %}"/>
<h5>Profile Image (Square Image)</h5>
<div class="form-group">
<input id="id_profile_image2" type="file" name="pic" accept="image/*">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
</div>
</script>
<div class="form-group margin-none">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-sm btn-primary" href="nml-home.html"> Confirm User Changes<i class="fa fa-fw fa-arrow-right"></i></button>
</div>
</div>
</form>
To test, I click the data-toggle button to popup the modal. It then opens the tk-modal-demo which has a file upload. I upload an image and then I click the save button in tk-modal-demo to dismiss the modal. Then I submit the form with the bottom form submit button. My validator says that the field is empty.
How can I set this required form field from the modal and have it populated when I submit?
It might be that the modal input elements are not created inside the <form> element. Input elements outside of this container will not be sent to the server upon submit.
You can first check out what is actually transmitted with the development console of your browser (in Chrome it's the Network tab). If your fields aren't there, then you might need to write a bit of Javascript, to either:
copy the contents of the input elements inside the modal to hidden fields within the form, for using the regular submission process
or, hijack the submit event and manually compose which fields you want to send