Transferring information from one page to another

2019-08-28 01:27发布

问题:

I'm trying to create a signup page for a website. The signup process has 2 stages:

  1. The user enters their name, email, password on a form on a page. They click next, then

  2. The user enters additional information on a new page (maybe upload a photo, whatever) and clicks submit.

All this information (from page 1 and 2) is then used to create a new user. How can one store information from one page to another?

One way that could work might be to create extra fields in the form on the second page and fill them with info from the first one, but it seems a bit hacky. Is there a recommended way to go about it?

回答1:

You don't need to use Form.class for each interaction with user, it's nice helper, but... just helper.

Divide your registration process to few actions, each will be responsible for editing only part of the model

  1. Your first - default view should be largest and should use Form.class and Constraints annotations for validating data. Of course you'll need additional actions' set like new/create or edit/update etc. After sending that form, the account is saved in DataBase, so you can just make changes to it in other actions identifying it by unique ID.
  2. Your next view (let's say that's only change password form) can use other Form.class BUT if it's quite easy and has special validation rules (like password strange etc.) you can just use ie. editPassword/updatePasswordset of actions and update your user object manually:

    public static Result updatePassword(Integer user_id){
        User user = User.find.byId(user_id);
        DynamicForm formData = form().bindFromRequest();
    
        if (!customValidatorMethod(formData.password)){
             return badRequest("Password was not changed");
        }
    
        user.password = formData.password;
        user.update(user_id);
        return ok("Password changed);
    }
    

Next you can create as many steps as you want.

Note: Don't save username and password in session data, cause some smartie can use it against his boss.... Instead use id of the user created in first step, additional you can add simple fields like registrationStep or registrationId (random hash) for identifying new user between all required registration steps. You'll remove that session data after full registration process, meanwhile you can check if user finished registration by simple checking the step number.



回答2:

The way I would do this is create the User object and store it in the database as soon as the first form is submitted, as this lets the user come back later if it is too much hassle.

You could also use session() to store it temporarily if you don't mind losing statelessness.

session("username", USERS_CHOSEN_NAME);
session("password", USERS_CHOSEN_PASSWORD);