symfony 2.3 passing path id to checkbox form in modal - javascript

I have a problem that has been bugging me for days now, and I know it might be trivial for some but please bear with me. In my twig I have an href that reveals a modal with a checkbox, the href also contains a path to an action in my controller
Twig
Action in Controller
/**
*
* #Route("/{id}/delete", name="delete_image")
*/
public function deleteAction(Request $request, CategoryImage $CategoryImage, $id)
{
$em = $this->getDoctrine()->getManager();
$CategoryImage = $em->getRepository('AcmeBundle:entity')->find($CategoryImage->getId());
$em->remove($repo);
$em->flush();
return $this->redirect($this->generateUrl('page_main', array("id"=>$id)));
}
Modal
<div id="deleteModal" class="reveal-modal large">
<h6>Delete Image</h6>
<br/>
{{form_start(DeleteImageForm, {'attr': {'id': 'DeleteImageForm'}})}}
Delete Image
{{form_widget(DeleteImageForm.remove)}}
{{form_errors(DeleteImageForm.remove)}}<br/><br/>
admin password <br/>
<input type="password" id="DeletePass"/>
<br/>
<button id = "Delete">Submit</button>
{{form_end(DeleteImageForm)}}
<a class="close-reveal-modal">×</a>
</div>
Jquery
$('#Delete').on('click', function(e){
var data = $(this).serialize();
if ($('#DeletePass').val() == 'password'){
$( "#DeleteImageForm" ).submit();
}else{
alert('invalid password');
e.preventDefault();
}
});
Is there any way to pass the id / value of the path to the modal so when checkbox is checked and is submitted it goes to the action?
Any help would be much appreciated.

Generate your delete form in twig, by passing a placeholder for the dynamic parameter i.e id. You can do it in controller where you generate the deleteForm.
The idea is to have a unique identifier in action so that we can replace via jQuery.
return $this->createFormBuilder()
->setAction($this->generateUrl('image_delete', array('id' => 'image_id')))
->setMethod('DELETE')
->getForm()
;
Now, when your modal gets open, Through jQuery, replace the placeholder i.e image_id to your required value, , as below :
var currentUrl = jQuery("form#DeleteImageForm").attr('action');
// suppose 154 is your new image id.
var newHref = currentUrl.replace('image_id', '154');
// change url of the form action.
jQuery("form#DeleteImageForm").attr('href', newHref);
Hope this helps.
Note : The code is not tested!

Related

Getting data from a current HTML, PHP form using JavaScript

