sirpercival
sirpercival

Reputation: 234

Conditional fields for a SQLFORM.factory in web2py

Say I construct a form using SQLFORM.factory like so:

my_fields = [Field('field1', default='some value'), 
             Field('field2', default = 'some other value')]
form = SQLFORM.factory(*my_fields)

Now I want field2 to show only if field equals some value. However, when I try to do something like:

my_fields[1].show_if = my_fields[0] == 'some value'

(before I actually make the factory) I get:

  File "/Applications/web2py.app/Contents/Resources/gluon/packages/dal/pydal/objects.py", line 1202, in __eq__
    return Query(db, db._adapter.EQ, self, value)
AttributeError: 'NoneType' object has no attribute '_adapter'

My guess is that show_if isn't working because it's a query, and I'm not actually using a table... but I don't have a table, which is why I'm using SQLFORM.factory. Any suggestions on how to make a field conditional in this case?

Upvotes: 1

Views: 975

Answers (1)

sirpercival
sirpercival

Reputation: 234

OK I figured it out.

If you examine the page source on the SQLFORM.factory form, you notice that the ids given are "no_table_field1" and "no_table_field2". So, stealingborrowing the code from the JQuery & Ajax chapter of the web2py book, I add this to the end of the relevant view:

<script>
jQuery(document).ready(function(){
   if(jQuery('#no_table_field1').prop('value') == 'some value')
        jQuery('#no_table_field2__row').show();
   else jQuery('#no_table_field2__row').hide();
   jQuery('#no_table_field1').change(function(){
        if(jQuery('#no_table_field1').prop('value') == 'some value')
             jQuery('#no_table_field2__row').show();
        else jQuery('#no_table_field2__row').hide();});
});
</script>

and it works beautifully. (Not a smooth transition, but it works.)

Upvotes: 3

Related Questions