[ DWR Website | Web Application Index ]

# Dynamically Editing a Table

This demo allows you to edit a table of data

- Demo
- How it works
- Source

### All People

Person | Age | Superhero? | Actions
--- | --- | --- | ---
Name Address | Age | Superhero |

### Edit Person

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

## Creating the table

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

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);

      dwr.engine.beginBatch();
      People.setPerson(person);
      fillTable();
      dwr.engine.endBatch();
    }

First we create an object which is filled out by `dwr.util.getValues()`. We then post the change to the server, and update the table. We use a batch for the last 2 operations to ensure that we only make a single round-trip to the server.

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() {
      dwr.util.useLoadingMessage();
      fillTable();
    }

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

    function fillTable() {
      People.getSmallCrowd(function(people) {
        // 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 + "?")) {
        dwr.engine.beginBatch();
        People.deletePerson(person.id);
        fillTable();
        dwr.engine.endBatch();
      }
    }

    function writePerson() {
      var person = { id:viewed, name:null, address:null, age:null, superhero:null };
      dwr.util.getValues(person);

      dwr.engine.beginBatch();
      People.setPerson(person);
      fillTable();
      dwr.engine.endBatch();
    }

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

## Java source:

    public class People {
        public People() {
            smallCrowd = createCrowd(10);
        }

        public Collection<Person> getSmallCrowd() {
            return smallCrowd.values();
        }

        public String setPerson(Person person) {
            smallCrowd.put(person.getId(), person);
            return "Updated values for " + person.getName();
        }

        public String deletePerson(String id) {
            Person person = smallCrowd.remove(id);
            if (person == null) {
                return "Person does not exist";
            }
            else {
                return "Deleted " + person.getName();
            }
        }

        private final Map<String, Person> smallCrowd;

        // ...
    }

## 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>