symfony2 set a refresh button - symfony

Can i implement a refresh button in twig template that will reload my entity data on click ?
Here is my controller :
public function indexAction() {
$repositoryForHistory = $this->getDoctrine()->getManager()->getRepository("PagesBundle:histories");
$histories = $repositoryForHistory->findBy(Array(), Array('date' => 'DESC'));
return $this->render('PagesBundle:Default:index.html.twig', array(
'histories' => $histories));
}
}
And the div i want to reload :
<tbody>
{% for history in histories %}
<tr>
<td class="center" style="color: #ADADAD;">
<i class="fa fa-calendar-o"></i>
</td>
<td>
<span class="bold-text text-small">{{history.user}} {{history.action}} {{history.featureName}}</span>
</td>
<td class="center" style="color: #ADADAD;">{{history.date|date('d-m-Y H:i')}}</td>
</tr>
{% endfor %} </tbody>
<a class="panel-refresh" href="#"> <i class="fa fa-refresh"></i> <span>Refresh</span></a>

You can make an ajax request and send it by clicking on Refresh button, and on success just replace html of the element you want to update (actually there is no div in your template and I don't understand exactly what do you mean by div).
So, for this you have to create a special controller action which will return a poor html without layout.
It's the simplest way.
Also you can take a look at angularjs. But in some sense it might be a bit more complicated.

You need to do something with AJAX, so that when somebody clicks the 'refresh button' it makes an XMLHttpRequest to Symfony, which returns a response that contains only the <tr>s (not the wrapping table, or the <head>, etc).
In jQuery (you didn't say you were using it, but the JavaScript is more complicated to write):
$('.panel-refresh').click( function(event, ui) {
// prevents the browser following the click
event.preventDefault();
// replaces the contents of `<tbody>` with the response from the controller
$('tbody').load('/path/to/action');
}
and replace '/path/to/action' with the actual path to the action.

thank you guys #Alex and #Blowski here is the solution :
in my Controller
function reloadHistoryAction() {
$repositoryForHistory = $this->getDoctrine()->getManager()->getRepository("PagesBundle:histories");
$histories = $repositoryForHistory->findBy(Array(), Array('date' => 'DESC'));
$html="";
foreach ($histories as $history) {
$html .="<tr>
<td class='center' style='color: #ADADAD;'>
<i class='fa fa-tasks'></i>
</td>
<td>
<span class='bold-text text-small'>".$history->getUser()." ".$history->getAction()." ".
$history->getFeatureName()."
</span>
</td>
<td class='center' style='color: #ADADAD;'>
". $history->getDate()->format('d-m-Y H:i')."
</td>
</tr> ";
}
return new Response($html);
}
And in my twig template an ajax call to the controller action :
$('.panel-refresh').click(function (e) {
e.preventDefault();
$.ajax({
url:'{{path('history/reload')}}',
type: "POST",
cache: "false",
dataType: "html",
success: function (data) {
$("tbody").html(data);
}
});
});
Thank you very much!

Related

ASP.NET bootstrap modal display

There is a representation in the form of a table. If I click on the row name in the table, a modal window is displayed. Modal window with a form that is quite complex.
To display the modal window I use the following code:
$('#modal-container').on('shown.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var url = button.attr("href");
var modal = $(this);
modal.find('.modal-content').load(url);
});
$.ajaxSetup({ cache: false });
$('#modal-container').on('hidden.bs.modal', function () {
$(this).removeData('modal');
});
There are the following problems:
when repeated calls for some very short time, the contents of the last call are displayed - it is not so important
sometimes new content is not displayed at all, and the modal window contains information from the last call - it's very important
tell me, please, what could be the problem. I do not know much about JS
code where content is downloaded:
<div id="modal-container" class="modal fade hidden-print" #*tabindex="-1" *# role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
</div>
</div>
call from the action method
return PartialView("Details", projectECVM);
I suspect that the js runs faster than the razor generates the page.
Here I am forming a call for the action method:
#foreach (var item in Model.ProjectVM)
{
<tr class="clickableProject" id="#item.Id" title="View BugReports for #item.ProjectName">
<td id="Name">
<a id="details-link" asp-action="Details" asp-controller="Project" asp-route-id="#item.Id" title="View details project #item.ProjectName" data-toggle="modal" data-target="#modal-container">#Html.DisplayFor(it => item.ProjectName)</a>
</td>
<td id="Owner">
<label class="clickableProject">#item.Owner</label>
</td>
<td id="TrelloBoardURL">
<a id="trelloboard-link" href="#item.TrelloBoardURL" title="Go to TrelloBoard" target="_blank"><img src="~/images/trello-logo-blue.png" height="20" /></a>
</td>
<td id="Modification">
<label class="clickableProject">#item.Modification</label>
</td>
<td id="By">
<label class="clickableProject">#item.By</label>
</td>
<td id="DateTime">
<label class="clickableProject">#item.EntryDateTime</label>
</td>
</tr>
}
Clear the content of the dialog box before loading new content:
$(document).ready(function () {
$(function () {
$('#modal-container').on('shown.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var url = button.attr("href");
var modal = $(this);
$(this).empty(); //adding this part before reloading it.
modal.find('.modal-content').load(url);
});
$.ajaxSetup({ cache: false });
$('#modal-container').on('hidden.bs.modal', function () {
//$(this).empty(); //moved from shown
$(this).removeData('modal');
});
if ($('#modal-container').text().trim().length > 0) {
$('#modal-container').dialog('open');
}
else {
}
});
});

MVC4-Refresh Issue:Same partial view called 3 times using foreach..loop

I am in a tricky situation,
Scenario- There are gadgets which are to be shown in mobile site.
2.One of the gadget is RSS which user can add multiple times for different topics like one for security, one for news, one for events.
3. So we have 1 partial view for RSS, but if the user has 2 RSS gadgets then the same partial view should load with different gadget name. Here the functionality is working fine using foreach loop.
#foreach (var rssFeed in Model.RSSFeedList)
{
<article class="bm2014_bigBoxWrap bm2014_bigBoxRSS bm2014_paginate">
<img src="~/Content/images/iconRefresh.png" width="20" height="20" alt="refresh icon" title="refresh icon">
<div class="bm2014_expColCtrl">
<h1 class="bm2014_bigBoxHdr">
<span class="bm2014_hiddenHdr"> </span>
<!-- for markup validation -->
#if (rssFeed.Channel.Name == "xyznews")
{
<span>#Html.Label(Labels.Title_xyz)</span>
}
else if(rssFeed.Channel.Category=="xyzRSSFeed")
{
<!--<span>#Html.Label(Labels.xyz) - #rssFeed.Channel.Title</span>-->
<span>#rssFeed.Channel.Title</span>
}
<span class="bm2014_expColBtn"><img src="~/Content/images/iconPlus.png" width="32" height="32" alt="expand collapse icon" title="expand collapse icon"></span>
</h1>
<div class="bm2014_expColContent bm2014_bellnetRSSWrapper" id="bm2014_divBellnetRSS">
#Html.Partial("~/Views/Shared/_RSS.cshtml", rssFeed)
</div>
</div>
</article>
}
<!-- RSS Panel end here -->
Problem is with refresh issue
if i hit the refresh button for selected gadget, it is by default taking only one RSS name and loading the content irrespective of different gadget selected.
partialview page code-
#model Models.RSSFeed
#{
Layout = null;
}
<script src="~/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.multilevelpushmenu.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-simple-pagination-plugin.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.dataTables.js" type="text/javascript"></script>
<script type="text/javascript">
/* scripts to load after the DOM gets ready */
$(function () {
offCanvasMenu(); // trigger Javascript controlled OFF canvas menu after AJAX refresh
$.ajaxSetup({ cache: false });
$("article.bm2014_bigBoxRSS #btnRefresh").on('click', function (event) {
var $rssGadgetID = $(this).parents("article.bm2014_paginate").find("div#bm2014_divBellnetRSS");
var $rssGadgetLdr = $rssGadgetID.find("div#bm2014_gadgetLoader");
ajaxLoaderHeightCtrl($rssGadgetID, $rssGadgetLdr);
// AJAX control
$.ajax({
url: '#Url.Action("RefreshBellnetRSS", "Home", new { feedName = Model.Channel.FeedName })',
contentType: 'application/html; charaset=utf-8',
type: 'GET',
dataType: 'html',
success: function (result) {
$rssGadgetLdr.fadeOut(100, function () {
$rssGadgetID.html(result);
var moveRSS = $("article.bm2014_bigBoxWrap").css("float");
if (moveRSS == "left") {
mQueryAJAX("portrait", $rssGadgetID);
}
else if (moveRSS == "none") {
if (window.matchMedia("(orientation: portrait)").matches) {
mQueryAJAX("portrait", $rssGadgetID);
}
if (window.matchMedia("(orientation: landscape)").matches) {
mQueryAJAX("portrait", $rssGadgetID);
}
}
hideTableHeader();
});
},
error: function (xhr, status) {
alert(status);
}
});
});
});
</script>
<div class="bm2014_gadgetLoader" id="bm2014_gadgetLoader" style="display: none;">
<img src='#Url.Content("~/Content/Images/loaderGadget.gif")' width="48" height="48" alt="ajax loader image" title="ajax loader image">
</div>
<div class="bm2014_strategyContent">
#if (Model.url != null)
{
<table>
<thead>
<th>dummy header - to be hidden</th>
</thead>
<tbody>
#foreach (var url in Model.url)
{
<tr>
<td>
#url.Name
</td>
</tr>
}
</tbody>
</table>
}
</div>
need help/suggestions
If I understand correctly, you need to have 3 refresh buttons for 3 RSS gadgets e.g. one for security, one for news, one for events.
In the current example, every time you call the code to apply click event, you replace the earlier event and the 'feedname' parameter in url for ajax call also gets updated.
$("article.bm2014_bigBoxRSS #btnRefresh").on('click', function (event) {
......
}
You need to be able to distinguish between the refresh buttons and pass correct parameters. One way is to use data-feedname attribute on your btnRefresh anchor tag (if using HTML5)

How to navigate to new page when click on submit button using `meteor js`

I need when click on submit or login button how to navigate to new page with same window using meteor js. please help me how to write.
when user submit the form page navigate to admindetails.html page .I am using router package and the html page and client code is below. My intention is after user login load another template in same window dynamically .Please help me.
Here is html page
<template name="body">
<div class="bgbody">
<div align="center">
<form id="login-form" action="/admindetails">
<table>
<p class="admin">Admin Login</p>
<tr>
<td><p for="username">Admin Name</p></td>
<td><input type="text" id="username" name="username" placeholder="UserName"></td>
</tr>
<tr>
<td><p for="password">Password</p></td>
<td><input type="password" id="pwd" name="password" placeholder="password"></td>
</tr>
<td></td><td><input class="btn btn-success" type="submit" value="Log In"></td>
</table>
</form>
</div>
</div>
</template>
Here is the Client code
if (Meteor.isClient)
{
Meteor.Router.add({
'/admindetails':'admindetails'
})
Template.body.events
({
'submit #login-form' : function (e,t)
{
/* template data, if any, is available in 'this'*/
if (typeof console !== 'undefined')
console.log("You pressed the button");
e.preventDefault();
/*retrieve the input field values*/
var email = t.find('#username').value
, password = t.find('#pwd').value;
console.log(email);
Meteor.loginWithPassword(email, password, function (err)
{
if (err)
{
console.log(err);
alert(err.reason);
Session.set("loginError", true);
}
else
{
console.log(" Login Success ");
Meteor.Router.to("/admindetails");
}
});
}
});
}
If you use the recommended Iron Router, you use the go method:
Router.go('/articles/example');
or:
Router.go('showArticle', {name: 'example'});
If you use the old Router, use:
Meteor.Router.to('/articles/example');
If you don't use any router, start right now. In the meantime, use the stone-age method:
window.location.href = '...';

Can only update the first record of a result set in MVC

I have taken over support of an MVC application, but unfortunately have pretty much zero experience or knowledge of MVC, so I apologise in advance if this is a stupid question.
We are placing every single result into a listed item in the HTML, then hiding all but one record, so you can filter through the different entries using First/Prev/Next/Last buttons, all via jQuery:
$("a#next").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":last-child")) {
return false;
}
nextli.removeClass("first").addClass("record").next().addClass("first").removeClass("record");
});
$("a#previous").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":first-child")) {
return false;
}
nextli.removeClass("first").addClass("record").prev().addClass("first").removeClass("record");
});
This is fine, and displays the records without any problem, however when you try to edit any record but the first, you get a "System.ArgumentNullException: Value cannot be null." error.
Here's the code in the controller for the edit function:
[HttpPost]
public ActionResult Edit(RecordsView rv)
{
if (ModelState.IsValid)
{
repository.EditRecord(rv.Records.FirstOrDefault().DogIncident);
}
return RedirectToAction("Index");
}
This is defined at the start of the cshtml file:
#using (Html.BeginForm("Edit", "Home", FormMethod.Post,new {#class="record-view"}))
And finally, here is how the HTML is generated on the view:
<li class="first" id="record-1805">
<form action="/Home/Edit" class="record-view" method="post">
<ul>
[form elements]
<li><input type="submit" style="margin: 18px 0;" value="Save"></li>
</ul>
</form>
</li>
<li class="record" id="record-1804">
<form action="/Home/Edit" class="record-view" method="post">
<ul>
[form elements]
<li><input type="submit" style="margin: 18px 0;" value="Save"></li>
</ul>
</form>
</li>
<li class="record" id="record-1803">
<form action="/Home/Edit" class="record-view" method="post">
<ul>
[form elements]
<li><input type="submit" style="margin: 18px 0;" value="Save"></li>
</ul>
</form>
</li>
Does anyone please know why I can only edit the first record that is displayed and not the others? Even if I go through the records using the next/back buttons and back to the first record to submit it, it updates fine, but updating any other record generates an error.
Referencing Darin's post: Pass a parameter to a controller using jquery ajax takes you halfway. He's using an input val in jQuery and passing it to the Controller Action.
Typically you'd provide one input link or #Html.ActionLink per record to be clicked for editing and MVC will bind to the controls parameter to your action (ID or what ever you want) just use the same name on the action link as the parameter and it will be mapped during the post.
data: { input: $('#caption').val() },
Change the signature of your controller action , or add another that takes an 'int' as shown below.
[HttpPost]
public ActionResult Edit(int ID = 0)
{
if (ModelState.IsValid)
{
repository.EditRecord(rv.Records.Where(r => r.ID == ID).DogIncident);
}
return RedirectToAction("Index");
}
Can you post the complete view so we can complete a solution ?
Was expecting the cshtml view. Here's an example:
#model IEnumerable<yourModelName>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.NID)
</th>
<th>
#Html.DisplayNameFor(model => model.CreatedOn)
</th>
<th>
#Html.DisplayNameFor(model => model.ExtensionAttribute15)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.yourElement1)
</td>
<td>
#Html.DisplayFor(modelItem => item.yourElement2)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
</td>
</tr>
}
</table>
#section Scripts{
<script type="text/javascript">
$("a#next").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":last-child")) {
return false;
}
nextli.removeClass("first").addClass("record").next().addClass("first").removeClass("record");
});
$("a#previous").on("click", function () {
var nextli = $("li.first");
if ($(nextli).is(":first-child")) {
return false;
}
nextli.removeClass("first").addClass("record").prev().addClass("first").removeClass("record");
});
</script>
}

