newbie : Accessing specific form elements' values from a controller.

1,296 views
Skip to first unread message

Salvation

unread,
Feb 4, 2012, 6:41:39 AM2/4/12
to web2py-users
Hi!
I have a html form in my default view. I don't want to create form
elements from my controller, but use pure HTML where possible. How can
I
1. Access the form elements, and their values into my controller, say
default.py. (something like GetElementById )
2. Detect if the form has been submitted, so that I can use the values
I Accessed.

I went through many questions here, but couldn't work it out.

My View:

<form id="mainForm" class="well form-search">
<legend>Search Videos</legend>
<span class="input">
<input type="text" size="45" name="search_keyword"
id="searchKeyword" class="xlarge">
</span>

<span class="formactions">
<button class="btn primary" type="submit">Search</
button>
</span>
</form>

My Controller:

def index():
# is form submitted ?
# if Yes
# Access the form
# get the value inside the searchKeyword text box
# Use it elsewhere
# else
# display the form and wait

I have a feeling that this is not the correct approach. Please feel
free to point me in the right direction.

Thank You.

Anthony

unread,
Feb 4, 2012, 10:41:10 AM2/4/12
to web...@googlegroups.com
When a form is submitted, the submitted values will be in request.post_vars as well as request.vars (the former is specifically for variables submitted via post requests, whereas the latter includes both post and get variables). So, you could do:

if request.vars:
    do something with request.vars.search_keyword
else:
    return dict()

However, if you want to take advantage of web2py's form creation and processing, you can use the FORM or SQLFORM.factory helpers as described here: http://web2py.com/books/default/chapter/29/7. In particular, if you want to write all the HTML manually but just use web2py's form processing in the controller, see:  http://web2py.com/books/default/chapter/29/7#SQLFORM-in-HTML (same would apply to using SQLFORM.factory). As an alternative to completely manual HTML, you might consider SQLFORM.factory along with http://web2py.com/books/default/chapter/29/7#Custom-forms.

Anthony

Carlos Costa

unread,
Feb 4, 2012, 10:43:13 AM2/4/12
to web...@googlegroups.com
I think you can do like this:

if request.vars:
use request.vars.varname to access values
else:
return .....

Since you point your form to the right actions the all the vars will
be there when you submit.
When you dont submit they will not be there.

2012/2/4 Salvation <timsin...@gmail.com>:

--
Carlos J. Costa
Cientista da Computação
Esp. Gestão em Telecom

EL MELECH NEEMAN!
אָמֵן

Reply all
Reply to author
Forward
0 new messages