Custom CSS classes for SQLFORM widget input in web2py

前端 未结 1 518
谎友^
谎友^ 2021-02-06 18:23

Given this SQLFORM in the controller:

form = SQLFORM.factory(db.source_server, db.target_server)

with the following table definition:



        
相关标签:
1条回答
  • 2021-02-06 18:54

    Note, all widgets already have a class named for the type of widget (e.g., "string", "integer", "date", etc.) as well as an id of the form "tablename_fieldname", so you might be able to make use of those in your CSS without needing to add custom classes. See here for more details.

    If you do need to customize the classes, note that web2py FORM and SQLFORM objects and their sub-components are HTML helper objects and can be manipulated like any HTML helpers. In particular, helpers act as lists with respect to their components and dictionaries with respect to their attributes (an input class is an attribute of the INPUT object). So, you can do something like this, either in the controller that creates the form or in the view:

    form.custom.widget.field_name['_class'] = 'bla bla'
    

    If you need to change the class of all widgets of a particular type, you can also do that via the .elements() search functionality:

    for input in form.elements('input', _class='string'):
        input['_class'] = 'my-string'
    

    An additional option is to explicitly define a widget for the Field in the table definition, either using a custom widget or simply passing a _class attribute to one of the built-in widgets:

    Field('target_user', 'string', widget = lambda field, value:
        SQLFORM.widgets.string.widget(field, value, _class='my-string'))
    

    This method will affect all forms that include this field (unless you explictly remove or replace the widget before creating the form).

    0 讨论(0)
提交回复
热议问题