I have a HTML/PHP sale form which I take in all the details of a sale(products, price etc.).
When I "hold" the sale I then pass the id of the sale, using PHP like the following:
<button type="submit" class="btn btn-primary pull-right btnPrintOrder" saleCode="<?php echo $code; ?>" value="hold" name="openTable">Hold</button>
The desired end result is it is supposed to set off a function to print out the sale details to seperate printers(bar/restaurant).
The print function works as I have tested it against older sales already saved to the database.
My problem is it is not registering the details of the current sale and the receipts are blank.
I have tried to put a delay on it to see could it pick the details up after they have been saved to the database but I'm not having any luck.
The function the button passes to is:
$(".saleForm").on("click", ".btnPrintOrder", function(){
var saleCode = $(this).attr("saleCode");
// setTimeout(food(saleCode), 50000);
// setTimeout(drink(saleCode), 50000);
window.open('extensions/tcpdf/pdf/food_order.php?code='+saleCode);
window.open('extensions/tcpdf/pdf/drink_order.php?code='+saleCode);
})
And the PHP code calling the details in drink_order.php is:
public function getDrinkReceiptPrinting(){
// Sale Info
$itemSale = "code";
$saleValue = $this->code;
$saleAnswer = OpenTableController::ShowTableController($itemSale, $saleValue);
$saledate = substr($saleAnswer["date"],0,-8);
$products = json_decode($saleAnswer["products"], true);
$findCategory = 2;
$catProducts = array_filter($products, function ($product) use ($findCategory) {
return $product['category'] == $findCategory;
});
$netPrice = number_format($saleAnswer["netPrice"],2);
//User Info
$itemUser = "id";
$userValue = $saleAnswer["idSeller"];
$userAnswer = UserController::ShowUsersController($itemUser, $userValue);
Any ideas would be great.
Change the PHP button attribute to this:
<button type="submit" class="btn btn-primary pull-right btnPrintOrder" data-sale-code="<?php echo $code; ?>" value="hold" name="openTable">Hold</button>
use data attribute (dataset attribute), since saleData is not standard attribute, and inside jQuery use .data() to get the value (note how to get it in jQuery):
$(".saleForm").on("click", ".btnPrintOrder", function(){
var saleCode = $(this).data("sale-code");
// setTimeout(food(saleCode), 50000);
// setTimeout(drink(saleCode), 50000);
window.open('extensions/tcpdf/pdf/food_order.php?code='+saleCode);
window.open('extensions/tcpdf/pdf/drink_order.php?code='+saleCode);
})

Viewing values in modal box/pop up - HTML, JavaScript, PHP and JavaScript

I've been trying to retrieve the data from MySQL database in order to display it on a modal/pop-up box in javascript. Here's my current progress:
When you click the "View Images" Button
Here's my snippet code for modal pop up box:
HTML
This html Trigger button will get the Report_ID in its button attribute id to pass it to javascript.
" onclick="showDetails(this);">View Images
<!-- Modal -->
<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-header">
<button type = "button" class = "close" data-dismiss = "modal" aria-hidden = "true">
×
</button>
<h4 class = "modal-title" id = "myModalLabel">
Images of the Report
</h4>
</div>
<div class = "modal-body">
<p>Original Image: <span id = "Orig_Image"></span></p>
<p>RGB Image: <span id = "RGB_Image"></span></p>
<!--<img src="smiley.gif" alt="Smiley face" height="200" width="200">-->
</div>
<!-- <div class = "modal-footer">
<button type = "button" class = "btn btn-default" data-dismiss = "modal">
Close
</button>
<button type = "button" class = "btn btn-primary">
Submit changes
</button>-->
</div>
</div>
</div>
JAVASCRIPT
This javascript code willl be the one to get the Report_ID from the html table. Report_ID will be the identifier in MySQL Query and will be used in the php script Retrieve_Image.php using GET method. If the retrieval of the data is success the javascript will pass the values in to the html with their corresponding ids (ex. ).
function showDetails(button){
var Report_ID = button.id;
}
$.ajax({
url: "Retrieve_Image.php",
method: "GET",
data: ("Report_ID": Report_ID),
success: function(response){
//alert(response);
var Images = JSON.parse(response);
$("#Orig_Image").text(Images.Original_Image_Directory);
$("#RGB_Image").text(Images.RGB_Image_Directory);
$("#myModalLabel").text(Images.Image_Name);
}
error: function(e){
alert('Error: '+e);
}
});
PHP
This script / php code will retrieve the images data and will return its retrieved values to javascript using json encode.
<?php
session_start();
include_once ("../System_Connector.php");
include_once ("Admin_Session_Checker.php");
$Report_ID = $_GET["Report_ID"];
$Retrieve_Report = "SELECT Image_Name,Original_Image_Directory,RGB_Image_Directory FROM Report_Image WHERE Report_ID = $Report_ID";
$Retrieval_Image_Query = mysqli_query($Connection, $Retrieve_Report);
if(!$Retrieval_Image_Query){
echo "<script type = 'text/javascript'> alert('Error: Could not retrieve data from database because of this error: '".mysqli_error($Connection)."') </script>";
}
$Report_Result = mysqli_fetch_object($Retrieval_Image_Query);
echo json_encode($Report_Result);
?>
PROBLEM
It does not returning any data from php script. I tried to run the php script by putting a value on $_GET["Report_ID"]; and it doesn't have a problem. I think the problem is on the trigger button, where it gets the Report_ID using button id. How can i find and fix the problem? All I want is to display the text values first for Original Image and RGB Image.
Example of what I'm trying to achieve (Output goal):
P.S. I used the bootstrap Modal Box: https://www.tutorialspoint.com/bootstrap/bootstrap_modal_plugin.htm
### add $.ajax inside showDetails ###
function showDetails(button){
var Report_ID = button.id;
$.ajax({
url: "Retrieve_Image.php",
method: "GET",
data: {"Report_ID": Report_ID},
success: function(response){
//alert(response);
var Images = JSON.parse(response);
$("#Orig_Image").text(Images.Original_Image_Directory);
$("#RGB_Image").text(Images.RGB_Image_Directory);
$("#myModalLabel").text(Images.Image_Name);
}
error: function(e){
alert('Error: '+e);
}
});
}
Place your ajax code inside showDetails function.

Remove query string on page reload

I have a hyperlink which i am redirecting to a page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/Merging/Index/?workItemID=' + id;
});
My action in the controller page is
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID==null? 0: workItemID.Value) ;
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
return View(mergingVM);
}
So what it does is when i click on the hyperlink it redirects me to the merging page.
After redirecting to Merge page, the drop down fills with id(selected in home page) and correspondingly triggers the button click.
My issue When i reload the merge page the value in the drop down doesn't get clear. I.e if i have redirected from home page to merge page , then the drop down has some value. but when i refreshes it the selected value should go. I understand that the query string still holds the value. But is there any alternative to send parameter to action without using windows.location.href in jquery.
If you are using hyperlink then also you can try it
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
$(this).attr('href','/Merging/Index/?workItemID=' + id)
});
In order to clean the query string you should use redirect to another view.
public ActionResult Index(int? workItemID)
{
MergingVM mergingVM = new MergingVM();
mergingVM.SourceList = GetSourceDropdownList();
mergingVM.WorkItem = (workItemID == null ? 0 : workItemID.Value);
mergingVM.MergeActionSelectList =
GetMergeProcessActionDropdownList();
PopulateDropDowns(mergingVM);
//to send this model to the redirected one.
TempData["model"] = mergingVM;
return RedirectToAction("CleanIndex");
}
public ActionResult CleanIndex()
{
var model = (MergingVM)TempData["model"] ?? new MergingVM();
// Do something
return View("Index", model);
}
To find alternatives to an send parameter to a method you first need to understand the model Bindding action.
The model bidding searches a value in:
Form Data
Route Data
Query String
Files
Custom (cookies for example)
If your action must need to be HttpGet you lose the Form Data which would be a nice alternative for you.
If I understand correctly... the below worked for me.
If there's an ID appended to the URL, it gets logged to the console as the variable "param". The URL is then replaced (so that if you refresh the page, the ID is removed from the URL).
$(document).ready(function() {
var url = window.location.toString;
var hostname = window.location.hostname;
var pathname = window.location.pathname;
var param = window.location.search;
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
window.location = '/new-page.php?' + id;
});
if ( pathname == "/new-page.php" && param ) {
console.log(param);
window.history.pushState("string", "Title", "http://yourURL.com/new-page.php");
//Do something with param...
}
});
This assumes that if there is no ID appended to the URL, the drop-down won't do anything. You also would need to update the URLs to the correct ones (I ran this on my local server).
I think you should use POST where you don't want to presist workItemID.
I mean all places where you have links you should use somethink like this:
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="1" /> <-- your Id
<input type="submit" value="Link to workItemID 1!" /> <-- your link
</form>
This way you will get your View but without workItemID in URL. But you should change css to make your POST link look like <a> tags.
Here is with your table:
#if (#Model.DataSetList[i].StateID == 43)
{
<td>
<form action="/Merging/Index" method="POST">
<input type="hidden" name="workItemID" value="#Model.DataSetList[i].Workitem_ID" />
<input class="lnkMerging" type="submit" value="Merging" />
</form>
</td>
}
else
{
<td>
<text style="color:darkgrey" contenteditable="false">Merging</text>
</td>
}
You can save the parameter in local storage api of html5, and then use those parameters in Page load of index page.
$('.lnkMerging').on("click", function () {
var id = $(this).attr('data-id');
localStorage.setItem("workItemID",id);
window.location = '/Merging/Index/;
});
On page load of index you can retrieve it using getItem
localStorage.getItem("workItemID"); and use it as per your requirement.
On page load of Merge page, you have to explicitly set the selected option like below and then remove the value from local storage.
$(document).ready(function(){
if(localStorage.getItem("workItemID")!=null){
$("#mydropdownlist").val(localStorage.getItem("workItemID"));
localStorage.removeItem('workItemID');
}
});
Make sure in var id = $(this).attr('data-id'); id should get same value as you have in the options on the merge page.

