Custom CSS classes for SQLFORM widget input in web2py

你。 提交于 2020-01-12 03:53:28

问题


Given this SQLFORM in the controller:

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

with the following table definition:

db.define_table('target_server',
                Field('target_url', 'string'),
                Field('target_user', 'string'),
                Field('target_password', 'password'))
db.define_table('target_server',
                Field('target_url', 'string'),
                Field('target_user', 'string'),
                Field('target_password', 'password'))

how can I apply custom CSS classes for each form widget <input> element?

  {{=form.custom.begin}}
  <fieldset>
    <legend>Source Server</legend>
    <div class="clearfix">
      <label for="source_url">URL:</label>
      <div class="input">

        <input class="bla bla" name="field_name">

      </div>
    </div>
  ...
  {{=form.custom.end}}

回答1:


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).



来源:https://stackoverflow.com/questions/8661166/custom-css-classes-for-sqlform-widget-input-in-web2py

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!