Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically fill a selectbox / dropdownbox in a form using web.py?

All web.py form examples are in the following format (from webpy.org):

myform = form.Form( 
    form.Textbox("boe"), 
    form.Textbox("bax", 
        form.notnull,
        form.regexp('\d+', 'Must be a digit'),
        form.Validator('Must be more than 5', lambda x:int(x)>5)),
    form.Textarea('moe'),
    form.Checkbox('curly'), 
    form.Dropdown('french', ['mustard', 'fries', 'wine'])) 

class index: 
    def GET(self): 
        form = myform()
        # make sure you create a copy of the form by calling it (line above)
        # Otherwise changes will appear globally
        return render.formtest(form)

    def POST(self): 
        form = myform() 
        if not form.validates(): 
            return render.formtest(form)
        else:
            # form.d.boe and form['boe'].value are equivalent ways of
            # extracting the validated arguments from the form.
            return "Grrreat success! boe: %s, bax: %s" % (form.d.boe, form['bax'].value)

I don't want to fill the dropdown box (form.Dropdown in the example above) static when declaring the form, but in the GET/POST method using entries retrieved from a database table when the page is called.

I've searched for a couple of hours but can't find a hint anywhere (google, webpy.org, google groups)

like image 783
ramdyne Avatar asked Jan 14 '11 23:01

ramdyne


3 Answers

You can declare form by passing empty list to form.Dropdown args, and then set args in your code.

# form declaration
MyForm = form.Form(form.Dropdown("french", []))

# then in your controller
my_form = MyForm()
my_form.french.args = ['mustard', 'fries', 'wine']

Also please don't use form for variable, because of the name clash with web.form.

like image 187
Andrey Kuzmin Avatar answered Nov 16 '22 17:11

Andrey Kuzmin


I know this was posted a while ago, but I did this by setting the value afterwards, as in:

form = input_form()
form.get('some_input').value = _id
return render.some_template(form)

This allows you to use the built-in validation as well if you please. I ended up finding an example like this on the boards, so it's probably kind of buried documentation wise.

like image 33
Dan Smith Avatar answered Nov 16 '22 16:11

Dan Smith


I suggest you create the other elements and the form, then in GET/POST create the dropdown element as you want and:

# Create copy of the form
form = myform()

# Append the dropdown to the form elements.
form.inputs = tuple(list(form.inputs) + [mydropdown])
like image 20
TryPyPy Avatar answered Nov 16 '22 16:11

TryPyPy