Struts2 back button and linking - button

I am using Struts 2.1.6 with Dojo plugin, whole app has ajax links (sx:a).
Did anybody succeed to implement back button functionality and linking to certain content?
Does anybody have any experience how to implement? I am planning to implement (if there is no good solution already) something like so:
changing address bar link (adding parameters) with js which I can then read and get proper content and then publish it with notifyTopics.
Or should I just change whole app to use jQuery plugin? Do jQuery has good solutions for back button and linking on ajax pages?

I can think of 2 simple ways off the top of my head:
<s:form action="actionName">
<input type="hidden" value="<s:property value="someProperty"/>" name="someProperty"/>
<input type="hidden" value="<s:property value="someProperty2"/>" name="someProperty2"/>
<s:submit value="Back" />
</s:form>
or
<s:url name="backURL" action="actionName">
<s:param name="someProperty" value="someProperty"/>
<s:param name="someProperty2" value="someProperty2"/>
</s:url>
Back
If you already have query string parameters:
Back
or
<input type="button" value="Back" onclick="javascript.window=document.referrer;"/>

I have tried to use Struts 2 with dojo and implement the back button. You are already way over the head of Struts 2's ajax implementation. They mainly used and wrote it to write simple and quick ajax function calls and is not very well suited for more extensive uses. Plus when you do s:head theme='ajax' tag; struts will import every ajax js file you 'may' need which kills load time.
I would suggest either 1. Learn dojo and use the library independent of struts 2. Or 2. Get jQuery, I was able to implement a back button functionality relatively simple (more so then struts 2 theme='ajax').

Don't know Struts, but have you looked at dojo.undo (0.4.3)?

All my links go through one action which looks for a parameter menuId (of course id of a menu which has to be shown).
From this action, before returning response I set one javascript function to be called:
setBackMenuId(menuId,sometext)
MenuId is the id, sometext is a name of that menu, so browser log history better.
function setBackMenuId(id,subtekst) {
window.location.hash = "menuId="+id;
document.title = subtekst;
selectedHash = document.location.hash;
if(intervalHashSearch == '') {
initializeHashSearch();
}
}
Then, other needed js functions:
function publishLinkTarget() {
var param = window.location.hash;
if(param) {
if(param.indexOf("menuId") > 0) {
var id = param.split("=", 2);
if(id[1]) {
setCookie('backMenuId',id[1],1,false);
setTimeout('publishLayoutContent()', 100);
}
}
}
}
var selectedHash = '';
var intervalHashSearch = '';
function initializeHashSearch() {
intervalHashSearch = window.setInterval('checkHash()', 500);
}
function stopHashSearch() {
window.clearInterval(intervalHashSearch);
intervalHashSearch = '';
}
function checkHash() {
var currentHash = document.location.hash;
if(selectedHash != currentHash) {
selectedHash = currentHash;
publishLinkTarget();
}
}
function publishLayoutContent() {
dojo.event.topic.publish("layoutContentTarget");
}
If you look at it you see, that first it is called 'setBackMenuId', which adds hash and parameter to address bar and changes title, and then remembers this hash, so interval hash search can find out the differrence. Then it initializes this hash search.
'checkHash' is running ever 500 miliseconds and is checking if hash has changed (that means, that back button was pressed, and not a new link was clicked (setBackMenuId sets selectedHash). If true (back/forward button was pressed) function 'publishLinkTarget' is called, which reads the parameters from hash, and if they are ok, first I set a cookie, so I can read it from the HttpServletRequest and find out for which menu id link is. If I am here it means that I have to also publish the content which is made with 'publishLayoutContent'.
In action class (this is MenuAction, method view, the same as published in ) only this is important:
Integer menuId = null;
if(request.getParameter("menuId") != null) {
menuId = Integer.valueOf(request.getParameter("menuId"));
} else {
menuId = getIntCookie("hiddenMenuId");
}
So, if I don't get the menu id from the parameter (link clicked) I get from a cookie (back/forward button).
And JSP with this target:
<s:url var="layoutContentUrl" action="Menu-view" namespace="/public" />
<sx:div showLoadingText="false" indicator="ajaxIndicator"
id="layout-content" href="%{layoutContentUrl}" theme="ajax"
listenTopics="layoutContentTarget" preload="false"
afterNotifyTopics="/ajaxAfter">
</sx:div>
NOTE: This is a special case if you have everything connected through one parameter, but it can be easily extended with other parameters which publish other targets. I will try to make it enough generic to publish it somewhere, but this is (I guess) a long way ahead :)
If you have any question, please post it.

