Created
May 29, 2012 07:44
-
-
Save danielberndt/2823156 to your computer and use it in GitHub Desktop.
Crud Controller
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public abstract class CrudController<T extends Model> { | |
protected Form<T> form; | |
private Template1<Form<T>,Html> composeTemplate; | |
private Template1<T,Html> showTemplate; | |
private Template2<T,Form<T>,Html> editTemplate; | |
private Template1<List<T>,Html> listTemplate; | |
private Finder<Long,T> finder; | |
public CrudController(Class<T> clazz, | |
Template1<List<T>,Html> listTemplate, | |
Template1<Form<T>,Html> composeTemplate, | |
Template1<T,Html> showTemplate, | |
Template2<T,Form<T>,Html> editTemplate, | |
Finder<Long,T> finder) { | |
this.form = Controller.form(clazz); | |
this.listTemplate = listTemplate; | |
this.composeTemplate = composeTemplate; | |
this.showTemplate = showTemplate; | |
this.editTemplate = editTemplate; | |
this.finder = finder; | |
} | |
protected abstract T createFromForm(T element, Long... preIds); | |
protected abstract Call redirectToItem(T element); | |
protected abstract Call redirectToList(); | |
protected T getFromId(Long id) { | |
return finder.byId(id) | |
}; | |
public final Result list() { | |
return Controller.ok(listTemplate.render(finder.all())); | |
} | |
public final Result compose() { | |
return Controller.ok(composeTemplate.render(form)); | |
} | |
public final Result create() { | |
... | |
return Controller.redirect(redirectToItem(newElement)); | |
} | |
public final Result item(Long id) { | |
T element = getFromId(id); | |
if (element==null) return Controller.notFound(); | |
return Controller.ok(itemTemplate.render(element)); | |
} | |
public final Result edit(Long id) { | |
... | |
return Controller.ok(editTemplate.render(form.fill(element), element)); | |
} | |
public final Result update(Long id) { | |
... | |
return Controller.redirect(redirectToItem(editedItem)); | |
} | |
public final Result delete(Long id) { | |
... | |
return Controller.redirect(redirectToList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment