[ 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 | Salary | Actions
--- | --- | ---
Name Address | $Salary |

### Edit Person

Name: |
Salary: | $
Address: |
(ID=-1)

## Creating the table

This demo introduces a number of features, some of which are new to DWR 2.0.

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

A Person is just a POJO containing an name and address fields along with a salary as a float and an id as an int. 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";

Finally thing 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, salary: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>Salary</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="tableSalary">Salary</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>Salary:</td>
        <td>$<input id="salary" type="text" size="20"/></td>
      </tr>
      <tr>
        <td>Address:</td>
        <td><input type="text" id="address" size="40"/></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() {
      fillTable();
    }

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

    function fillTable() {
      People.getAllPeople(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("tableSalary" + id, person.salary);
          dwr.util.setValue("tableAddress" + id, person.address);
          $("pattern" + id).style.display = "table-row";
          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({ id:id });
        fillTable();
        dwr.engine.endBatch();
      }
    }

    function writePerson() {
      var person = { id:viewed, name:null, address:null, salary: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 {
        // Code to create a random set of people omitted

        public Set getAllPeople() {
            return people;
        }

        public void setPerson(Person person) {
            if (person.getId() == -1) {
                person.setId(getNextId());
            }

            people.remove(person);
            people.add(person);
        }

        public void deletePerson(Person person) {
            people.remove(person);
        }

        private Set people = new HashSet();
    }

    public class Person
    {
        private int id;
        private String name;
        private String address;
        private float salary;

        // Getters, setters, equals and toString omitted
    }

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