Example #1
0
 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL
     BUTTON = TAG.button
     admin = URL("admin",
                 "default",
                 "design",
                 args=current.request.application)
     from gluon.dal import thread
     dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \
                            for row in i.db._timings]) \
                    for i in thread.instances]
     u = web2py_uuid()
     return DIV(
         BUTTON('design', _onclick="document.location='%s'" % admin),
         BUTTON('request',
                _onclick="jQuery('#request-%s').slideToggle()" % u),
         DIV(BEAUTIFY(current.request),
             _class="hidden",
             _id="request-%s" % u),
         BUTTON('session',
                _onclick="jQuery('#session-%s').slideToggle()" % u),
         DIV(BEAUTIFY(current.session),
             _class="hidden",
             _id="session-%s" % u),
         BUTTON('response',
                _onclick="jQuery('#response-%s').slideToggle()" % u),
         DIV(BEAUTIFY(current.response),
             _class="hidden",
             _id="response-%s" % u),
         BUTTON('db stats',
                _onclick="jQuery('#db-stats-%s').slideToggle()" % u),
         DIV(BEAUTIFY(dbstats), _class="hidden", _id="db-stats-%s" % u),
         SCRIPT("jQuery('.hidden').hide()"))
    def widget(field, value, download_url=None, **attributes):
        """
        generates a INPUT file tag.

        Optionally provides an A link to the file, including a checkbox so
        the file can be deleted.
        All is wrapped in a DIV.

        see also: :meth:`FormWidget.widget`

        :param download_url: Optional URL to link to the file (default = None)
        """

        default = dict(_type='file', )
        attr = UploadWidget._attributes(field, default, **attributes)

        inp = INPUT(**attr)

        if download_url and value:
            url = download_url + '/' + value
            (br, image) = ('', '')
            if UploadWidget.is_image(value):
                br = BR()
                image = IMG(_src=url, _width=UploadWidget.DEFAULT_WIDTH)
            inp = DIV(
                inp, '[', A(UploadWidget.GENERIC_DESCRIPTION, _href=url), '|',
                INPUT(_type='checkbox',
                      _name=field.name + UploadWidget.ID_DELETE_SUFFIX),
                'delete]', br, image)
        return inp
 def __call__(self, field, value, **attributes):
     default = dict(
         _type='text',
         value=(value != None and str(value)) or '',
     )
     attr = StringWidget._attributes(field, default, **attributes)
     div_id = self.keyword + '_div'
     attr['_autocomplete'] = 'off'
     if self.is_reference:
         key2 = self.keyword + '_aux'
         key3 = self.keyword + '_auto'
         attr['_class'] = 'string'
         name = attr['_name']
         if 'requires' in attr: del attr['requires']
         attr['_name'] = key2
         value = attr['value']
         record = self.db(self.fields[1] == value).select(
             self.fields[0]).first()
         attr['value'] = record and record[self.fields[0].name]
         attr['_onblur']="jQuery('#%(div_id)s').delay(3000).fadeOut('slow');" % \
             dict(div_id=div_id,u='F'+self.keyword)
         attr['_onkeyup'] = "jQuery('#%(key3)s').val('');var e=event.which?event.which:event.keyCode; function %(u)s(){jQuery('#%(id)s').val(jQuery('#%(key)s :selected').text());jQuery('#%(key3)s').val(jQuery('#%(key)s').val())}; if(e==39) %(u)s(); else if(e==40) {if(jQuery('#%(key)s option:selected').next().length)jQuery('#%(key)s option:selected').attr('selected',null).next().attr('selected','selected'); %(u)s();} else if(e==38) {if(jQuery('#%(key)s option:selected').prev().length)jQuery('#%(key)s option:selected').attr('selected',null).prev().attr('selected','selected'); %(u)s();} else if(jQuery('#%(id)s').val().length>=%(min_length)s) jQuery.get('%(url)s?%(key)s='+escape(jQuery('#%(id)s').val()),function(data){if(data=='')jQuery('#%(key3)s').val('');else{jQuery('#%(id)s').next('.error').hide();jQuery('#%(div_id)s').html(data).show().focus();jQuery('#%(div_id)s select').css('width',jQuery('#%(id)s').css('width'));jQuery('#%(key3)s').val(jQuery('#%(key)s').val());jQuery('#%(key)s').change(%(u)s);jQuery('#%(key)s').click(%(u)s);};}); else jQuery('#%(div_id)s').fadeOut('slow');" % \
             dict(url=self.url,min_length=self.min_length,
                  key=self.keyword,id=attr['_id'],key2=key2,key3=key3,
                  name=name,div_id=div_id,u='F'+self.keyword)
         return TAG[''](INPUT(**attr),
                        INPUT(_type='hidden',
                              _id=key3,
                              _value=value,
                              _name=name,
                              requires=field.requires),
                        DIV(_id=div_id, _style='position:absolute;'))
     else:
         attr['_name'] = field.name
         attr['_onblur']="jQuery('#%(div_id)s').delay(3000).fadeOut('slow');" % \
             dict(div_id=div_id,u='F'+self.keyword)
         attr['_onkeyup'] = "var e=event.which?event.which:event.keyCode; function %(u)s(){jQuery('#%(id)s').val(jQuery('#%(key)s').val())}; if(e==39) %(u)s(); else if(e==40) {if(jQuery('#%(key)s option:selected').next().length)jQuery('#%(key)s option:selected').attr('selected',null).next().attr('selected','selected'); %(u)s();} else if(e==38) {if(jQuery('#%(key)s option:selected').prev().length)jQuery('#%(key)s option:selected').attr('selected',null).prev().attr('selected','selected'); %(u)s();} else if(jQuery('#%(id)s').val().length>=%(min_length)s) jQuery.get('%(url)s?%(key)s='+escape(jQuery('#%(id)s').val()),function(data){jQuery('#%(id)s').next('.error').hide();jQuery('#%(div_id)s').html(data).show().focus();jQuery('#%(div_id)s select').css('width',jQuery('#%(id)s').css('width'));jQuery('#%(key)s').change(%(u)s);jQuery('#%(key)s').click(%(u)s);}); else jQuery('#%(div_id)s').fadeOut('slow');" % \
             dict(url=self.url,min_length=self.min_length,
                  key=self.keyword,id=attr['_id'],div_id=div_id,u='F'+self.keyword)
         return TAG[''](INPUT(**attr),
                        DIV(_id=div_id, _style='position:absolute;'))
 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL
     BUTTON = TAG.button
     admin = URL("admin","default","design",
                 args=current.request.application)
     from gluon.dal import thread
     if hasattr(thread,'instances'):
         dbstats = [TABLE(*[TR(PRE(row[0]),'%.2fms' % (row[1]*1000)) \
                                for row in i.db._timings]) \
                        for i in thread.instances]
         dbtables = dict([(i.uri, {'defined': sorted(list(set(i.db.tables) - 
                                              set(i.db._LAZY_TABLES.keys()))) or
                                              '[no defined tables]',
                                   'lazy': sorted(i.db._LAZY_TABLES.keys()) or
                                           '[no lazy tables]'})
                          for i in thread.instances])
     else:
         dbstats = [] # if no db or on GAE
         dbtables = {}
     u = web2py_uuid()
     return DIV(
         BUTTON('design',_onclick="document.location='%s'" % admin),
         BUTTON('request',_onclick="jQuery('#request-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.request),_class="hidden",_id="request-%s"%u),
         BUTTON('session',_onclick="jQuery('#session-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.session),_class="hidden",_id="session-%s"%u),
         BUTTON('response',_onclick="jQuery('#response-%s').slideToggle()"%u),
         DIV(BEAUTIFY(current.response),_class="hidden",_id="response-%s"%u),
         BUTTON('db tables',_onclick="jQuery('#db-tables-%s').slideToggle()"%u),
         DIV(BEAUTIFY(dbtables),_class="hidden",_id="db-tables-%s"%u),
         BUTTON('db stats',_onclick="jQuery('#db-stats-%s').slideToggle()"%u),
         DIV(BEAUTIFY(dbstats),_class="hidden",_id="db-stats-%s"%u),
         SCRIPT("jQuery('.hidden').hide()")
         )
Example #5
0
 def toolbar(self):
     from html import DIV, SCRIPT, BEAUTIFY, TAG, URL, A
     BUTTON = TAG.button
     admin = URL("admin",
                 "default",
                 "design",
                 args=current.request.application)
     from gluon.dal import DAL
     dbstats = []
     dbtables = {}
     infos = DAL.get_instances()
     for k, v in infos.iteritems():
         dbstats.append(
             TABLE(*[
                 TR(PRE(row[0]), '%.2fms' % (row[1] * 1000))
                 for row in v['dbstats']
             ]))
         dbtables[k] = dict(defined=v['dbtables']['defined']
                            or '[no defined tables]',
                            lazy=v['dbtables']['lazy']
                            or '[no lazy tables]')
     u = web2py_uuid()
     backtotop = A('Back to top', _href="#totop-%s" % u)
     return DIV(BUTTON('design', _onclick="document.location='%s'" % admin),
                BUTTON('request',
                       _onclick="jQuery('#request-%s').slideToggle()" % u),
                BUTTON('response',
                       _onclick="jQuery('#response-%s').slideToggle()" % u),
                BUTTON('session',
                       _onclick="jQuery('#session-%s').slideToggle()" % u),
                BUTTON('db tables',
                       _onclick="jQuery('#db-tables-%s').slideToggle()" %
                       u),
                BUTTON('db stats',
                       _onclick="jQuery('#db-stats-%s').slideToggle()" % u),
                DIV(BEAUTIFY(current.request),
                    backtotop,
                    _class="hidden",
                    _id="request-%s" % u),
                DIV(BEAUTIFY(current.session),
                    backtotop,
                    _class="hidden",
                    _id="session-%s" % u),
                DIV(BEAUTIFY(current.response),
                    backtotop,
                    _class="hidden",
                    _id="response-%s" % u),
                DIV(BEAUTIFY(dbtables),
                    backtotop,
                    _class="hidden",
                    _id="db-tables-%s" % u),
                DIV(BEAUTIFY(dbstats),
                    backtotop,
                    _class="hidden",
                    _id="db-stats-%s" % u),
                SCRIPT("jQuery('.hidden').hide()"),
                _id="totop-%s" % u)
    def __init__(self,
                 table,
                 record=None,
                 deletable=False,
                 linkto=None,
                 upload=None,
                 fields=None,
                 labels=None,
                 col3={},
                 submit_button='Submit',
                 delete_label='Check to delete:',
                 showid=True,
                 readonly=False,
                 comments=True,
                 keepopts=[],
                 ignore_rw=False,
                 record_id=None,
                 formstyle='table3cols',
                 **attributes):
        """
        SQLFORM(db.table,
               record=None,
               fields=['name'],
               labels={'name': 'Your name'},
               linkto=URL(r=request, f='table/db/')
        """

        self.ignore_rw = ignore_rw
        self.formstyle = formstyle
        nbsp = XML(' ')  # Firefox2 does not display fields with blanks
        FORM.__init__(self, *[], **attributes)
        ofields = fields
        keyed = hasattr(table, '_primarykey')

        # if no fields are provided, build it from the provided table
        # will only use writable or readable fields, unless forced to ignore
        if fields == None:
            fields = [
                f.name for f in table
                if (ignore_rw or f.writable or f.readable) and not f.compute
            ]
        self.fields = fields

        # make sure we have an id
        if self.fields[0] != table.fields[0] and \
                isinstance(table,Table) and not keyed:
            self.fields.insert(0, table.fields[0])

        self.table = table

        # try to retrieve the indicated record using its id
        # otherwise ignore it
        if record and isinstance(record, (int, long, str, unicode)):
            if not str(record).isdigit():
                raise HTTP(404, "Object not found")
            record = table._db(table.id == record).select().first()
            if not record:
                raise HTTP(404, "Object not found")
        self.record = record

        self.record_id = record_id
        if keyed:
            if record:
                self.record_id = dict([(k, record[k])
                                       for k in table._primarykey])
            else:
                self.record_id = dict([(k, None) for k in table._primarykey])
        self.field_parent = {}
        xfields = []
        self.fields = fields
        self.custom = Storage()
        self.custom.dspval = Storage()
        self.custom.inpval = Storage()
        self.custom.label = Storage()
        self.custom.comment = Storage()
        self.custom.widget = Storage()
        self.custom.linkto = Storage()

        for fieldname in self.fields:
            if fieldname.find('.') >= 0:
                continue

            field = self.table[fieldname]
            comment = None

            if comments:
                comment = col3.get(fieldname, field.comment)
            if comment == None:
                comment = ''
            self.custom.comment[fieldname] = comment

            if labels != None and fieldname in labels:
                label = labels[fieldname]
                colon = ''
            else:
                label = field.label
                colon = ': '
            self.custom.label[fieldname] = label

            field_id = '%s_%s' % (table._tablename, fieldname)

            label = LABEL(label,
                          colon,
                          _for=field_id,
                          _id=field_id + SQLFORM.ID_LABEL_SUFFIX)

            row_id = field_id + SQLFORM.ID_ROW_SUFFIX
            if field.type == 'id':
                self.custom.dspval.id = nbsp
                self.custom.inpval.id = ''
                widget = ''
                if record:
                    if showid and 'id' in fields and field.readable:
                        v = record['id']
                        widget = SPAN(v, _id=field_id)
                        self.custom.dspval.id = str(v)
                        xfields.append((row_id, label, widget, comment))
                    self.record_id = str(record['id'])
                self.custom.widget.id = widget
                continue

            if readonly and not ignore_rw and not field.readable:
                continue

            if record:
                default = record[fieldname]
            else:
                default = field.default

            cond = readonly or \
                (not ignore_rw and not field.writable and field.readable)

            if default and not cond:
                default = field.formatter(default)
            dspval = default
            inpval = default

            if cond:

                # ## if field.represent is available else
                # ## ignore blob and preview uploaded images
                # ## format everything else

                if field.represent:
                    inp = field.represent(default)
                elif field.type in ['blob']:
                    continue
                elif field.type == 'upload':
                    inp = UploadWidget.represent(field, default, upload)
                else:
                    inp = field.formatter(default)
            elif hasattr(field, 'widget') and field.widget:
                inp = field.widget(field, default)
            elif field.type == 'upload':
                inp = self.widgets.upload.widget(field, default, upload)
            elif field.type == 'boolean':
                inp = self.widgets.boolean.widget(field, default)
                if default:
                    inpval = 'checked'
                else:
                    inpval = ''
            elif OptionsWidget.has_options(field):
                if not field.requires.multiple:
                    inp = self.widgets.options.widget(field, default)
                else:
                    inp = self.widgets.multiple.widget(field, default)
                if fieldname in keepopts:
                    inpval = TAG[''](*inp.components)
            elif str(field.type).startswith('list'):
                inp = self.widgets.list.widget(field, default)
            elif field.type == 'text':
                inp = self.widgets.text.widget(field, default)
            elif field.type == 'password':
                inp = self.widgets.password.widget(field, default)
                if self.record:
                    dspval = PasswordWidget.DEFAULT_PASSWORD_DISPLAY
                else:
                    dspval = ''
            elif field.type == 'blob':
                continue
            else:
                inp = self.widgets.string.widget(field, default)

            xfields.append((row_id, label, inp, comment))
            self.custom.dspval[fieldname] = dspval or nbsp
            self.custom.inpval[fieldname] = inpval or ''
            self.custom.widget[fieldname] = inp

        # if a record is provided and found, as is linkto
        # build a link
        if record and linkto:
            for (rtable, rfield) in table._referenced_by:
                if keyed:
                    rfld = table._db[rtable][rfield]
                    query = urllib.quote(
                        str(rfld == record[rfld.type[10:].split('.')[1]]))
                else:
                    #                 <block>
                    query = urllib.quote(
                        str(table._db[rtable][rfield] == record.id))
                lname = olname = '%s.%s' % (rtable, rfield)
                if ofields and not olname in ofields:
                    continue
                if labels and lname in labels:
                    lname = labels[lname]
                widget = A(lname,
                           _class='reference',
                           _href='%s/%s?query=%s' % (linkto, rtable, query))
                xfields.append(
                    (olname.replace('.', '__') + SQLFORM.ID_ROW_SUFFIX, '',
                     widget, col3.get(olname, '')))
                self.custom.linkto[olname.replace('.', '__')] = widget


#                 </block>

# when deletable, add delete? checkbox
        self.custom.deletable = ''
        if record and deletable:
            widget = INPUT(
                _type='checkbox',
                _class='delete',
                _id=self.FIELDKEY_DELETE_RECORD,
                _name=self.FIELDNAME_REQUEST_DELETE,
            )
            xfields.append(
                (self.FIELDKEY_DELETE_RECORD + SQLFORM.ID_ROW_SUFFIX,
                 LABEL(delete_label,
                       _for=self.FIELDKEY_DELETE_RECORD,
                       _id=self.FIELDKEY_DELETE_RECORD +
                       SQLFORM.ID_LABEL_SUFFIX), widget,
                 col3.get(self.FIELDKEY_DELETE_RECORD, '')))
            self.custom.deletable = widget
        # when writable, add submit button
        self.custom.submit = ''
        if not readonly:
            widget = INPUT(_type='submit', _value=submit_button)
            xfields.append(
                ('submit_record' + SQLFORM.ID_ROW_SUFFIX, '', widget,
                 col3.get('submit_button', '')))
            self.custom.submit = widget
        # if a record is provided and found
        # make sure it's id is stored in the form
        if record:
            if not self['hidden']:
                self['hidden'] = {}
            if not keyed:
                self['hidden']['id'] = record['id']

        (begin, end) = self._xml()
        self.custom.begin = XML("<%s %s>" % (self.tag, begin))
        self.custom.end = XML("%s</%s>" % (end, self.tag))
        if formstyle == 'table3cols':
            table = TABLE()
            for id, a, b, c in xfields:
                td_b = self.field_parent[id] = TD(b, _class='w2p_fw')
                table.append(
                    TR(TD(a, _class='w2p_fl'),
                       td_b,
                       TD(c, _class='w2p_fc'),
                       _id=id))
        elif formstyle == 'table2cols':
            table = TABLE()
            for id, a, b, c in xfields:
                td_b = self.field_parent[id] = TD(b,
                                                  _class='w2p_fw',
                                                  _colspan="2")
                table.append(
                    TR(TD(a, _class='w2p_fl'),
                       TD(c, _class='w2p_fc'),
                       _id=id + '1',
                       _class='even'))
                table.append(TR(td_b, _id=id + '2', _class='odd'))
        elif formstyle == 'divs':
            table = TAG['']()
            for id, a, b, c in xfields:
                div_b = self.field_parent[id] = DIV(b, _class='w2p_fw')
                table.append(
                    DIV(DIV(a, _class='w2p_fl'),
                        div_b,
                        DIV(c, _class='w2p_fc'),
                        _id=id))
        elif formstyle == 'ul':
            table = UL()
            for id, a, b, c in xfields:
                div_b = self.field_parent[id] = DIV(b, _class='w2p_fw')
                table.append(
                    LI(DIV(a, _class='w2p_fl'),
                       div_b,
                       DIV(c, _class='w2p_fc'),
                       _id=id))
        elif type(formstyle) == type(lambda: None):
            table = TABLE()
            for id, a, b, c in xfields:
                td_b = self.field_parent[id] = TD(b, _class='w2p_fw')
                newrows = formstyle(id, a, td_b, c)
                if type(newrows).__name__ != "tuple":
                    newrows = [newrows]
                for newrow in newrows:
                    table.append(newrow)
        else:
            raise RuntimeError, 'formsyle not supported'
        self.components = [table]
Example #7
0
def LOAD(c=None, f='index', args=None, vars=None,
         extension=None, target=None,ajax=False,ajax_trap=False,
         url=None,user_signature=False, timeout=None, times=1,
         content='loading...',**attr):
    """  LOAD a component into the action's document

    Timing options:
    -times: An integer or string ("infinity"/"continuous")
    specifies how many times the component is requested
    -timeout (milliseconds): specifies the time to wait before
    starting the request or the frequency if times is greater than
    1 or "infinity".
    Timing options default to the normal behavior. The component
    is added on page loading without delay.
    """
    from html import TAG, DIV, URL, SCRIPT, XML
    if args is None: args = []
    vars = Storage(vars or {})
    target = target or 'c'+str(random.random())[2:]
    attr['_id']=target
    request = current.request
    if '.' in f:
        f, extension = f.rsplit('.',1)
    if url or ajax:
        url = url or URL(request.application, c, f, r=request,
                         args=args, vars=vars, extension=extension,
                         user_signature=user_signature)
        # timing options
        if isinstance(times, basestring):
            if times.upper() in ("INFINITY", "CONTINUOUS"):
                times = "Infinity"
            else:
                raise TypeError("Unsupported times argument %s" % times)
        elif isinstance(times, int):
            if times <= 0:
                raise ValueError("Times argument must be greater than zero, 'Infinity' or None")
        else:
            raise TypeError("Unsupported times argument type %s" % type(times))
        if timeout is not None:
            if not isinstance(timeout, (int, long)):
                raise ValueError("Timeout argument must be an integer or None")
            elif timeout <= 0:
                raise ValueError("Timeout argument must be greater than zero or None")
            statement = "web2py_component('%s','%s', %s, %s);" \
            % (url, target, timeout, times)
        else:
            statement = "web2py_component('%s','%s');" % (url, target)
        script = SCRIPT(statement, _type="text/javascript")
        if not content is None:
            return TAG[''](script, DIV(content,**attr))
        else:
            return TAG[''](script)

    else:
        if not isinstance(args,(list,tuple)):
            args = [args]
        c = c or request.controller
        other_request = Storage(request)
        other_request['env'] = Storage(request.env)
        other_request.controller = c
        other_request.function = f
        other_request.extension = extension or request.extension
        other_request.args = List(args)
        other_request.vars = vars
        other_request.get_vars = vars
        other_request.post_vars = Storage()
        other_response = Response()
        other_request.env.path_info = '/' + \
            '/'.join([request.application,c,f] + \
                         map(str, other_request.args))
        other_request.env.query_string = \
            vars and URL(vars=vars).split('?')[1] or ''
        other_request.env.http_web2py_component_location = \
            request.env.path_info
        other_request.cid = target
        other_request.env.http_web2py_component_element = target
        other_response.view = '%s/%s.%s' % (c,f, other_request.extension)

        other_environment = copy.copy(current.globalenv) ### NASTY

        other_response._view_environment = other_environment
        other_response.generic_patterns = \
            copy.copy(current.response.generic_patterns)
        other_environment['request'] = other_request
        other_environment['response'] = other_response

        ## some magic here because current are thread-locals

        original_request, current.request = current.request, other_request
        original_response, current.response = current.response, other_response
        page = run_controller_in(c, f, other_environment)
        if isinstance(page, dict):
            other_response._vars = page
            other_response._view_environment.update(page)
            run_view_in(other_response._view_environment)
            page = other_response.body.getvalue()
        current.request, current.response = original_request, original_response
        js = None
        if ajax_trap:
            link = URL(request.application, c, f, r=request,
                            args=args, vars=vars, extension=extension,
                            user_signature=user_signature)
            js = "web2py_trap_form('%s','%s');" % (link, target)
        script = js and SCRIPT(js,_type="text/javascript") or ''
        return TAG[''](DIV(XML(page),**attr),script)
Example #8
0
    def __init__(self,
                 table,
                 record=None,
                 deletable=False,
                 download="",
                 upload=None,
                 fields=None,
                 labels=None,
                 col3={},
                 submit_button='Submit',
                 delete_label='Check to delete:',
                 showid=True,
                 readonly=False,
                 comments=True,
                 keepopts=[],
                 ignore_rw=False,
                 formstyle='divs',
                 record_pk_name='_id',
                 tabs=[],
                 **attributes):
        """
        FORMBUILDER(db.table,
               record=None,
               fields=['name'],
               labels={'name': 'Your name'},
        """
        self.table = table
        if record:
            for itm in record:
                if isinstance(record[itm], (list, tuple)):
                    if not (itm in self.table.fields
                            and self.table[itm].type.startswith("list::")):
                        record[itm] = record[itm][-1]
        self.custom_file = upload
        self.ignore_rw = ignore_rw
        self.formstyle = formstyle
        self.record_pk_name = record_pk_name
        nbsp = XML('&nbsp;')  # Firefox2 does not display fields with blanks
        attributes.update({"_id": "hyform_%s" % self.table._tablename})
        FORM.__init__(self, *[], **attributes)
        ofields = fields

        # if no fields are provided, build it from the provided table
        # will only use writable or readable fields, unless forced to ignore
        if fields == None:
            fields = [
                f.name for f in table
                if (ignore_rw or f.writable or f.readable)
            ]

        self.record = record

        self.field_parent = {}
        xfields = {}
        xfields_keys = []
        self.fields = fields
        self.custom = Storage()
        self.custom.dspval = Storage()
        self.custom.inpval = Storage()
        self.custom.label = Storage()
        self.custom.comment = Storage()
        self.custom.widget = Storage()

        for fieldname in self.fields:
            if fieldname.find('.') >= 0:
                continue

            field = self.table[fieldname]
            comment = None

            if comments:
                comment = col3.get(fieldname, field.comment)
            if comment == None:
                comment = ''
            self.custom.comment[fieldname] = comment

            if labels != None and fieldname in labels:
                label = labels[fieldname]
                colon = ''
            else:
                label = field.label
                colon = ': '
            self.custom.label[fieldname] = label

            field_id = '%s_%s' % (table._tablename, fieldname)

            label = LABEL(label,
                          colon,
                          _for=field_id,
                          _id=field_id + FORMBUILDER.ID_LABEL_SUFFIX)

            row_id = field_id + FORMBUILDER.ID_ROW_SUFFIX

            if readonly and not ignore_rw and not field.readable:
                continue

            if record:
                default = record.get(fieldname, field.default)
            else:
                default = field.default

            cond = readonly or \
                (not ignore_rw and not field.writable and field.readable)

            if default and not cond:
                default = field.formatter(default)
            dspval = default
            inpval = default

            if cond:

                # ## if field.represent is available else
                # ## ignore blob and preview uploaded images
                # ## format everything else

                if field.represent:
                    inp = field.represent(default)
                elif field.type in ['blob']:
                    continue
                elif field.type == 'upload':
                    inp = UploadWidget.represent(field, default, download)
                elif field.type == 'boolean':
                    inp = self.widgets.boolean.widget(field,
                                                      default,
                                                      _disabled=True)
                else:
                    inp = field.formatter(default)
            elif field.type == 'upload':
                if hasattr(field, 'widget') and field.widget:
                    inp = field.widget(field, default, download)
                else:
                    inp = self.widgets.upload.widget(field, default, download)
            elif hasattr(field, 'widget') and field.widget:
                inp = field.widget(field, default)
            elif field.type == 'boolean':
                inp = self.widgets.boolean.widget(field, default)
                if default:
                    inpval = 'checked'
                else:
                    inpval = ''
            elif OptionsWidget.has_options(field):
                if not field.requires.multiple:
                    inp = self.widgets.options.widget(field, default)
                else:
                    inp = self.widgets.multiple.widget(field, default)
                if fieldname in keepopts:
                    inpval = TAG[''](*inp.components)
            elif field.type.startswith('list:'):
                inp = self.widgets.list.widget(field, default)
            elif field.type == 'text':
                inp = self.widgets.text.widget(field, default)
            elif field.type == 'hidden':
                inp = self.widgets.hidden.widget(field, default)
            elif field.type == 'password':
                inp = self.widgets.password.widget(field, default)
                if self.record:
                    dspval = PasswordWidget.DEFAULT_PASSWORD_DISPLAY
                else:
                    dspval = ''
            elif field.type == 'blob':
                continue
            else:
                inp = self.widgets.string.widget(field, default)
            xfields_keys.append(fieldname)
            xfields[fieldname] = (row_id, label, inp, comment)
            self.custom.dspval[fieldname] = dspval or nbsp
            self.custom.inpval[fieldname] = inpval or ''
            self.custom.widget[fieldname] = inp

        # when writable, add submit button
        self.custom.submit = ''
        if not readonly:
            widget = INPUT(_type='submit',
                           _class="submit",
                           _value=submit_button,
                           _id="submit_%s" % self.table._tablename)
            self.custom.submit = widget
        # if a record is provided and found
        # make sure it's id is stored in the form
        if record:
            if not self['hidden']:
                self['hidden'] = {}

        (begin, end) = self._xml()
        self.custom.begin = XML("<%s %s>" % (self.tag, begin))
        self.custom.end = XML("%s</%s>" % (end, self.tag))

        table = TAG['']()
        if formstyle == 'divs':
            # tabs = [
            #          {"tabname":"personal","caption":"个人信息","fields":["login","age"]},
            #          {"tabname":"comp","caption":"公司信息","fields":["login","age"]},
            #          {"tabname":"gf","caption":"朋友信息","fields":["login","age"]},
            #        ]
            if tabs:
                tab_headers = UL()
                tab_bodys = []

                for i, tab in enumerate(tabs):
                    tbody = DIV(_id="body_%s" % (tab.get("tabname", "")))
                    if i == 0:
                        li = LI(tab.get("caption", ""),
                                _class="active",
                                _id="tab_%s" % (tab.get("tabname", "")))
                        tbody['_class'] = "active"
                    else:
                        li = LI(tab.get("caption", ""),
                                _style="display:none;",
                                _id="tab_%s" % (tab.get("tabname", "")))
                        tbody['_style'] = "display:none;"
                    tab_headers.append(li)
                    for f in tab.get("fields", []):
                        if f in xfields_keys:
                            id, a, b, c = xfields[f]
                            div_b = self.field_parent[id] = DIV(
                                b, _class='w2p_fw')
                            tbody.append(
                                DIV(DIV(a, _class='w2p_fl'),
                                    div_b,
                                    DIV(c, _class='w2p_fc'),
                                    _id=id,
                                    _class="fb_row"))
                    tab_bodys.append(tbody)
                tab_headers = DIV(tab_headers,
                                  _id="tab_headers_%s" % self.table._tablename)
                tab_bodys = DIV(tab_bodys,
                                _id="tab_bodys_%s" % self.table._tablename)
                table.append(DIV(tab_headers, tab_bodys))
            else:
                for d in xfields_keys:
                    id, a, b, c = xfields[d]
                    div_b = self.field_parent[id] = DIV(b, _class='w2p_fw')
                    table.append(
                        DIV(DIV(a, _class='w2p_fl'),
                            div_b,
                            DIV(c, _class='w2p_fc'),
                            _id=id,
                            _class="fb_row"))

        self.components = [table, self.custom.submit]
Example #9
0
def LOAD(c=None,
         f='index',
         args=None,
         vars=None,
         extension=None,
         target=None,
         ajax=False,
         ajax_trap=False,
         url=None,
         user_signature=False,
         timeout=None,
         times=1,
         content='loading...',
         post_vars=Storage(),
         **attr):
    """  LOADs a component into the action's document

    Args:
        c(str): controller
        f(str): function
        args(tuple or list): arguments
        vars(dict): vars
        extension(str): extension
        target(str): id of the target
        ajax(bool): True to enable AJAX bahaviour
        ajax_trap(bool): True if `ajax` is set to `True`, traps
            both links and forms "inside" the target
        url(str): overrides `c`,`f`,`args` and `vars`
        user_signature(bool): adds hmac signature to all links
            with a key that is different for every user
        timeout(int): in milliseconds, specifies the time to wait before
            starting the request or the frequency if times is greater than
            1 or "infinity"
        times(integer or str): how many times the component will be requested
            "infinity" or "continuous" are accepted to reload indefinitely the
            component
    """
    from html import TAG, DIV, URL, SCRIPT, XML
    if args is None:
        args = []
    vars = Storage(vars or {})
    target = target or 'c' + str(random.random())[2:]
    attr['_id'] = target
    request = current.request
    if '.' in f:
        f, extension = f.rsplit('.', 1)
    if url or ajax:
        url = url or URL(request.application,
                         c,
                         f,
                         r=request,
                         args=args,
                         vars=vars,
                         extension=extension,
                         user_signature=user_signature)
        # timing options
        if isinstance(times, basestring):
            if times.upper() in ("INFINITY", "CONTINUOUS"):
                times = "Infinity"
            else:
                raise TypeError("Unsupported times argument %s" % times)
        elif isinstance(times, int):
            if times <= 0:
                raise ValueError(
                    "Times argument must be greater than zero, 'Infinity' or None"
                )
        else:
            raise TypeError("Unsupported times argument type %s" % type(times))
        if timeout is not None:
            if not isinstance(timeout, (int, long)):
                raise ValueError("Timeout argument must be an integer or None")
            elif timeout <= 0:
                raise ValueError(
                    "Timeout argument must be greater than zero or None")
            statement = "$.web2py.component('%s','%s', %s, %s);" \
                % (url, target, timeout, times)
            attr['_data-w2p_timeout'] = timeout
            attr['_data-w2p_times'] = times
        else:
            statement = "$.web2py.component('%s','%s');" % (url, target)
        attr['_data-w2p_remote'] = url
        if not target is None:
            return DIV(content, **attr)

    else:
        if not isinstance(args, (list, tuple)):
            args = [args]
        c = c or request.controller
        other_request = Storage(request)
        other_request['env'] = Storage(request.env)
        other_request.controller = c
        other_request.function = f
        other_request.extension = extension or request.extension
        other_request.args = List(args)
        other_request.vars = vars
        other_request.get_vars = vars
        other_request.post_vars = post_vars
        other_response = Response()
        other_request.env.path_info = '/' + \
            '/'.join([request.application, c, f] +
                     map(str, other_request.args))
        other_request.env.query_string = \
            vars and URL(vars=vars).split('?')[1] or ''
        other_request.env.http_web2py_component_location = \
            request.env.path_info
        other_request.cid = target
        other_request.env.http_web2py_component_element = target
        other_request.restful = types.MethodType(
            request.restful.im_func, other_request
        )  # A bit nasty but needed to use LOAD on action decorates with @request.restful()
        other_response.view = '%s/%s.%s' % (c, f, other_request.extension)

        other_environment = copy.copy(current.globalenv)  # NASTY

        other_response._view_environment = other_environment
        other_response.generic_patterns = \
            copy.copy(current.response.generic_patterns)
        other_environment['request'] = other_request
        other_environment['response'] = other_response

        ## some magic here because current are thread-locals

        original_request, current.request = current.request, other_request
        original_response, current.response = current.response, other_response
        page = run_controller_in(c, f, other_environment)
        if isinstance(page, dict):
            other_response._vars = page
            other_response._view_environment.update(page)
            run_view_in(other_response._view_environment)
            page = other_response.body.getvalue()
        current.request, current.response = original_request, original_response
        js = None
        if ajax_trap:
            link = URL(request.application,
                       c,
                       f,
                       r=request,
                       args=args,
                       vars=vars,
                       extension=extension,
                       user_signature=user_signature)
            js = "$.web2py.trap_form('%s','%s');" % (link, target)
        script = js and SCRIPT(js, _type="text/javascript") or ''
        return TAG[''](DIV(XML(page), **attr), script)
Example #10
0
    def __init__(
        self,
        table,
        record = None,
        deletable = False,
        download = "",
        upload = None,
        fields = None,
        labels = None,
        col3 = {},
        submit_button = 'Submit',
        delete_label = 'Check to delete:',
        showid = True,
        readonly = False,
        comments = True,
        keepopts = [],
        ignore_rw = False,
        formstyle = 'divs',
        record_pk_name = '_id',
        tabs = [],
        **attributes
        ):
        """
        FORMBUILDER(db.table,
               record=None,
               fields=['name'],
               labels={'name': 'Your name'},
        """
        self.table = table
        if record:
            for itm in record:
                if isinstance(record[itm],(list,tuple)):
                    if not (itm in self.table.fields and self.table[itm].type.startswith("list::")):
                        record[itm] = record[itm][-1]
        self.custom_file = upload
        self.ignore_rw = ignore_rw
        self.formstyle = formstyle
        self.record_pk_name = record_pk_name
        nbsp = XML('&nbsp;') # Firefox2 does not display fields with blanks
        attributes.update({"_id":"hyform_%s"%self.table._tablename})
        FORM.__init__(self, *[], **attributes)
        ofields = fields

        # if no fields are provided, build it from the provided table
        # will only use writable or readable fields, unless forced to ignore
        if fields == None:
            fields = [f.name for f in table if (ignore_rw or f.writable or f.readable)]

        self.record = record

        self.field_parent = {}
        xfields = {}
        xfields_keys = []
        self.fields = fields
        self.custom = Storage()
        self.custom.dspval = Storage()
        self.custom.inpval = Storage()
        self.custom.label = Storage()
        self.custom.comment = Storage()
        self.custom.widget = Storage()

        for fieldname in self.fields:
            if fieldname.find('.') >= 0:
                continue

            field = self.table[fieldname]
            comment = None

            if comments:
                comment = col3.get(fieldname, field.comment)
            if comment == None:
                comment = ''
            self.custom.comment[fieldname] = comment

            if labels != None and fieldname in labels:
                label = labels[fieldname]
                colon = ''
            else:
                label = field.label
                colon = ': '
            self.custom.label[fieldname] = label

            field_id = '%s_%s' % (table._tablename, fieldname)

            label = LABEL(label, colon, _for=field_id,
                          _id=field_id+FORMBUILDER.ID_LABEL_SUFFIX)

            row_id = field_id + FORMBUILDER.ID_ROW_SUFFIX

            if readonly and not ignore_rw and not field.readable:
                continue

            if record:
                default = record.get(fieldname, field.default)
            else:
                default = field.default

            cond = readonly or \
                (not ignore_rw and not field.writable and field.readable)

            if default and not cond:
                default = field.formatter(default)
            dspval = default
            inpval = default

            if cond:

                # ## if field.represent is available else
                # ## ignore blob and preview uploaded images
                # ## format everything else

                if field.represent:
                    inp = field.represent(default)
                elif field.type in ['blob']:
                    continue
                elif field.type == 'upload':
                    inp = UploadWidget.represent(field, default, download)
                elif field.type == 'boolean':
                    inp = self.widgets.boolean.widget(field, default, _disabled=True)
                else:
                    inp = field.formatter(default)
            elif field.type == 'upload':
                if hasattr(field, 'widget') and field.widget:
                    inp = field.widget(field, default, download)
                else:
                    inp = self.widgets.upload.widget(field, default, download)
            elif hasattr(field, 'widget') and field.widget:
                inp = field.widget(field, default)
            elif field.type == 'boolean':
                inp = self.widgets.boolean.widget(field, default)
                if default:
                    inpval = 'checked'
                else:
                    inpval = ''
            elif OptionsWidget.has_options(field):
                if not field.requires.multiple:
                    inp = self.widgets.options.widget(field, default)
                else:
                    inp = self.widgets.multiple.widget(field, default)
                if fieldname in keepopts:
                    inpval = TAG[''](*inp.components)
            elif field.type.startswith('list:'):
                inp = self.widgets.list.widget(field,default)
            elif field.type == 'text':
                inp = self.widgets.text.widget(field, default)
            elif field.type == 'hidden':
                inp = self.widgets.hidden.widget(field, default)
            elif field.type == 'password':
                inp = self.widgets.password.widget(field, default)
                if self.record:
                    dspval = PasswordWidget.DEFAULT_PASSWORD_DISPLAY
                else:
                    dspval = ''
            elif field.type == 'blob':
                continue
            else:
                inp = self.widgets.string.widget(field, default)
            xfields_keys.append(fieldname)
            xfields[fieldname] = (row_id,label,inp,comment)
            self.custom.dspval[fieldname] = dspval or nbsp
            self.custom.inpval[fieldname] = inpval or ''
            self.custom.widget[fieldname] = inp


        # when writable, add submit button
        self.custom.submit = ''
        if not readonly:
            widget = INPUT(_type='submit',_class="submit",
                           _value=submit_button,
                           _id = "submit_%s"%self.table._tablename )
            self.custom.submit = widget
        # if a record is provided and found
        # make sure it's id is stored in the form
        if record:
            if not self['hidden']:
                self['hidden'] = {}

        (begin, end) = self._xml()
        self.custom.begin = XML("<%s %s>" % (self.tag, begin))
        self.custom.end = XML("%s</%s>" % (end, self.tag))

        table = TAG['']()
        if formstyle == 'divs':
            # tabs = [
            #          {"tabname":"personal","caption":"个人信息","fields":["login","age"]},
            #          {"tabname":"comp","caption":"公司信息","fields":["login","age"]},
            #          {"tabname":"gf","caption":"朋友信息","fields":["login","age"]},
            #        ]
            if tabs:
                tab_headers = UL()
                tab_bodys = []
                
                for i, tab in enumerate(tabs):
                    tbody = DIV(_id="body_%s"%(tab.get("tabname","")))
                    if i == 0:
                        li = LI(tab.get("caption",""),_class="active", _id="tab_%s"%(tab.get("tabname","")))
                        tbody['_class'] = "active"
                    else:
                        li = LI(tab.get("caption",""),_style="display:none;",_id="tab_%s"%(tab.get("tabname","")))
                        tbody['_style'] = "display:none;"
                    tab_headers.append(li)
                    for f in tab.get("fields",[]):
                        if f in xfields_keys:
                            id,a,b,c = xfields[f]
                            div_b = self.field_parent[id] = DIV(b,_class='w2p_fw')
                            tbody.append(DIV(DIV(a,_class='w2p_fl'),div_b,DIV(c,_class='w2p_fc'),_id=id, _class="fb_row"))
                    tab_bodys.append(tbody)                  
                tab_headers = DIV(tab_headers, _id="tab_headers_%s"%self.table._tablename)
                tab_bodys = DIV(tab_bodys, _id="tab_bodys_%s"%self.table._tablename)
                table.append(DIV(tab_headers, tab_bodys))
            else:
                for d in xfields_keys:
                    id,a,b,c = xfields[d]
                    div_b = self.field_parent[id] = DIV(b,_class='w2p_fw')
                    table.append(DIV(DIV(a,_class='w2p_fl'),
                                 div_b,
                                 DIV(c,_class='w2p_fc'),_id=id,_class="fb_row"))

        self.components = [table, self.custom.submit]
Example #11
0
def LOAD(c=None, f='index', args=None, vars=None,
         extension=None, target=None,ajax=False,ajax_trap=False,
         url=None,user_signature=False, content='loading...',**attr):
    from html import TAG, DIV, URL, SCRIPT, XML
    if args is None: args = []
    vars = Storage(vars or {})
    target = target or 'c'+str(random.random())[2:]
    attr['_id']=target
    request = current.request
    if '.' in f:
        f, extension = f.split('.',1)
    if url or ajax:
        url = url or URL(request.application, c, f, r=request,
                         args=args, vars=vars, extension=extension,
                         user_signature=user_signature)
        script = SCRIPT('web2py_component("%s","%s")' % (url, target),
                             _type="text/javascript")
        return TAG[''](script, DIV(content,**attr))
    else:
        if not isinstance(args,(list,tuple)):
            args = [args]
        c = c or request.controller
        other_request = Storage()
        for key, value in request.items():
            other_request[key] = value
        other_request['env'] = Storage()
        for key, value in request.env.items():
            other_request.env['key'] = value
        other_request.controller = c
        other_request.function = f
        other_request.extension = extension or request.extension
        other_request.args = List(args)
        other_request.vars = vars
        other_request.get_vars = vars
        other_request.post_vars = Storage()
        other_response = Response()
        other_request.env.path_info = '/' + \
            '/'.join([request.application,c,f] + \
                         map(str, other_request.args))
        other_request.env.query_string = \
            vars and URL(vars=vars).split('?')[1] or ''
        other_request.env.http_web2py_component_location = \
            request.env.path_info
        other_request.cid = target
        other_request.env.http_web2py_component_element = target
        other_response.view = '%s/%s.%s' % (c,f, other_request.extension)

        other_environment = copy.copy(current.globalenv) ### NASTY

        other_response._view_environment = other_environment
        other_response.generic_patterns = \
            copy.copy(current.response.generic_patterns)
        other_environment['request'] = other_request
        other_environment['response'] = other_response

        ## some magic here because current are thread-locals

        original_request, current.request = current.request, other_request
        original_response, current.response = current.response, other_response
        page = run_controller_in(c, f, other_environment)
        if isinstance(page, dict):
            other_response._vars = page
            for key in page:
                other_response._view_environment[key] = page[key]
            run_view_in(other_response._view_environment)
            page = other_response.body.getvalue()
        current.request, current.response = original_request, original_response
        js = None
        if ajax_trap:
            link = URL(request.application, c, f, r=request,
                            args=args, vars=vars, extension=extension,
                            user_signature=user_signature)
            js = "web2py_trap_form('%s','%s');" % (link, target)
        script = js and SCRIPT(js,_type="text/javascript") or ''
        return TAG[''](DIV(XML(page),**attr),script)