I am trying to create a relationship between the User model of the play-authenticate module and my model - Books. I am using play 2.0.4 and I have integrated play-authenticate into my project. In my controllers/Application I have the getLocalUser method:
public static User getLocalUser(final Session session) {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session));
return localUser;
}
I am trying override Model's method in my Books model to save the user who adds/modify book records.
public void save() {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser(session());
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
The error I get when I do this, which I do not understand is:
The method session() is undefined for the type Books.
I'm not sure how this can be as I do have access to the controller/application methods because of my import:
import controllers.Application;
Update: *
public static Result createBook() {
Form<Book> filledForm = bookForm.bindFromRequest();
if(filledForm.hasErrors()) {
return badRequest(
views.html.bookCreator.render(Book.all(), filledForm)
);
}
else {
Book.create(filledForm.get());
//Book.save(getLocalUser(session()));
return redirect(routes.Application.createSuccess());
}
}*
First it is a very bad idea to call session() within your models classes, because if you do this, you'll create some kind of cyclic dependencies (presentation layer -> model -> presentation layer).
If you really want to keep it this way, just do this:
Controller:
public static User getLocalUser() {
final User localUser = User.findByAuthUserIdentity(PlayAuthenticate
.getUser(session()));
return localUser;
}
Model:
public void save() {
User logged = Application.getLocalUser();
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o) {
User logged = Application.getLocalUser();
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
But I'd prefer to do this:
Controller:
public Result anAction() {
...
save(getLocalUser(session()));
...
}
Model:
public void save(final User logged) {
if (logged != null) {
this.createUser = logged;
this.modifyUser = logged;
}
super.save();
}
public void update(Object o, final User logged) {
if (logged != null) {
this.modifyUser = logged;
}
super.update(o);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With