AJAX feedback form using django crispy forms in Bootstrap Modal - ajax

There are quite a few moving parts to this question, but if you have any insight to any piece of it, it would be appreciated.
I want to build a feedback form that acts as one would expect. When the user clicks the feedback button at the bottom right of the page, it launches a bootstrap modal. The modal has a django crispy form that submits or returns the fields that are invalid when the submit button is pressed.
First, I have my feedback button:
{% load crispy_forms_tags %}
.feedback-button {
position: fixed;
bottom: 0;
right: 30px;
}
<div class='feedback-button'>
<a class="btn btn-info" href="#feedbackModal" data-toggle="modal" title="Leave feedback" target="_blank">
<i class="icon-comment icon-white"></i>
Leave feedback
</a>
</div>
<div class="modal hide" id="feedbackModal" tabindex="-1" role="dialog" aria-labelledby="feedbackModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="feedbackModalLabel">Contact Form</h3>
</div>
<div class="modal-body">
{% crispy feedback_form feedback_form.helper %}
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Submit</button>
</div>
</div>
Next, I have my form:
class Feedback(models.Model):
creation_date = models.DateTimeField("Creation Date", default=datetime.now)
topic = models.CharField("Topic", choices = TOPIC_CHOICES, max_length=50)
subject = models.CharField("Subject", max_length=100)
message = models.TextField("Message", blank=True)
sender = models.CharField("Sender", max_length=50, blank=True, null=True)
def __unicode__(self):
return "%s - %s" % (self.subject, self.creation_date)
class Meta:
ordering = ["creation_date"]
verbose_name = "Feedback"
verbose_name_plural = "Feedback"
class Crispy_ContactForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.layout = Layout(
Fieldset(
Field('topic', placeholder='Topic', css_class='input-medium'),
Field('subject', placeholder='Subject', css_class='input-xlarge'),
Field('message', placeholder='Message', rows='5', css_class='input-xlarge'),
Field('sender', placeholder='Sender', css_class='input-xlarge'),
),
)
self.helper.form_id = 'id-Crispy_ContactForm'
self.helper.form_method = 'post'
super(Crispy_ContactForm, self).__init__(*args, **kwargs)
class Meta:
model = Feedback
exclude = ['creation_date']
I tried to omit the legend in the crispy form because if I include it, the modal appears to have two form titles. But omitting the legend in the crispy form layout resulted in the fields appearing out of order.
So I'm left with a few questions:
Overall, am I going about this the right way?
If I hook up the modal's submit button to AJAX, how do I go about error checking the
form?
Is there a better way to display the crispy form in the
bootstrap modal?

I found a partial solution on this page. In my base template, I created the button and the form:
<div class='feedback-button'><a class="btn btn-info" href="#feedbackModal" data-toggle="modal" title="Leave feedback" target="_blank"><i class="icon-comment icon-white"></i> Leave feedback</a></div>
{% include "_feedback_form.html" with feedback_form=feedback_form %}
Then I created two feedback forms
<div class="modal hide" id="feedbackModal" tabindex="-1" role="dialog" aria-labelledby="feedbackModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
<h3 id="feedbackModalLabel">Contact Form</h3>
</div>
{% include "_feedback_form_two.html" with feedback_form=feedback_form %}
</div>
and
{% load crispy_forms_tags %}
<form action="{% url feedback %}" method="post" id="id-Crispy_ContactForm" class="form ajax" data-replace="#id-Crispy_ContactForm">
<div class="modal-body">
{% crispy feedback_form %}
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<input type="submit" name="submit_feedback" value="Submit" class="btn btn-primary" id="submit-id-submit_feedback" />
</div>
</form>
I broke the feedback forms into two because the bootstrap-ajax.js file that I'm leveraging from the above link replaces the html from the one template. If I use a combined feedback form, it will have class="modal hide". I need it to just have class="modal" so that if the form is refreshing with errors, the modal doesn't disappear.
In my view, I have
#login_required
def feedback_ajax(request):
feedback_form = Crispy_ContactForm(request.POST)
dismiss_modal = False
if feedback_form.is_valid():
message = feedback_form.save()
feedback_form = Crispy_ContactForm()
dismiss_modal = True
data = {
"html": render_to_string("_feedback_form_two.html", {
"feedback_form": feedback_form
}, context_instance=RequestContext(request)),
"dismiss_modal": dismiss_modal
}
return HttpResponse(json.dumps(data), mimetype="application/json")
And then in the bootstrap-ajax.js file (again from the above link), I made a few alterations. In the processData function, I defined:
var $el_parent = $el.parent();
and I added
if (data.dismiss_modal) {
var msg = '<div class="alert alert-success" id="' + $(replace_selector).attr('id') + '">Feedback Submitted</div>'
$(replace_selector).replaceWith(msg);
$el_parent.modal('hide');
$(replace_selector).replaceWith(data.html);
}
This isn't fully functional yet because the Success Message disappears with the modal immediately. I want the modal to display the message and disappear after maybe 3 seconds. haven't figured this out yet, but it works well enough for now.
I'm still tinkering, but this addresses most of my questions:
It submits data with AJAX and returns with error checking if needed.
The form displays fairly well in the modal.
I have a few remaining issues. I need to figure out a way to suppress the legend in the crispy form, and I need to find a way to display the modal crispy form and not interfere with another crispy form that appears elsewhere on the site.

