Set ATG Property And Popup Window After Clicking on Link

la cuarta ventana on Flickrla cuarta ventana by bachmont 

Sometimes when you click on a link in an ATG JSP/DSP page you want a property of an ATG component to be set as well.  For example:

[xml]<dsp:a href="foo.jsp">Foo
<dsp:property bean="BarFormHandler.baz" paramvalue="index"/>
</dsp:a>[/xml]

What gets tricky is if you also want a popup window to display the contents of this link.

The Wrong Way

I tried adapting the instructions from the tutorial Popup Windows | open new customised windows with JavaScript.

[xml]<dsp:a href="javascript:poptastic(‘foo.jsp’);">Foo
<dsp:property bean="BarFormHandler.baz" paramvalue="index"/>
</dsp:a>[/xml]

This does not work, i.e. the setter for baz in BarFormHandler is never called.

The Brute Force Way

I then reverted to the original DSP and looked at the outputted HTML.  Based on that I updated the DSP like this.

[xml]<% atg.servlet.DynamoHttpServletRequest dreq = atg.servlet.ServletUtil.getCurrentRequest(); %>
<a href="javascript:poptastic(‘foo.jsp?_DARGS=/betweengo/test.jsp_AF&_dynSessConf=<%= dreq.getSessionConfirmationNumber() %>&_D%3A/betweengo/BarFormHandler.baz=+&/betweengo/BarFormHandler.baz=<dsp:valueof param="index" />’);">Foo</a>[/xml]

This works but is grotesque.

The Good Idea That Did Not Work

Then I realized I could just set a parameter in the URL and have the form handler use the value to set the property.

[xml]<a href="javascript:poptastic(‘foo.jsp?index=<dsp:valueof param="index" />’);">Foo</a>[/xml]

And in BarFormHandler

public boolean beforeSet(DynamoHttpServletRequest req,
            DynamoHttpServletResponse res) throws DropletFormException {

  String indexParam = request.getParameter("index");
  setIndex(Integer.parseInt(indexParam));

  return super.beforeSet(request, response);
}

This did not work plus I did not really like it because now I have a beforeSet method that is called for every single request.

The Winner

I then realized I did not read the tutorial Popup Windows | open new customised windows with JavaScript carefully.  There is a more elegant way to call the JavaScript which degrades gracefully for browsers that don’t support JavaScript.

[xml]<dsp:a href="foo.jsp" onclick="poptastic(this.href);return false;">Foo
<dsp:property bean="BarFormHandler.baz" paramvalue="index"/>
</dsp:a>[/xml]

This works, is elegant and requires just adding the onclick attribute to the original DSP.

JavaScript Invalid Argument in Internet Explorer Only

Today I noticed one of my links were not working.  This was only happening in Internet Explorer 8.  Looking down at the status bar in the lower left corner I saw the message “Error on page.”  Double-clicking on it popped up this window full of useless information.

Internet Explorer 8 invalid argument JavaScript error

A Google search for “internet explorer invalid argument” brought me to this page, Internet Explorer Sucks.  Fortunately the author had run into this problem and figured out the solution.

It turns out In Internet Explorer, the second argument to the JavaScript window.open method, which is the windowName argument, can’t have spaces. My original link looked like this.

<a href="javascript:void(0);" onclick="window.open('popUp.jsp','Frank Kim betweenGo','menubar=0,toolbar=0,location=0,scrollbars=yes,width=400,height=175')">What's this?</a>

When I took out the spaces from the windowName argument the link worked.  You would think Internet Explorer 8 would have fixed this issue by now, it doesn’t affect any other modern web browser.

Unobtrusive JavaScript

Unobtrusive JavaScript’s goal is to move all the functionality (the Controller) out of the HTML (the Model) and the CSS (the View).  This is also called full MVC separation.

This is how typically JavaScript and HTML mix.  For example in submitting a form using a text link.

<a href="javascript:submit(document.testForm)">Submit</a>

Or for jumping to different parts of a page using a dropdown.

 <input type="image" src="/img/buttons/update.gif"
   onClick="window.location.hash=
document.jumpTo.names.options[document.jumpTo.names.selectedIndex].value">

Using the unobtrusive JavaScript technique one can separate the JavaScript from the HTML.

<div id="foo">Submit</div>

<script type="text/javascript">
 Event.observe($('foo'), 'click', function(event) {
   $(Event.element(event)).form.submit();
   return false;
 });
</script>

We use the Protoculous JavaScript file which combines the Prototype framework and Scriptaculous libraries to do unobtrusive JavaScript.

Undefined

Nouveau Variation on Flickr

(Photo: Nouveau Variation by Syntopia)

I find the undefined keyword and identity operators (=== and !==) in JavaScript pretty useful.  For example if I am parsing a JSON input and I am not sure if something is there or not I test it like this.

if (root.Foo === undefined)

If I want to test if something is defined I do it like this.

if (root.Bar !== undefined)

saladwithsteve explains it well in his JavaScript undefined vs. null post.

Update 12-14-2009: Unfortunately the above method did not work for testing a variable directly.  I ended up following the advice of this post, Javascript IsDefined Function.  To test if a variable is defined I now do this.

if (typeof(foo) != "undefined")

Removing a Cookie