Closing an HTML form in a jQuery modal with the submit button

I have inherited the following HTML form in a jQuery modal:
<div id = "openModal" class = "modalDialog">
<div>
X
<form id = "write_us_form" action="" method = "post">
<div class = "form_container">
<label class = "form_label">Name</label>
<input type = "text" class = "form_textfield" name = "f_name"><br>
<label class = "form_label">E-mail</label>
<input type = "text" class = "form_textfield" name = "f_email"><br>
<label class = "form_label">Subject</label>
<input type = "text" class = "form_textfield" name = "f_subject"><br>
<label class = "form_label">Message</label>
<textarea class = "form_textarea" name = "f_message" rows = "5"></textarea>
<input type = "submit" class = "form_submit_button" value = "Send message">
</div>
</form>
</div>
</div>
When I click the submit button, the following jQuery script runs, apparently to not refresh the page and run the send_form.php file to send an email:
$(function ()
{
$('#write_us_form').on('submit', function (e)
{
e.preventDefault (); // prevent page reload
$.ajax (
{
type : 'POST', // hide URL
url : 'send_form.php', // form validation file
data : $('#write_us_form').serialize (),
success : function (data)
{
$('#openModal').dialog('close');
alert ('Thank you for contacting us!');
}
});
});
});
The code does not do two things:
1. Close the modal. I already added the dialog('close') part, but it does not have any effect.
2. If I close the modal with the close button, and then click the proper button on the website that displays the modal, the form still has the previous contents in it.
The php part works, the proper email is sent, I'm just trying to find a way to close the modal and possibly refresh the form when it is opened again.
Thanks for any bit of help!
Edit:
Your dialog box might not be closing if your ajax call is not successful. If your 'Thank you for contacting us' alert is being executed and your modal is still not closing, it could be an issue with your syntax. It could be the case, that your modal is a bootstrap modal in which case the syntax would be different. You would want to hide the modal.
In the case of the form contents, you want to reset the form in the success block. See your modified code below:
$('#write_us_form').on('submit', function (e)
{
e.preventDefault (); // prevent page reload
$.ajax (
{
type : 'POST', // hide URL
url : 'send_form.php', // form validation file
data : $('#write_us_form').serialize (),
success : function (data)
{
$('#openModal').modal('hide');
$("#write_us_form").trigger("reset");
alert ('Thank you for contacting us!');
}
});
});
});

