[ DWR Website | Web Application Index ]

Dynamically Editing a Table

This demo allows you to edit a table of data

All People

Person Age Superhero? Actions

Edit Person

Name:
Address:
Age:
Superhero?:
(ID=-1)

Creating the table

When the page first loads, the onload event calls the init function which calls the server-side People.getSmallCrowd() function to return an array of people objects.

function fillTable() {
$.post("../../../dwr/jsonp/People/getSmallCrowd", { },
callBackFunction, "json");
}

People.getSmallCrowd() is called using the jQuery post function to make an asynchronous call to the server utilizing DWR's JSON capabilities. The first parameter is the URL for DWR's JSON service. The URL can be broken down as follows:

The third parameter is the callback function and will be invoked when the remote call returns. The callback function will always be passed one parameter - the data returned from the remote call.

A Person is just a POJO containing an id, name and address fields along an age as an integer an boolean superhero status. Full details of the Java source are shown on the "Source" tab.

The Javascript uses the cloneNode() feature to create a row in a table for each returned person. So for each person we do this:

dwr.util.cloneNode("pattern", { idSuffix:person.id });

This creates a copy of the node with the id "pattern", and alters the ids of any sub-nodes to have a suffix of the current persons id, so if pattern looks like this:

<div id="pattern"><input id="edit"/></div>

Then after cloning using an idSuffix:42, you will have this:

<div id="pattern"><input id="edit"/></div>
<div id="pattern42"><input id="edit42"/></div>

After cloning we then fill in the blanks in the newly cloned row. This uses the setValue that we looked at in the Dynamic Text demo:

dwr.util.setValue("tableName" + id, person.name);
dwr.util.setValue("tableSalary" + id, person.salary);
dwr.util.setValue("tableAddress" + id, person.address);

We also need to ensure that the pattern row is not visible, but the clones are. We do this by setting a style of display:none on the pattern row in the HTML, and then setting the cloned row to have display:table-row in the Javascript:

$("pattern" + id).style.display = "table-row";

We need to account for the fact that this could be a re-draw rather than a draw on page-load, so we might need to remove old rows. dwr.util.removeAllRows() as been around since 1.0, but new in 2.0 is the options object which can contain a filter to be selective about the rows we remove. In this case we want to remove everything but the "pattern" row.

    // Delete all the rows except for the "pattern" row
dwr.util.removeAllRows("peoplebody", { filter:function(tr) {
return (tr.id != "pattern");
}});

For the full Javascript or the HTML, see the source tab. The full Javascript does 2 extra things - it caches the people, and sorts them.

Populating the form

When an 'edit' button is clicked, the editClicked() function is called with the id of the button. We can work out the person id from this easily because the button was created by the clone process, so the person id is just the button id without the 'edit' prefix.

This makes the editClicked() function really simple:

function editClicked(eleid) {
// we were an id of the form "edit{id}", eg "edit42". We lookup the "42"
var person = peopleCache[eleid.substring(4)];
dwr.util.setValues(person);
}

The dwr.util.setValues() function finds form fields with the same names as the properties of the object passed in.

Updating the server

There is a good use of dwr.util.getValues() in the code to post changes back to the server:

function writePerson() {
var person = { id:viewed, name:null, address:null, age:null, superhero:null };
dwr.util.getValues(person);
$.post("../../../dwr/jsonp/People/setPerson?param0=" + encodeURIComponent($.toJSON(person)), { },
fillTable, "json");
}

First we create an object which is filled out by dwr.util.getValues(). We then post the change to the server, once again using the jQuery post function. This time we are calling the setPerson function.  The setPerson function takes one parameter (of type Person), and thus we are specifying param0 (if multiple parameters exist name them accordingly param0, param1, param2, etc.).  The Person object must be converted to a JSON string and encoded before we send it to the server.  We are using the jquery-json plugin's $.toJSON function to serialize the person object into a JSON string and we are using the JavaScript encodeURIComponent function to properly encode the JSON string.

See the source tab for full source.

HTML source:

