If you benefit from web2py hope you feel encouraged to pay it forward by contributing back to society in whatever form you choose!

Imagine a form divided in steps where user has to fill data and this data has to be validated for each step.

This Example is bases on default auth tables

For this example, please change in your model the following line

from:

auth.define_tables()

to

auth.define_tables(username=True)

Controllers

def step1():
    form=SQLFORM(db.auth_user,fields=['username','email'])
    if form.accepts(request.vars, dbio=False):
        session.step1=request.vars
        redirect('step2')
    return dict(form=form)

def step2():
    form=SQLFORM(db.auth_user,fields=['username','email','first_name','last_name'])    
    if request.post_vars:
        request.vars.update(session.step1)    
    if form.accepts(request.vars):
        session.flash=T("Data recorded")
        return redirect('index')
    return dict(form=form)

Views

Step1

{{extend 'layout.html'}}

<fieldset>
<legend>Passo 1</legend>

    {{=form.custom.begin}}

    <div>
        <label>Username</label>
        {{=form.custom.widget.username}}
    </div>

    <div>
        <label>Email</label>
        {{=form.custom.widget.email}}
    </div>

    <div>
    {{=form.custom.submit}}
    </div>
    {{=form.custom.end}}

</fieldset>

Step2

{{extend 'layout.html'}}

<fieldset>
<legend>Passo 2</legend>

    {{=form.custom.begin}}

    <div>
        <label>First name</label>
        {{=form.custom.widget.first_name}}
    </div>

    <div>
        <label>Last name</label>
        {{=form.custom.widget.last_name}}
    </div>

    <div>
    {{=form.custom.submit}}
    </div>
    {{=form.custom.end}}

</fieldset>

Conclusion

That was a simple trick on the use of session and dbio=False

  • At step1, defined only fields=['username','email'] for the SQLFORM and dbio=False in the form.accepts, we are going to show only that 2 fields, and the data will not be saved at this step because dbio is set to False.

  • The data will be passed to the step2 using the session.step1 variable which contains request.vars as value.

  • At step2, defined all fields, fields=['username','email','first_name','last_name'], the fitst two will be already filled by the user and we need to hide them.

  • Now it is time to update request.vars with the data in session and it is done in:

    if request.post_vars: request.vars.update(session.step1)

At the end, the form.accepts in step2 will record the data in the database.

Thanks to http://motanet.com.br/ for this nice example.

Related slices

Comments (0)


Hosting graciously provided by:
Python Anywhere