Related

Can a Meteor method call get invoked via Collection.findOne

In my Meteor code. Can I define a method "or a function" on the server and call it on collectionName.findOne({id: 'someId'}).methodName; on the client?
Being new to Meteor, I don't know if this is possible and if so, what would the syntax look like? Thanks
This code is just a brain dump.
//server
Meteor.method({
doWork1: function (args) {
//do work
return something;
}
});
MyCol = new Mongo.Collection('myCol');
MyCol.insert({item: "envelopes", qty : 100, myFunc: doWork1});
//client
Meteor.call(MyCol.findOne({item: 'envelops'}).myFunc;
Edited:
Blaze Sahlzen comments made me think and add the following.
The reasons why I thought to give a mongo collection a try is this:
Stage one: the user fills up a form and click a button, the input values need to be used as arguments for a method which when successfully returns, the form gets modified to show different input fields for the user to fill up again and click the SAME button.
Stage two: same as stage one but with different input fields again.
Stage n: same as stage n-1 but with different input fields again.
I need to store all input values and group them by their stage identifier.
Each method may add/remove different kind of input controls for the next stage.
Since the SAME button will be used thus I don't have different buttons for different methods, so I came up with my original question "brain dump code". You are welcome to reinvent or change it and offer yours. :) Thanks again.
edited 2
A practical example could look like this:
var stageOne = {};
//for each DOM input
stageOne[inputName][i]= [inputValue][i];
myCol.insert({'stageOne': stageOne});
//then an observer for stageOne
But I just can't get my head around how to "link" each stage with the correct method to call without having to use a long if or switch conditional statement.
Alright, if I understand what you mean, I don't think you need observeChanges. The following solution might be a bit extensive, so bear with me.
Firstly you need a session variable to control on the client side which form values need to be shown. You could introduce this variable in your Template.name.onRendered.
Session.set('stage',1);
Then you have your input fields
<form>
<label id="label1">{{label1}}</label>
<input id="field1" type="text"/>
<label id="label1">{{label2}}</label>
<input id="field2" type="text"/>
<label id="label1">{{label3}}</label>
<input id="field3" type="text"/>
<button id="form-submit" type="submit"/>
</form>
I can imagine that you want to switch up the names of their labels to reflect the change in forms as you go to different stages. As a result you can write helpers as such:
'label1': function(){
var myStage = Session.get('stage');
if (myStage == 1){return '<label-title-for-stage-1>';
} else if (myStage == 2){return '<label-title-for-stage-2>';}
} else if .... etc.
}
Any changes to the session variable 'stage' will force the helper to reload, making it ideal to update form titles as you go through your stages.
You can then write an event for the button click event as such:
'submit #form-submit': function(){
var options = {
stage: Session.get('stage'),
values: [
{ value: $('#field1').val(), name:$("#label1").text() },
{ value: $('#field2').val(), name:$("#label1").text() },
{ value: $('#field3').val(), name:$("#label3").text() }]
}
Meteor.call('storeValues', options, function(error, result) {
if (error) {
console.log(error);
}
Session.set('stage',result);
});
}
This will essentially combine the filled fields into one object and call upon a server method, waiting for a callback from the server that tells the client which stage to move to.
Now, on the server side you can insert the values for this particular user in your collection and see if a particular stage has filled up and return whether the client can move on to the next stage.
Meteor.methods({
'storeValues': function(options){
for (var i = 0; i < options.values.length; i++){
myCol.insert({
value:options.values[i].value,
name:options.values[i].name,
stage: options.stage
});
}
if (options.values.length > 'amount-per-stage'){
return options.stage + 1;
} else {
return options.stage;
}
}
});
This way you store the data that gets entered in each form, while moving up one stage each time if all fields have been entered.
What you could do is use observeChanges:
var query = MyCol.find({item: 'envelops'});
var handle = query.observeChanges({
added: function () {
somethingHappened();
},
changed: function () {
somethingHappened();
}
});
var somethingHappened = function(){
// do something
}
Query contains your collection, and the handle function automatically checks whether any changes are being made to that collection, triggering the somethingHappened function if there are.
Inside somethingHappened you can place the behaviour that you would normally place in your method.
You can use observeChanges both client side and server side, but in this case you only need it on the server side.

