How to improve a widget select list that allows new options to be added?

17 views
Skip to first unread message

AGRogers

unread,
Aug 18, 2020, 8:32:57 AM8/18/20
to web...@googlegroups.com
Hi

I want a drop down list that shows all the values from existing records AND allows the user to add a new value if they want.

I have got something working using https://select2.org/ . But my approach is questionable.

The problem i have is that when a new value is added and the form is submitted, the widget code is called *before* the new value is persisted to the database. So when the form reloads after successfully being processed, the dropdown doesn't have the new item and so can't be displayed.

If i then reload the page the new item is included and all is well.

I got around this by delaying the creation of the Select2 dropdown. Instead of the widget immediately building the Select2 it executes an AJAX call which grabs the dropdown data and then builds it. Of course this is done after the form has been accepted so it has the new entry and all works well.

Is this the best way to do it?

Or can i somehow set the widget **after** the form has been created?

Thanks
Andrew

Clemens

unread,
Aug 18, 2020, 8:50:37 AM8/18/20
to web2py-users
Hi,

not sure, what kind of form you're using. Expecting you use SQLFORM, I solved this in similar case as follows:
form[0].insert(-1, TR(TD(LABEL(T('City')),
                      TD(SELECT(_name='city', *[OPTION('{} {}'.format(city.code, city.name), _value=city.id)
                         for city in db(db.city.id>0).select(db.city.ALL, orderby=city.code)], value=this_city.id)))))

this_city a preselected value and the one matching the record currently processed.

Since on reload (after submit) the db is requested again, the select list should be updated.


Have a try, hope it helps!

Best regards
Clemens
Reply all
Reply to author
Forward
0 new messages