Fred K
Fred K

Reputation: 13910

Passing argument from Controller to Action

I've created the action OnlyOwner with action composition that gets two users and has to return them to the controller. Here the code explained:

Controller

@With(OnlyOwner.class) // Call to the action
public static Result profile(Long id) {
    return ok(profile.render(user, userLogged));
}

Action

public class OnlyOwner extends Action.Simple{

    @Override
    public Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
        // Here I'm trying to get the Long id passed to che controller
        Long id = (Long)ctx.args.get("id"); // but this retrieves a null
        User user = User.findById(id);
        User userLogged = // Here I get another user
        // Now I want to return both the users to the controller
    }
}

What is the code to do that?

Upvotes: 3

Views: 983

Answers (1)

Schleichardt
Schleichardt

Reputation: 7542

You have to put the objects into the args of the HTTP context: http://www.playframework.com/documentation/2.2.x/api/java/play/mvc/Http.Context.html#args

public class Application extends Controller {

    @With(OnlyOwner.class)
    public static Result profile(Long id) {
        return ok(profile.render(user(), userLogged()));//method calls
    }

    private static User user() {
        return getUserFromContext("userObject");
    }

    private static User userLogged() {
        return getUserFromContext("userLoggedObject");
    }

    private static User getUserFromContext(String key) {
        return (User) Http.Context.current().args.get(key);
    }
}


public class OnlyOwner extends Action.Simple {
    @Override
    public Promise<SimpleResult> call(Http.Context ctx) throws Throwable {
        //if you have id not as query parameter (http://localhost:9000/?id=43443) 
        //but as URL part (http://localhost:9000/users/43443) you will have to parse the URL yourself
        Long id = Long.parseLong(ctx.request().getQueryString("id"));
        ctx.args.put("userObject", User.findById(id));
        ctx.args.put("userLoggedObject", User.findById(2L));
        return delegate.call(ctx);
    }
}

Upvotes: 2

Related Questions