Problems while Styling a form element that gets data back with ajax

im facing a strange problem while trying to style a form element. A select element in particular.
the idea is simple. i got one select, and when its state changes, through ajax, a second selects gets its data throung a request. so far, everything is ok. the ajax is working fine. but when the first select changes its state, the select element styling is getting back to normal styling.
a live example can be found here
im using 2 main files, the important content of file 1 file is this
<script language="javascript" type="text/javascript">
/* FUNCTION : Ajax Initialize - Start */
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
/* FUNCTION : Ajax Initialize - End */
/* FUNCTION : Get Values - Start */
function getValue(numb) {
var strURL="find.php?theValue="+numb;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('my_requestDiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
/* FUNCTION : Get Values - End */
</script>
and
<form method="post" action="" name="form1" id="example">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="160" class="title_style">What</td>
<td width="340">
<select class="select" name="start" onChange="getValue(this.value)">
<option value="">please make a selection</option>
<option value="1">Colors</option>
</select>
</td>
</tr>
<tr>
<td width="160" class="title_style">Result</td>
<td width="340">
<div id="my_requestDiv">
<select class="select1" name="my_request" >
<option>Please select above first</option>
</select>
</div>
</td>
</tr>
</table>
</form>
where, after the user makes a selection on select element 1, through ajax, a variable is passed to find.php
<?php
$what=intval($_GET['theValue']);
$link = mysql_connect('localhost', 'YOUR_USERNAME_HERE', 'YOUR_PASSWORD_HERE');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES 'utf8'", $link);
mysql_select_db('cry-for-help');
$query="SELECT id, value FROM my_table WHERE requested='$what'";
$result=mysql_query($query);
?>
<select class="select" name="my_request">
<option>make your selection now</option>
<?php
while($row=mysql_fetch_array($result)) {
?>
<option value=<?php echo $row['id']?>><?php echo $row['value']?></option>
<?php
}
?>
</select>
and the result is posted back on file 1 as content for the second select element.
The Problem is that the styling is gone.
you can download the example files here
any help would be appreciated. Also, im sorry if my english is not that good, and my programming skills not that advanced to explain my problem with less words.
Jan
Based on the page to which you linked, it looks the problem is that you are replacing all of the extra HTML elements which have been generated by jqtransform. In your JavaScript callback, you are doing this:
document.getElementById('my_requestDiv').innerHTML=req.responseText;
This replaces the entire contents of the div, blowing away all of the extra elements that jqtransform puts in there. What you actually want to do is replace just the select element itself with the results from your PHP service, or perhaps run jqtransform again after updating the div.
Since you're already including jQuery, I would recommend using their powerful selection functionality to replace just the select element:
$('select[name="my_request"]').replaceWith(req.responseText);
I'm not familiar with the jqtransform library so you may need to investigate further to see which route makes the most sense.

Resources