Here is the proof of concept I am using.
models/db.py
db.define_table('customer',
db.Field('name'),
db.Field('phone'),
migrate=True,
)
db.define_table('product',
db.Field('name'),
migrate=True,
)
db.define_table('purchase',
Field('date'),
Field('customer_id',
requires = IS_IN_DB(db, 'customer.id', '%(name)s')
),
Field('product_id',
requires = IS_IN_DB(db, 'product.id', '%(name)s')
),
migrate=True,
)
controllers/customer.py
def search():
customer = None
form = SQLFORM.factory(
Field('phone',
requires=IS_NOT_EMPTY(),
),
Field('customer_id','hidden'),
)
if form.accepts(request.vars, session):
rows = db(db.customer.phone==form.vars.phone).select()
if len(rows) > 0:
customer = rows[0]
else:
response.flash = 'Customer not found.'
return dict(form=form, customer=customer)
views/customer/search.load
{{=form}}
{{if customer:}}
<dd>
<li>Name: {{=customer.name}}</li>
</dd>
{{pass}}
controllers/default.py
def index():
form = SQLFORM.factory(
Field('product_id',
requires=IS_IN_DB(db, 'product.id', '%(name)s'),
),
Field('customer_id','hidden'),
)
if form.accepts(request.vars, session):
db.purchase.insert(
product_id=form.vars.product_id,
customer_id=form.vars.customer_id,
)
response.flash = 'Purchase added'
return dict(form=form)
views/default/index.html
{{extend 'layout.html'}}
<fieldset id="Customer">
<legend>Customer</legend>
{{=LOAD('customer', f='search.load', ajax=True)}}
</fieldset>
<fieldset id="Product">
<legend>Product</legend>
{{=form}}
</fieldset>
Enter a phone number in the input and submit. The customer search
looks up the customer and displays the name. Select a product and
submit, and the purchase record is created using the customer id from
the customer found in the customer search. But how to get the customer
id from the widget to the form?
This is a very simple example. I intend to improve the customer
search. For example, display more info than the name, handle phone
numbers not in the database, allow the user to add it on the spot, and
edit an existing user.
The widget could be inserted in any form that requires a customer to
be selected.
If I am able to get this to work, I will be looking at other widgets
that involve mulitple inputs, so multiple values have to be passed to
the main page form.