Play! how to make master-detail views

Continuing the taks tutorial project, we will add details to tasks. The detail will be a list of events on a task to make an history of what happened.

First we will add the Event class. If you use Eclipse and the Play! plugin, you can use the new play! menu :

The new Eclipse menu when the Play! plugin is installed

The class will be very simple for this how-to :

package models;

import play.*;
import play.db.jpa.*;

import javax.persistence.*;
import java.util.*;

@Entity
public class Event extends Model {
    public String status;
    public Date eventDate;
}

Then we add the link between Task and Event; add this property to Task :

	@OneToMany
	public List<Event> events;

Now we will add a link in the current view to show the detail view, add a column with a html link :

			<td><a href="@{task(task.id)}">&gt;</a></td>

Now we have to had the controller action task in Application :

    public static void task(Long id) {
    	Task task = Task.findById(id);
    	render(task);
    }

Last action is to write the task.html template. It will be very similar to the index template, except we will use the template tag on the events property of the rendered task object :

#{extends 'main.html' /}
#{set title:'task history' /}

<table>
	<thead>
		<tr>
			<th class="event">status</th>
			<th class="date">when</th>
		</tr>
	</thead>
	<tbody>
		#{list task.events, as:'event'}

		
	    <tr class="event" transferId="${event.id}" >
   			<td id="status-${event.id}">${event.status}</td>
   			<td id="when-${event.id}">${event.eventDate}</td>
   		</tr>

	    #{/list}
	    <tr>
	        #{form @saveEvent(task.id)}
	        <td><input type="text" name="event.status"></td>
	        <td><input type="text" name="event.when"></td>
	        <td><input type="submit" value="+"></td>
			#{/form}
	    </tr>
	</tbody>
</table>

The important part is the save action; here we pass the id of the master object as it will be used in the save action in the controller. So here is the save action in Application :

    public static void saveEvent(Long id, final Event event) {
    	Task task = Task.findById(id);
    	event.save();
    	task.events.add(event);
    	task.save();
    	task(id);    	
    }

In the controller,
we get back a reference to the master object (via the id passed from the view),
we save the event entered in the form
we add it to the events list property of the master
we then save the master object
and we call again the action to show the detail of the task.

So here is our master-detail views how to finished
.

Advertisements

About this entry