What is the simplest way to find current item ID in the template

In my C# or dreamweaver template I need to know what am I rendering. The problem is that I don't know for sure if I'm looking for a page or component. I could probably use package.GetByType(ContentType.Page) and if it's empty - get content of a component, but I feel there should be a shorter way.
Example of David is shorter:
engine.PublishingContext.ResolvedItem.Item.Id
engine.PublishingContext.ResolvedItem.Item.Id
You can also check the Publishing Context's resolved Item and see if it's a Page or not (if it's not, then it's a Component).
For example:
Item currentItem;
if (engine.PublishingContext.ResolvedItem.Item is Page)
{
currentItem = package.GetByName(Package.PageName);
}
else
{
currentItem = package.GetByName(Package.ComponentName);
}
TcmUri currentId = engine.GetObject(currentItem).Id;
If you want to shortcut the engine.GetObject() call, then you may be able to get the ID from the Item's XML directly:
String currentId = currentItem.GetAsSource().GetValue("ID");
That's how I've seen it done before:
// Contains the call you describe in your question
Page page = GetPage();
if (page == null)
{
// Contains a call using package.GetByName("Component")
// to avoid the situation with multiple Components on the package
Component comp = GetComponent();
// Do component stuff
}
else
{
// Do page stuff
}
Not sure you can encapsulate it much nicer than that really but I may be proved wrong.

How to set UseSubmitBehavior="False" in one place for the whole web application

I want all of the buttons in my asp.net web forms application to have UseSubmitBehavior="False" but I don't want to go through all my pages trying to hunt down each and every last button and set the property individually.
I am hoping there is a way to do this globally, for example in the web.config file. Thanks!
This is not a page property or something like that
this is a button property which allowes submit via __doPostBack
You Can't do this globally via web.config ( or in any other way).
The reason for wanting to set UseSubmitBehavior="False" is to stop the form from submitting when the user presses enter. If this is your goal then the following will interest you:
Another way to do this is to use JavaScript. This shifts the overhead of MikeSmithDev's suggestion to the client which might be more acceptable depending on your scenario.
Please note that the following JavaScript makes use of the jQuery library:
$(document).ready(function () {
preventSubmitOnEnter();
});
function preventSubmitOnEnter() {
$(window).keypress(function (e) {
if (e.which == 13) {
var $targ = $(e.target);
if (!$targ.is("textarea") && !$targ.is(":button,:submit")) {
return false;
}
}
});
}

ASP.NET postbacks lose the hash in the URL