To remove a cookie the Java API suggests getting the cookie, setting its maxAge to 0, and then adding that cookie to the response.  Digging around deeper I realized you also need to set the domain and the path to match the cookie’s domain and path.  Here is an example of how to do this.

    Cookie [] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(COOKIE_WE_WANT)) {
        cookie.setMaxAge(0);
        cookie.setDomain(".betweengo.com");
        cookie.setPath("/");
        response.addCookie(cookie);
        break;
      }
    }

Note that if the domain was not set when the cookie was created then you should not set it when you try to remove it. Similarly with the path property. For example if the domain was not set at creation then the code would look like this:

    Cookie [] cookies = request.getCookies();
    for (Cookie cookie : cookies) {
      if (cookie.getName().equals(COOKIE_WE_WANT)) {
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
        break;
      }
    }

Also you should ensure that you add the cookie to the response before the response has already been committed.  Previously the above code was in a tag but that was too late to modify the response.  I moved this code to a filter and then it worked fine.

Finally you can do this in JavaScript. Doing it in JavaScript has the downside that it is done after the page is loaded. But it’s definitely helpful for testing. Here’s an example of deleting the cookie named “foo”.

document.cookie = 'foo=;expires='+new Date(0).toUTCString()+';';

In the above example I did not set the path or the domain. One will need to do that if the path and/or domain were set in the cookie at creation.

Jumping to different parts of a page using a dropdown

It is relatively simple to dynamically create a dropdown from which you can jump to different parts of a page using JavaScript and ATG DSPEL.

First create the dropdown.

<form name="jumpTo" action=".">
  <dspel:droplet name="/atg/dynamo/droplet/ForEach">
    <dspel:param name="array" param="categories"/>
    <dspel:setvalue param="category" paramvalue="element"/>
    <dspel:oparam name="outputStart">
      <select name="names">
    </dspel:oparam>
    <dspel:oparam name="output">
      <dspel:getvalueof id="index" param="index"/>
      <c:set var="catShortName" value="cat${index}"/>
      <option value="<c:out value="${catShortName}"/>">
        <dspel:valueof param="category.name"/>
      </option>
    </dspel:oparam>
    <dspel:oparam name="outputEnd">
      </select>
    </dspel:oparam>
  </dspel:droplet>
</form>

Next create the button outside of the form for jumping to different parts of the page. I learned about the window.location.hash from this article. And I learned about how to access the selected value from the dropdown from this article.

 <input type="image" src="/img/buttons/update.gif"
   onClick="window.location.hash=
document.jumpTo.names.options[document.jumpTo.names.selectedIndex].value">

Finally you create the name anchors throughout your document.

<dspel:droplet name="/atg/dynamo/droplet/ForEach">
  <dspel:param name="array" param="categories"/>
  <dspel:setvalue param="category" paramvalue="element"/>
  <dspel:oparam name="output">

    <%-- magazine category --%>
    <dspel:getvalueof id="index" param="index"/>
    <c:set var="catShortName" value="cat${index}"/>
    <a name="<c:out value="${catShortName}"/>"
       id="<c:out value="${catShortName}"/>">
      <dspel:valueof param="category.name"/>
    </a>

  </dspel:oparam>
</dspel:droplet>

Submitting an ATG Form Using a Text Link

It has always bedeviled me how to submit an ATG form using a text link. I have asked many people about this but no one seems to know. Finally with the help of ATG support I figured it out.

Below is a simple example of how to do it. The trick is the hidden submit input which triggers ATG to call the handleSubmit method of the form handler.

<%@ taglib uri="/dspTaglib" prefix="dsp"%>

<dsp:page>

<script>
  function submit(form) {
    form.submit();
  }
</script>

<dsp:form action="<%=request.getRequestURI()%>" method="post" name="testForm">

  Foo: <dsp:input type="text" bean="TestFormHandler.foo"/>

  <p><a href="javascript:submit(document.testForm)">Submit</a>

  <dsp:input type="hidden" bean="TestFormHandler.submit" value="Submit"/>

</dsp:form>

</dsp:page>

You can also invoke the JavaScript like this:

  <p><a href="#" onclick="submit(document.testForm); return false;">Submit</a>

Submitting a form with a radio button

Submitting a form from a radio button is not common but it is a nice UI which is even better when done with AJAX.

A typical form with two radio buttons would look something like this.

<form action="test.html">
1 <input type="radio" name="test" value ="1"><br>
2 <input type="radio" name="test" value ="2">
<p><input type="submit" value="submit">
</form>
1
2

But with basic JavaScript you can make a simpler form like this.

<script>
function submitAction( form, absPath ) {
form.action = absPath;
form.submit();
}
</script>
<form action="test.html" id="test">
1 <input type="radio" name="test" value ="1" onchange="submitAction(document.getElementById('test'), 'test.html')"><br>
2 <input type="radio" name="test" value ="2" onchange="submitAction(document.getElementById('test'), 'test.html')">
</form>
1
2

If you are using Struts the above form’s JSP would be:

<html:form action="test.do" styleId="test">
1 <input type="radio" name="test" value ="1" onchange="submitAction(document.getElementById('test'), 'test.do')"><br>
2 <input type="radio" name="test" value ="2" onchange="submitAction(document.getElementById('test'), 'test.do')">
</html:form>