I answered a similar question to this on a related question.
https://stackoverflow.com/a/12905016/1406860
This will get you everything except the return of errors.
I would suggest doing the validation and creating an 'errors': 'List of problems' entry in the dictionary that is fed back and check for this in the AJAX success as per whether to close the modal (because there weren't errors) or displaying errors as appropriate.
JD

Related

How to POST an object to controller

I'm having a difficulty passing my 'product' object to the controller. How can I do it? I'm not getting errors. The problem is that the 'product' object is null on my controller.
html:
<section th:each="menu : ${allMenus}">
<button
<h1 th:text="${menu.name}"></h1>
</button>
<div>
<div th:each="product : ${menu.productList}">
<a data-toggle="modal" th:href="'#' + ${product.name} + 'Modal'">
h5 th:text="${product.name}"></h5>
<small th:text="${product.price} + '$'"></small>
<p th:text="${product.description}"></p>
</a>
<div th:replace="/productModal :: productModal(product=${product})"></div>
</div>
</section>
Modal:
<div th:fragment="productModal(product)">
<div role="document">
<form method="post" th:action="#{/addItemToCart}">
<div th:each="topping : ${product.toppings}">
<input type="checkbox" th:id="${topping} + ${product.id}" name="checkedToppings" th:value="${topping}" />
<label th:for="${topping} + ${product.id}" th:text="${topping}"></label>
</div>
<div>
<button type="submit">Add to Shopping Cart</button>
</div>
</form>
</div>
</div>
controller:
#RequestMapping(value="/addItemToCart", method=RequestMethod.POST)
public String addItemToCart(#ModelAttribute("product") Product product, #RequestParam("checkedToppings") List<String> toppings)
{
//product is null;
//checkedToppings are retrieved correctly
return "redirect:/menu";
}
Short answer:
you don't post objects to controllers using HTML.
Details:
You will never be able to post a "product" object to your controller from an HTML page.
Instead,
you should send identifying information about the desired "product" to the controller,
perhaps a product-id or some other product-unique-identity-blammy.
Response to options in comments:
Hackers love hidden fields and JavaScript;
I recommend against using those for this situation.
I believe that you only have one option: identifying info.
This does not need to be a "real" product number.
You can generate a UUID and store a map in the choose one: (Servlet Session, Database, Application Session, somewhere else on the server) that maps from the UUID to the desired product.

Dropzone opens file chooser twice

I have set up dropzone with a clickable element. Clicking the button causes dropzone to open the file chooser twice, instead of just once, the second coming immediately after the first file has been chosen.
The init code is:
Dropzone.autoDiscover = false;
$(document).ready(function(){
// Remove the template from the document.
var previewNode = document.querySelector("#template");
previewNode.id = "";
var previewTemplate = previewNode.parentNode.innerHTML;
previewNode.parentNode.removeChild(previewNode);
$("div#photo").dropzone({
url: "/blackhole/",
thumbnailWidth: 240,
thumbnailHeight: 240,
parallelUploads: 1,
maxFiles:1,
maxFilesize: 5,
uploadMultiple: false,
previewTemplate: previewTemplate,
autoProcessQueue: true,
previewsContainer: "#photoPreview",
clickable: ".fileinput-button",
init: function() {
this.on("maxfilesexceeded", function(file) {
this.removeAllFiles();
this.addFile(file);
});
}
});
And the page elements are:
<div class="table table-striped" class="files">
<div id="photo">
<div id="actions" class="row">
<div class="col-lg-7">
<button type="button" class="btn btn-success fileinput-button">
<i class="glyphicon glyphicon-plus"></i>
<span>Choose file...</span>
</button>
</div>
</div>
</div>
<div class="files dropzone-previews" id="photoPreview">
<div id="template" class="file-row">
<div>
<span class="preview"><img data-dz-thumbnail /></span>
</div>
<div>
<p class="name" data-dz-name></p>
<strong class="error text-danger" data-dz-errormessage></strong>
</div>
<div>
<p class="size" data-dz-size></p>
<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">
<div class="progress-bar progress-bar-success" style="width:0%;" data-dz-uploadprogress></div>
</div>
</div>
<div>
<button data-dz-remove type="button" class="btn btn-warning cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel</span>
</button>
</div>
</div>
</div>
</div>
</div>
Strangely, even though I have added code to replace the any existing file with a later one (so only one file can be uploaded), the second file chooser dialog lets me add a second file.
Its like dropzone has been initialized twice, but I checked that it is only initialized once, and also added the autoDiscover = false option for good measure.
Can anyone spot my mistake?
The problem seems to be in how we initialized dropzone:
$("div#photo").dropzone({
...
}
Doing it the non-jquery way solved the problem:
var myDropZone = new Dropzone("#photo",{
...
}
This was on dropzone 3.11.1.
An issue has been created on github/dropzone:
https://github.com/enyo/dropzone/issues/771
This happens for me when more than one dropzone exists on the page with the same class for a browse trigger, it seems that dropzone attaches the event to any element on the page and not just within its own container
In the issue opened for this, maliayas said:
This bug happens when your clickable element is already an
input[type=file]. Dropzone injects another one and now you have two.
Either dropzone should handle this case or documentation should
mention not to use an input[type=file] for the clickable element.
Changing my dropzone element to something other than an input[type=file] fixed the issue for me.
Attach dropzone to the parent, not the input.
In Chrome if you inspect and look at the eventListeners. You will see that once you attach dropzone to your input, you have an additional click eventListener.
Say you have a list of uploads for documents with a child input element.
<li class="upload drag-and-drop">
<input type="file"/>
</li>
Code:
$('input').dropzone();
Will attach an event listener to an already clickable element. So you have 2 event listeners. One from the browser. One from dropzone. Hence 2 dialogs...
If you attach it to the parent:
$('li.upload').dropzone();
You'll now had the listener at the parent. This allows the bubble up behavior to hit the correct element when you drag and drop and not inadvertently effect the input.

EmberJs {{ action }} helper in a view doesn't work

I'm trying to add bootstrap modals in my ember app. I'd like to be able to add modals, with a specified template and be able to handle actions. I can't get it works. The modal appears, my controller's properties are bound, but i can't handle actions. I don't understand why. I'd really like to be able to trigger modal from anywhere in my controllers and bind actions on them.
My view looks like this:
App.ModalView = Ember.View.extend({
classNames: ['modal fade'],
attributeBindings: ['role'],
role: 'dialog',
didInsertElement: function() {
this._super();
this.$().modal();
this.$().on('hidden.bs.modal', this.close.bind(this));
},
close: function(event) {
return this.destroy();
}
});
And i instanciate it like this in a random controller:
var modal = controller.container.lookup('view:modal');
modal.reopen({
controller: this,
targetObject: this,
templateName: 'mymodal'
});
return modal.appendTo('body');
My template looks like this:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">My Modal Title</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
My modal content
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" data-dismiss="modal" class="btn default">Close</button>
<button type="button" class="btn green" {{ action "myaction"}}>My Button with an action</button>
</div>
</div>
</div>
If i try to display some controller properties, it works. But when i click on the button with the "myaction" action nothing happends. Maybe i'm completely wrong about the way to handle modals in my app (i'm pretty new in the Ember's World).
I'm using the last release of ember (1.1.1) and bootstrap 3.
Thanks,
Vinc
I figured it out. In fact, my app was running into a specific dom element (#app). As i was adding the view to the body, my modale was added "outside" my app ! So, the events bubbling chain was broken. Instead of adding my view to the body, i add it to my application root element and now everything works as expected !
There's a good chance that the modal method is disconnecting it from the body, which would break your actions.
See also: Ember.js and Foundation 4 modal window
You shouldn't access view like this
var modal = controller.container.lookup('view:modal');
See Wycats comment here.
Alternatively, This answer may help you in instantiating modals

Angular UI Bootstrap - I can open and close a modal just once

I have a weird problem with a modal. It should be a absolutely normal modal that I can open and close many times, but I can open just one and also just close one time! http://plnkr.co/ksTy0HdifAJDhDf4jcNr
My index.html file looks this:
<body ng-controller="MainCtrl">
<div ng-include src="'widget.html'" ng-controller="WidgetCtrl"></div>
<!-- other widgets and content -->
</body>
As you can see I have devided my application in different parts (called widgets), that I am including per ng-include in my index html file. Every widget has it's own controller.
The widget.html looks like this:
<div modal="theModal">
<div class="modal-header"><h3>The Modal</h3></div>
<div class="modal-body">
Body intentionally left blank
</div>
<div class="modal-footer">
<button class="btn" type="button" ng-click="CloseModal()">ok</button>
</div>
</div>
<!-- more modals and other stuff -->
<button ng-click="OpenModal()">open modal</button>
And now the widget controller (which is a child controller of the main controller)
app.controller('WidgetCtrl', function ($scope) {
$scope.OpenModal = function() { $scope.theModal = true; }
$scope.CloseModal = function() { $scope.theModal = false;}
});
All stuff for opening and closing the modal is part of the sub controller (WidgetCtrl) and therefore shouldn't conflict with anything from the parent controller.
$scope.theModal is in the beginning undefined, so the modal is not shown. With a click on the button $scope.theModal is defined and set to true; this is triggered by Angular UI and the modal is shown. On a click of ok, the now existing $scope.theModal is set to false and the modal disappears. Everything is perfect but .. it's not working again!
You just have to include close="CloseModal()" in the first div of your widget
<div modal="theModal" close="CloseModal()">
<div class="modal-header"><h3>The Modal</h3></div>
<div class="modal-body">
Body intentionally left blank
</div>
<div class="modal-footer">
<button class="btn" type="button" ng-click="CloseModal()">ok</button>
</div>
</div>
Here is a working plunker

ajax script onclick alert to popup message box

I found this voting script online and was wondering instead of a onclick alert(You already voted) can i change it to a popup message that i can style with css... i have only submitted a part of the code if you need to see more let me know. thanks in advance
function addVotData(elm_id, vote, nvotes, renot) {
// exists elm_id stored in ivotings
if(ivotings[elm_id]) {
// sets to add "onclick" for vote up (plus), if renot is 0
var clik_up = (renot == 0) ? ' onclick="addVote(this, 1)"' : ' onclick="<a type="button" class="btn" style="width:100%;" href="#test_modal" data-toggle="modal">alert</a>"';
// if vot_plus, add code with <img> 'votplus', else, if vot_updown1/2, add code with <img> 'votup', 'votdown'
if(ivotings[elm_id].className == 'vot_plus') { // simple vote
ivotings[elm_id].innerHTML = '<h6>'+ vote+ '</h6><span><img src="'+votingfiles+'arrow.png" alt="1" title="vote"'+ clik_up+ '/></span>';
};
}
}
You can use Bootstrap modal pop up instead of alert.
This is well explained example
If you need more help let me know
Update
html for model pop up:
<div class="modal fade" id="test_modal"> <div class="modal-header">
<a class="close" data-dismiss="modal">×</a> <h3>Modal Header</h3> </div>
<div class="modal-body"> <p>Test Alert</p> </div> <div class="modal-footer">
Close </div> </div>
Html for Button
<input type="Button" Text="ShowModal" Id="MyButton"/>
javaScript:
$( "#MyButton" ).click(function() {
$('#modalName').modal('show');
});

Resources