On an ASP.NET page with a tabstrip, I'm using the hash code in the URL to keep track of what tab I'm on (using the BBQ jQuery plugin). For example:
http://mysite.com/foo/home#tab=budget
Unfortunately, I've just realized that there are a couple of places on the page where I'm using an old-fashioned ASP.NET postback to do stuff, and when the postback is complete, the hash is gone:
http://mysite.com/foo/home
... so I'm whisked away to a different tab. No good.
This is a webforms site (not MVC) using .NET 4.0. As you can see, though, I am using URL routing.
Is there a way to tell ASP.NET to keep the hash in the URL following a postback?
The problem is that the postback goes to the url of the current page, which is set in the action of the form on the page. By default this url is without #hash in asp.net, and its automatically set by asp.net, you have no control over it.
You could add the #hash to the forms action attribute with javascript:
document.getElementById("aspnetForm").action += location.hash
or, if updating an action with a hash already in it:
var form = document.getElementById("aspnetForm");
form.action = form.action.split('#')[0] + location.hash
just make sure you execute this code on window.load and you target the right ID
I tried to put the code from Willem's answer into a JS function that got called everytime a new tab was activated. This didn't work because it kept appending an additional #hash part to the URL every time I switched tabs.
My URL ended up looking like http://myurl.example.com/home#tab1#tab2#tab3#tab2 (etc.)
I modified the code slightly to remove any existing #hash component from the URL in the <form> element's action attribute, before appending on the new one. It also uses jQuery to find the element.
$('.nav-tabs a').on('shown', function (e) {
// ensure the browser URL properly reflects the active Tab
window.location.hash = e.target.hash;
// ensure ASP.NET postback comes back to correct tab
var aspnetForm = $('#aspnetForm')[0];
if (aspnetForm.action.indexOf('#') >= 0) {
aspnetForm.action = aspnetForm.action.substr(0, aspnetForm.action.indexOf('#'));
}
aspnetForm.action += e.target.hash;
});
Hope this helps someone!
I have another solution, implemented and tested with chrome, IE and safari.
I am using the "localStorage" object and it suppose to work all the browsers which support localStorage.
On the click event of tab, I am storing the currentTab value to local storage.
$(document).ready(function() {
jQuery('.ctabs .ctab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage["currentTab"] = currentAttrValue;
// Show/Hide Tabs
jQuery('.ctabs ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
if (localStorage["currentTab"]) {
// Show/Hide Tabs
jQuery('.ctabs ' + localStorage["currentTab"]).show().siblings().hide();
// Change/remove current tab to active
jQuery('.ctabs .ctab-links a[href$="' + localStorage["currentTab"] + '"]').parent('li').addClass('active').siblings().removeClass('active');
}
});

ASP.NET MVC Submitting Form Using ActionLink

I am trying to use link to submit a form using the following code:
function deleteItem(formId) {
// submit the form
$("#" + formId).submit();
}
Basically I have a grid and it displays a number of items. Each row has a delete button which deletes the item. I then fire the following function to remove the item from the grid.
function onItemDeleted(name) {
$("#" + name).remove();
}
It works fine when I use a submit button but when I use action link the JavaScript from the controller action is returned as string and not executed.
public JavaScriptResult DeleteItem(string name)
{
var isAjaxRequest = Request.IsAjaxRequest();
_stockService.Delete(name);
var script = String.Format("onItemDeleted('{0}')", name);
return JavaScript(script);
}
And here is the HTML code:
<td>
<% using (Ajax.BeginForm("DeleteItem",null, new AjaxOptions() { LoadingElementId = "divLoading", UpdateTargetId = "divDisplay" },new { id="form_"+stock.Name }))
{ %>
<%=Html.Hidden("name", stock.Name)%>
<a id="link_delete" href="#" onclick="deleteItem('form_ABC')">Delete</a>
<% } %>
</td>
My theory is that submit button does alter the response while the action link simply returns whatever is returned from the controller's action. This means when using submit the JavaScript is added to the response and then executed while in case of action link it is simply returned as string.
If that is the case how can someone use action links instead of submit buttons.
UPDATE:
Seems like I need to perform something extra to make the action link to work since it does not fire the onsubmit event.
http://www.devproconnections.com/article/aspnet22/posting-forms-the-ajax-way-in-asp-net-mvc.aspx
My guess is the MS Ajax form knows how to handle a JavaScriptResponse and execute the code whereas your plain old Action link, with no relationship to the AjaxForm, does not. I'm pretty sure the MS ajax library essentially eval()s the response when it sees the content type of javascript being sent back.
Since you have no callback in your deleteItem() method there is no place for the script to go. To fix you'll have to manually eval() the string sent back which is considered a bad practice.
Now I'm not familiar with the MS Ajax library to be certain of any of this but what your doing is possible. I'd do things differently but don't want to answer with a "my way is better" approach ( especially because your blog has helped me before ) but I'd like to show this can be easier.
I'd ditch the form entirely and use unobtrusive javascript to get the behavior you want. IN psuedo jqueryish ( don't know ms ajax ) code:
function bindMyGrid() {
$('.myDeleteLink').onclicksyntax( function() {
//find the td in the row which contains the name and get the text
var nameTdCell = this.findThisCellSibling();
//do an ajax request to your controller
ajax('myUrl/' + nameTdCell.text(), function onSuccessCallback() {
//get the tr row of the name cell and remove it
nameTdCell.parent().remove();
});
});
}
This also gains the benefit of not returning javascript from your controller which some consider breaking the MVC pattern and seperation of concerns. Hope my psuedo code helps.
Try without the UpdateTargetId property in the AjaxOptions (don't specify it)
new AjaxOptions() { LoadingElementId = "divLoading" }
What about just change look of a standard or using some css class? It'll look like a link and you'll avoid some problems you get with anchors - user will be able to click on it by a mouse wheel and open that link in a new tab/window.

Resources