User input not saved in model with Javascript

Building a site so users can add topics onto a site and ask then Q&A. Using AJAX, the "Add Media" button on the home page loads my Add Media Form (text and an image) to the site. The box is rendering fine with the correct forms, but after hitting Submit the form doesn't save in the database. When just rendering the form onto a new HTML page without jquery, the model works just fine and the input is saved. How do I get the information submitted in a jquery lightbox to be saved in the database too?
So this is the html page
#home.html
Add Media
<div id="login-box" class="addmovie-popup">
This is the jquery that goes with it
#home.js
$(document).ready(function() {
$('.block3 a').click(function(ev) {
ev.preventDefault();
var url = $(this).attr('href');
$('#login-box').load('http://127.0.0.1:8000/home/add_movie/');
});
});
The URL conf
#urls.py
url(r'^add_media/$', 'add_media'),
The view for adding media
#views.py
def add_media(request):
if request.method == "POST":
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save(user = request.user)
return HttpResponseRedirect("/home//")
else:
form = MediaForm()
return render_to_response("qanda/add_media.html", {'form': form}, context_instance = RequestContext(request))
And the HTML form that it is rendering
#add_media.html
<h1> Add Media:</h1>
<form enctype = "multipart/form-data" action = "" method = "post">{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "Add" />
<input type = "hidden" name = "next" value = "{{ next|escape }}" />
</form>
If you're loading HTML into your page dynamically action = "" would point to the current page, which clearly doesn't handle your POST requests.
Set the action to the correct URL.

Categories

Resources