<h3>All People</h3>
<table border="1" class="rowed grey">
<thead>
<tr>
<th>Person</th>
<th>Age</th>
<th>Superhero?</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="peoplebody">
<tr id="pattern" style="display:none;">
<td>
<span id="tableName">Name</span><br/>
<small>  <span id="tableAddress">Address</span></small>
</td>
<td><span id="tableAge">Age</span></td>
<td><span id="tableSuperhero">Superhero</span></td>
<td>
<input id="edit" type="button" value="Edit" onclick="editClicked(this.id)"/>
<input id="delete" type="button" value="Delete" onclick="deleteClicked(this.id)"/>
</td>
</tr>
</tbody>
</table>
<h3>Edit Person</h3>
<table class="plain">
<tr>
<td>Name:</td>
<td><input id="name" type="text" size="30"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input id="address" type="text" size="40"/></td>
</tr>
<tr>
<td>Age:</td>
<td><input id="age" type="text" size="20"/></td>
</tr>
<tr>
<td>Superhero?:</td>
<td><input id="superhero" type="checkbox" size="20"/></td>
</tr>
<tr>
<td colspan="2" align="right">
<small>(ID=<span id="id">-1</span>)</small>
<input type="button" value="Save" onclick="writePerson()"/>
<input type="button" value="Clear" onclick="clearPerson()"/>
</td>
</tr>
</table>

Javascript source:

function init() {
  Tabs.init('tabList', 'tabContents');
  fillTable();
}

var peopleCache = { };
var viewed = -1;

function fillTable() {
    $.post("../../../dwr/jsonp/People/getSmallCrowd", { },
        callBackFunction, "json");
}

function callBackFunction(people) {
    people = people.reply;
    // Delete all the rows except for the "pattern" row
    dwr.util.removeAllRows("peoplebody", { filter:function(tr) {
        return (tr.id != "pattern");
    }});
    // Create a new set cloned from the pattern row
    var person, id;
    people.sort(function(p1, p2) { return p1.name.localeCompare(p2.name); });
    for (var i = 0; i < people.length; i++) {
        person = people[i];
        id = person.id;
        dwr.util.cloneNode("pattern", { idSuffix:id });
        dwr.util.setValue("tableName" + id, person.name);
        dwr.util.setValue("tableAge" + id, person.age);
        dwr.util.setValue("tableAddress" + id, person.address);
        dwr.util.setValue("tableSuperhero" + id, person.superhero ? "Yes" : "No");
        dwr.util.byId("pattern" + id).style.display = ""; // officially we should use table-row, but IE prefers "" for some reason
        peopleCache[id] = person;
    }
}

function editClicked(eleid) {
  // we were an id of the form "edit{id}", eg "edit42". We lookup the "42"
  var person = peopleCache[eleid.substring(4)];
  dwr.util.setValues(person);
}

function deleteClicked(eleid) {
  // we were an id of the form "delete{id}", eg "delete42". We lookup the "42"
  var person = peopleCache[eleid.substring(6)];
  if (confirm("Are you sure you want to delete " + person.name + "?")) {
    $.post("../../../dwr/jsonp/People/deletePerson/" + person.id, { },
        fillTable, "json");
  }
}

function writePerson() {
  var person = { id:viewed, name:null, address:null, age:null, superhero:null };
  dwr.util.getValues(person);
  $.post("../../../dwr/jsonp/People/setPerson?param0=" + encodeURIComponent($.toJSON(person)), { },
    fillTable, "json");
}

function clearPerson() {
  viewed = -1;
  dwr.util.setValues({ id:-1, name:null, address:null, salary:null });
}

web.xml

Note: In order to enable JSON/JSONP you must add the following init-param to your DWR servlet definition in your web.xml (This is a snippet and is not a complete web.xml).


...
<servlet>
<servlet-name>dwr-invoker</servlet-name>
<display-name>DWR Servlet</display-name>
<description>Direct Web Remoter Servlet</description>
<servlet-class>org.directwebremoting.servlet.DwrServlet</servlet-class>
<init-param>
<param-name>jsonpEnabled</param-name>
<param-value>true</param-value>
</init-param>
...

dwr.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dwr PUBLIC
"-//GetAhead Limited//DTD Direct Web Remoting 2.0//EN"
"http://getahead.org/dwr/dwr20.dtd">

<dwr>
<allow>
<create creator="new" javascript="People" scope="script">
<param name="class" value="org.getahead.dwrdemo.people.People"/>
</create>
<convert match="org.getahead.dwrdemo.people.Person" converter="bean"/>
</allow>
</dwr>