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

writing a modular app in web2py

this app should allow the creation of items, it should show a list of items that is dynamically updated if an item is created or if an item changes. The item list should contain links that allow the editing of items.


the controller

controllers/default.py

def index():
    'index will load the list and the create/edit forms as components'
    return dict()

def list_items():
    'shows a list of items that were created, each items is clickable and can be edited'
    return dict(itemlist = db(db.mytable.id>0).select())

def create_edit():
    'return a creation form if no item is specified, return an edit form if the item is known'
    item = get_item(request.args(0))
    if item:  form = crud.update(db.mytable, item)
    else:     form = crud.create(db.mytable)

    if form.accecpts(reques.vars, session):#item created or item changed
        response.headers['web2py-component-command'] = \
            'web2py_ajax_page("GET","%s","","show_itemlist")' % \
            URL(r=request,f='list_items')
         #this will update the component that is in a div with the id 
         #show_itemlist, the URL specifies what content should be loaded into the div

    return dict(form = form)

the views

index views/default/index.html

first die item list is loaded into a div with the id show_itemlist (this is done by LOAD)

then a link is created that will load the creation form (no item specified while calling creat_edit) into the div below

{{=LOAD('default', 'list_items', ajax = True, target = 'show_itemlist')}}
<a onlclick="web2py_component({{=URL(r=request, f='create_edit')}},'show_edit_create');" href='#'>create</a>
<div id="show_edit_create">click create or item on list</div>

list_items views/default/list_items.html

each item on the item list will load the specified URL into the div with the id show_edit_create

<ul>
{{for item in itemlist:}}{{=LI('edit %s'%item.name, _onclick="web2py_component(\'%s\', \'show_edit_create\')"%URL(r=request, f='create_edit', args=[item.id]))}}{{pass}}
</ul>

create_edit views/default/create_edit.html

{{=form}}

Related slices

Comments (2)


Hosting graciously provided by:
Python Anywhere