2

I have a CRUD form that has a select widget. The options in the widget are dynamic. I cannot use tags, as the values are coming from other tables. I am trying to change the values in the controller using this method:

def change_widget(form, id, widget):
"Tries to find a widget in the given form with the given id and swaps it with the given widget"
for i in range( len(form[0].components) ):
    if hasattr(form[0].components[i].components[1].components[0], 'attributes'):
        if '_id' in form[0].components[i].components[1].components[0].attributes:
            if form[0].components[i].components[1].components[0].attributes['_id'] == id:
                form[0].components[i].components[1].components[0] = widget
                return True

return False

After I call the method and inspect the form, I can see that the form has been successfully modified. On the view side, I'm using a custom view and trying to display the form like so:

{{=form.custom.begin}} {{=form.custom.widget.customized_field}}
{{=form.custom.submit}} {{=form.custom.end}}

But, it still shows me the original unmodified widget. What am I doing wrong? Is there a better way to do this?

naveed
  • 1,395
  • 2
  • 15
  • 29

1 Answers1

4

First, here's a much easier way to replace the widget:

form.element(_id=id).parent[0] = widget

However, because you are completely replacing the original widget with a new widget object rather than simply modifying the original widget, form.custom.widget.customized_field will still refer to the original widget. So, you have to explicitly replace form.custom.widget.customized_field as well. Try:

def change_widget(form, name, widget):
    form.element(_name=name).parent[0] = form.custom.widget[name] = widget

where name is the name of the field.

See here for more about searching the server-side DOM.

Also, note that you can specify a custom widget for the field before the form is even created, either within the table definition, or afterward:

db.define_table('mytable', Field('myfield', widget=custom_widget))

or

db.mytable.myfield.widget = custom_widget

Then when you create a form, the custom widget will be used rather than the default widget.

See here for more about widgets.

Anthony
  • 25,466
  • 3
  • 28
  • 57