Search code examples
data-access-layercrudnested-formsweb2pyabstraction

Generate a nested CRUD form


From a logical perspective it sometime doesn't make sense, for example, to add an Address before you add a Customer.

db.define_table('address',
   Field('line1','string', required=True),
   Field('line2','string'),
   Field('suburb','string', required=True),
   Field('post_code','integer'),
   Field('email','string')
)

db.address.post_code.requires = IS_INT_IN_RANGE(0000, 9999)
db.address.email.requires     = IS_EMAIL()

db.define_table('customer',
   Field('name', 'string', required=True, unique=True),
   Field('locations', 'list:reference db.address', required=True),
   Field('comment', 'string')
) # quick aside: how would I ensure there isn't another customer with same name+location?

db.address.requires = IS_IN_DB(db, db.address, '%(line1)s' + ', ' + '%(suburb)s', multiple=True)

So if I could generate one form that allows you to create a customer, complete with address, the management would become much more logical.

However it would still be useful to be able to pick from records already in the db, but to just have an "Add" button—rolling down with javascript—which will open by default if field is empty (and .requires not to be).

How would I generate this nested CRUD?

Thanks for all suggestions


Solution

  • I believe that this topic in the official book covers it somewhat:

    http://web2py.com/books/default/chapter/29/7#One-form-for-multiple-tables

    Basically, you have to use sqlform.factory. Your controller will call the insert on the address first, then get that ID for the address, and then using that ID, call the insert on the customer.

    That handles your adds, but not a dropdown, unfortunately. You would need to write your own html as far as that's concerned. No automatic CRUD.