Exemple #1
0
def get_delete_lst(fields_lst):
  rtable = TABLE(_style="width: 100%;")
  rtable.append(TR(TD(DIV(T("SELECT ROW"),_class="div_label",_style="color: #FFD700;"),_class="td_label",
                      _style="width: auto;border-bottom-style: double;border-width: 4px;border-color: #8B8B83;"),
         TD(SPAN("1",_class="div_label",_style=checklabel_style),
            INPUT(_type="checkbox",_value="on",_checked="checked",_disabled="disabled",_name="selrow",_id="row_1",_class="boolean", _style="vertical-align: middle;"),
            _class="td_input", _style=checkbox_style),
         TD(SPAN("2",_class="div_label",_style=checklabel_style),
            INPUT(_type="checkbox",_value="on",_name="selrow",_id="row_2",_class="boolean", _style="vertical-align: middle;"),
            _class="td_input", _style=checkbox_style),
         TD(SPAN("3",_class="div_label",_style=checklabel_style),
            INPUT(_type="checkbox",_value="on",_name="selrow",_id="row_3",_class="boolean", _style="vertical-align: middle;"),
            _class="td_input", _style=checkbox_style),
         TD(SPAN("4",_class="div_label",_style=checklabel_style),
            INPUT(_type="checkbox",_value="on",_name="selrow",_id="row_4",_class="boolean", _style="vertical-align: middle;"),
            _class="td_input", _style=checkbox_style),
         ))
  for field in fields_lst:
    if field["fieldcat"]==0:
      rtable.append(TR(TD(DIV(field["label"],_class="div_label"),_class="td_label",_style="width: auto;"),
         TD(field["widget"],_class="td_input", _style="width: auto;", _id="1"),
         TD(field["widget"],_class="td_input", _style="width: auto;", _id="2"),
         TD(field["widget"],_class="td_input", _style="width: auto;", _id="3"),
         TD(field["widget"],_class="td_input", _style="width: auto;", _id="4")
         ))
  return rtable
Exemple #2
0
 def test_INPUT(self):
     self.assertEqual(
         INPUT(_a='1', _b='2').xml(), b'<input a="1" b="2" type="text" />')
     # list value
     self.assertEqual(
         INPUT(_value=[1, 2, 3]).xml(),
         b'<input type="text" value="[1, 2, 3]" />')
Exemple #3
0
 def encrypted_form(self):
     return FORM(INPUT(_type='submit', _name="submit", _value='PayPal'),
         INPUT(_type='hidden', _name='cmd', _value='_s-xclick'),
         INPUT(_type='hidden', _name='encrypted', _value=self._encrypt()),
         _action=self.settings.paypal_url,
         _enctype='',
         _method='POST')
Exemple #4
0
def index():
    form = FORM(
        INPUT(_name='vmid', _id='vmid'),
        INPUT(_class='task-button',
              _type='button',
              _id='start',
              _name='start',
              _value='start'),
        INPUT(_class='task-button',
              _type='button',
              _name='pause',
              _value='pause'),
        INPUT(_class='task-button',
              _type='button',
              _name='shutdown',
              _value='shutdown'),
        INPUT(_class='task-button',
              _type='button',
              _name='resume',
              _value='resume'),
    )
    script = """
    <script>
    (function(){
            var $buttons = $('.task-button');
            $buttons.each(function(){
              var $this = $(this);
              $this.on('click', function(){
                $.ajax({
                    type : 'POST',
                    url : 'baadal/action/'+ this.name + '.json',
                    data : {
                        vmid : $('#vmid').val()
                    },
                    success : function (response) {
                        console.log(response);
                    }
                });
              });
              console.log(this.name);
            });
        })();
        </script>
        """
    response.script = script
    return dict(form=form)
Exemple #5
0
def get_update_lst(fields_lst):
  rtable = TABLE(_style="width: 100%;")
  rtable.append(TR(
         TD(_style=checkbox_style2),
         TD(SPAN("1",_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-left:10px;padding-right:0px;"),
         TD(SPAN(T("ROW"),_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-left:0px;"),
         TD(SPAN("2",_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-right:0px;"),
         TD(SPAN(T("ROW"),_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-left:0px;"),
         TD(SPAN("3",_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-right:0px;"),
         TD(SPAN(T("ROW"),_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-left:0px;"),
         TD(SPAN("4",_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-right:0px;"),
         TD(SPAN(T("ROW"),_class="div_label",_style=checklabel_style),
            _class="td_input", _style=checkbox_style2+"padding-left:0px;")
         ))
  fieldcat=0
  for field in fields_lst:
    style="width: auto;vertical-align: middle;"
    if field["fieldcat"]==2:
      style += "font-style:italic;"
      if fieldcat<2:
        style+="border-top-style: double;border-width: 4px;border-color: #8B8B83;"
    fieldcat=field["fieldcat"]
    rtable.append(TR(
                     TD(DIV(field["label"],_class="div_label"),
                        _class="td_label",_style=style),
                     TD(INPUT(_type="checkbox",_value="on",_name="selfield",_id="select_"+field["fieldname"]+"_1",_class="boolean", 
                              _style="vertical-align: middle;"),_class="td_input", _style=style+"padding-right:0px;padding-left:10px;"),
                     TD(field["widget"],_class="td_input", _style=style+"padding-left:0px;", _id="1"),
                     TD(INPUT(_type="checkbox",_value="on",_name="selfield",_id="select_"+field["fieldname"]+"_2",_class="boolean", 
                              _style="vertical-align: middle;"),_class="td_input", _style=style+"padding-right:0px;padding-left:5px;"),
                     TD(field["widget"],_class="td_input", _style=style+"padding-left:0px;", _id="2"),
                     TD(INPUT(_type="checkbox",_value="on",_name="selfield",_id="select_"+field["fieldname"]+"_3",_class="boolean", 
                              _style="vertical-align: middle;"),_class="td_input", _style=style+"padding-right:0px;padding-left:5px;"),
                     TD(field["widget"],_class="td_input", _style=style+"padding-left:0px;", _id="3"),
                     TD(INPUT(_type="checkbox",_value="on",_name="selfield",_id="select_"+field["fieldname"]+"_4",_class="boolean", 
                              _style="vertical-align: middle;"),_class="td_input", _style=style+"padding-right:0px;padding-left:5px;"),
                     TD(field["widget"],_class="td_input", _style=style+"padding-left:0px;", _id="4")
       ))
  return rtable
def myfolderwidgetmultiple(field, value, **attributes):
    _id = '%s_%s' % (field._tablename, field.name)
    _name = field.name
    _class = 'string folders span10'
    _style = "display: inline-block;"
    requires = field.requires if isinstance(field.requires,
                                            (IS_NOT_EMPTY,
                                             IS_LIST_OF)) else None
    items = [
        LI(
            DIV(SPAN(I(_class="icon-folder-open"), _class="add-on"),
                INPUT(_class=_class,
                      _name=_name,
                      value=v,
                      hideerror=True,
                      requires=requires,
                      _style=_style),
                _class="input-prepend span9",
                _style=_style)) for v in value or ['']
    ]
    script = SCRIPT("""
// from http://refactormycode.com/codes/694-expanding-input-list-using-jquery
(function(){
jQuery.fn.grow_input_fold = function() {
return this.each(function() {
var ul = this;
jQuery(ul).find(":text").after('<a href="javascript:void(0)">+</a>').keypress(function (e) { return (e.which == 13) ? pe(ul) : true; }).next().click(function(){ pe(ul) });
});
};
function pe(ul) {
var new_line = ml(ul);
rel(ul);
new_line.appendTo(ul);
new_line.find(":text").focus().after('<a href="javascript:void(0)">+</a>').keypress(function (e) { return (e.which == 13) ? pe(ul) : true; }).next().click(function(){ pe(ul) });
new_line.find(":text").scanfolders();
return false;
}
function ml(ul) {
var line = jQuery(ul).find("li:first").clone();
line.find(':text').val('');
line.find('a').remove();
return line;
}
function rel(ul) {
return;
jQuery(ul).find("li").each(function() {
var trimmed = jQuery.trim(jQuery(this.firstChild).val());
if (trimmed=='') jQuery(this).remove(); else jQuery(this.firstChild).val(trimmed);
});
}
})();
jQuery(document).ready(function(){
    jQuery('#%s_grow_input').grow_input_fold();
    });
""" % _id)
    attributes['_id'] = _id + '_grow_input'
    return TAG[''](UL(*items, _class="unstyled", **attributes), script)
    def widget(cls, field, value, **attributes):

        default = dict(
            _type='text',
            value=(not value is None and str(value)) or '',
        )
        attr = cls._attributes(field, default, **attributes)

        return INPUT(**attr)
    def widget(cls, field, value, **attributes):
        """
        Generates a Bootstrap Radio Button
        """

        if isinstance(value, (list, tuple)):
            value = str(value[0])
        else:
            value = str(value)

        attr = cls._attributes(field, {}, **attributes)
        attr['_class'] = add_class(attr.get('_class'), 'web2py_radiowidget')

        requires = field.requires
        if not isinstance(requires, (list, tuple)):
            requires = [requires]
        if requires:
            if hasattr(requires[0], 'options'):
                options = requires[0].options()
            else:
                raise SyntaxError('widget cannot determine options of %s' %
                                  field)
        options = [(k, v) for k, v in options if str(v)]
        opts = []
        cols = attributes.get('cols', 1)
        totals = len(options)
        mods = totals % cols
        rows = totals / cols
        if mods:
            rows += 1

        for r_index in range(rows):
            tds = []
            for k, v in options[r_index * cols:(r_index + 1) * cols]:
                checked = {'_checked': 'checked'} if k == value else {}
                tds.append(
                    LABEL(INPUT(_type='radio',
                                _id='%s%s' % (field.name, k),
                                _name=field.name,
                                requires=attr.get('requires', None),
                                hideerror=True,
                                _value=k,
                                value=value,
                                **checked),
                          v,
                          _for='%s%s' % (field.name, k)))
            opts.append(DIV(tds, _class='radio'))

        if opts:
            opts[-1][0][0]['hideerror'] = False
        return DIV(*opts, **attr)
def myradiowidget(field, value, **attributes):
    """
    <div class="control-group">
            <label for="inlineCheckboxes" class="control-label">Inline checkboxes</label>
            <div class="controls">
              <label class="checkbox inline">
                <input type="checkbox" value="option1" id="inlineCheckbox1"> 1
              </label>
              <label class="checkbox inline">
                <input type="checkbox" value="option2" id="inlineCheckbox2"> 2
              </label>
              <label class="checkbox inline">
                <input type="checkbox" value="option3" id="inlineCheckbox3"> 3
              </label>
            </div>
          </div>
    """
    _id = "%s_%s" % (field._tablename, field.name)

    requires = field.requires
    if not isinstance(requires, (list, tuple)):
        requires = [requires]
    if requires:
        if hasattr(requires[0], 'options'):
            options = requires[0].options()
        else:
            raise SyntaxError, 'widget cannot determine options of %s' \
                % field
    options = [(k, v) for k, v in options if str(v)]
    labels_and_inputs = []
    for i, a in options:
        checked = {'_checked': 'checked'} if i == value else {}
        labels_and_inputs.extend([
            LABEL(a,
                  INPUT(_type="radio",
                        _name=field.name,
                        _value=i,
                        _id="%s%s" % (_id, i),
                        **checked),
                  _class="radio%s" % (attributes.get('type', ' inline')))
        ])

    return TAG[''](*labels_and_inputs)
Exemple #10
0
 def form(self):
     return FORM(INPUT(_type='submit', _value='PayPal'),
         *[INPUT(_name=i[0], _type="hidden", _value=i[1]) for i in self.items.iteritems()],
         _action=self.settings.paypal_url,
         _enctype='',
         _method='POST')
    def widget(cls,
               field,
               value,
               disable=False,
               auth_user_permissions=None,
               **attributes):

        mylogger.debug(message='auth_user_permissions:%s' %
                       auth_user_permissions)
        mylogger.debug(message='value:%s' % value)

        _widget = super(PermissionWidget, cls).widget(field,
                                                      value,
                                                      cols=5,
                                                      **attributes)
        _hidden_fields = []

        for e in _widget.elements('input'):

            _value = e.attributes[
                '_value'] if '_value' in e.attributes else None
            _name = e.attributes['_name']
            checked = e.attributes[
                '_checked'] == 'checked' if '_checked' in e.attributes else False
            mylogger.debug(message='_value:%s' % _value)
            mylogger.debug(message='_name:%s' % _name)

            # tip to "disable" input with None value
            if _value is None:
                e.attributes['_name'] = '%s-renamed-to-disable' % _name

            # disabling checkboxes for default permissions
            if (_value and _value
                    in current.settings['disabled_permissions'].keys()
                ) or disable:
                mylogger.debug(message='NM')
                e.update(_disabled='disabled')
                e.update(_class='NM')

                # checking checkboxes for default permissions set to True
                # adding an hidden field to pass the value in the form
                if not disable and current.settings['disabled_permissions'][
                        _value]:
                    e.update(_checked='checked')
                    _hidden_fields.append(
                        INPUT(_type='hidden', _value=_value, _name=_name))

            # hidding checkboxes for permissions not owned by the authenticated user
            # to avoid action
            elif (auth_user_permissions
                  is not None) and (_value not in auth_user_permissions):
                mylogger.debug(message='blocked')
                e.update(_style='display: none;')
                if checked:
                    e.update(_class='blocked')
                try:
                    e.__delitem__('_checked')
                except KeyError:
                    pass
                # disabling the hidden if the permission was not set
                # we could also remove the input
                if not checked:
                    e.update(_disabled='disabled')

        _v_header1 = [
            cc.get_string("PRODUCT_CARD"),
            cc.get_string("PRODUCT_CARD_RESTRICTED"),
            cc.get_string("STORAGE_CARD"),
            cc.get_string("STORAGE_ARCHIVE"),
            cc.get_string("STORE_LOCATION"),
            cc.get_string("ENTITY"),
            cc.get_string("USER"),
            cc.get_string("COC"),
            cc.get_string("SUPPLIER"),
            cc.get_string("MESSAGE"),
            cc.get_string("COMMAND")
        ]
        _v_header2 = ['', '', '*', '*', '*', '*', '*', '', '', '**', '']
        _i = 0
        for e in _widget.elements('tr')[:11]:
            e.insert(0, _v_header1[_i])
            _i = _i + 1
        _i = 0
        for e in _widget.elements('tr')[:11]:
            e.insert(6, _v_header2[_i])
            _i = _i + 1

        _h_legend = TR(
            TR(TD('S: %s' % cc.get_string("PERMISSION_SELECT"), _colspan="7")),
            TR(TD('R: %s' % cc.get_string("PERMISSION_READ"), _colspan="7")),
            TR(TD('U: %s' % cc.get_string("PERMISSION_UPDATE"), _colspan="7")),
            TR(TD('C: %s' % cc.get_string("PERMISSION_CREATE"), _colspan="7")),
            TR(TD('D: %s' % cc.get_string("PERMISSION_DELETE"), _colspan="7")),
            TR(
                TD('*: %s' % cc.get_string("PERMISSION_IN_HIS_ENTITY"),
                   _colspan="7")),
            TR(
                TD('**: %s' % cc.get_string("PERMISSION_HIS_MESSAGE"),
                   _colspan="7")))

        _h_header = TR(TH(''), TH('S'), TH('R'), TH('U'), TH('C'), TH('D'),
                       TH(''))

        _widget.element('table').insert(0, _h_header)
        _widget.element('table').insert(0, _h_legend)

        _widget.components.extend(_hidden_fields)

        return _widget
Exemple #12
0
def select():
    import re
    db = get_database(request)
    dbname = request.args[0]
    regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)')
    if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'):
        regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)')
    if request.vars.query:
        match = regex.match(request.vars.query)
        if match:
            request.vars.query = '%s.%s.%s==%s' % (
                request.args[0], match.group('table'), match.group('field'),
                match.group('value'))
    else:
        request.vars.query = session.last_query
    query = get_query(request)
    if request.vars.start:
        start = int(request.vars.start)
    else:
        start = 0
    nrows = 0
    stop = start + 100
    table = None
    rows = []
    orderby = request.vars.orderby
    if orderby:
        orderby = dbname + '.' + orderby
        if orderby == session.last_orderby:
            if orderby[0] == '~':
                orderby = orderby[1:]
            else:
                orderby = '~' + orderby
    session.last_orderby = orderby
    session.last_query = request.vars.query
    form = FORM(TABLE(
        TR(
            T('Query:'), '',
            INPUT(_style='width:400px',
                  _name='query',
                  _value=request.vars.query or '',
                  requires=IS_NOT_EMPTY(error_message=T("Cannot be empty")))),
        TR(
            T('Update:'),
            INPUT(_name='update_check', _type='checkbox', value=False),
            INPUT(_style='width:400px',
                  _name='update_fields',
                  _value=request.vars.update_fields or '')),
        TR(
            T('Delete:'),
            INPUT(_name='delete_check',
                  _class='delete',
                  _type='checkbox',
                  value=False), ''),
        TR('', '', INPUT(_type='submit', _value='submit'))),
                _action=URL(r=request, args=request.args))
    if request.vars.csvfile != None:
        try:
            import_csv(db[request.vars.table], request.vars.csvfile.file)
            response.flash = T('data uploaded')
        except Exception, e:
            response.flash = DIV(T('unable to parse csv file'), PRE(str(e)))
    def widget(cls, field, value, **attributes):

        default = dict(_type='checkbox', value=value)
        attr = cls._attributes(field, default,
                               **attributes)
        return INPUT(**attr)
    def __call__(self, field, value):

        mylogger.debug(message='current.request.vars:%s' %
                       current.request.vars)
        mylogger.debug(message='field._tablename:%s' % (str(field._tablename)))
        mylogger.debug(message='field:%s' % (str(field)))
        mylogger.debug(message='field.name:%s' % (str(field.name)))
        mylogger.debug(message='field.type:%s' % (str(field.type)))
        mylogger.debug(message='field.requires:%s' % (str(field.requires)))
        mylogger.debug(message='type(value):%s' % (str(type(value))))
        mylogger.debug(message='value:%s' % (str(value)))

        if current.request and current.request['function']:
            function = current.request['function']
        function_configuration = self.configuration[
            '*'] if self.configuration.keys().count(
                '*') > 0 else self.configuration[
                    function] if function in self.configuration.keys() else ''

        # query parameter not used yet...
        if 'query' in function_configuration:
            query = function_configuration['query'].as_json()
        else:
            query = None
        if 'disable_validate' in function_configuration:
            disable_validate = function_configuration['disable_validate']
        else:
            disable_validate = False
        if 'add_in_db' in function_configuration:
            add_in_db = function_configuration['add_in_db']
        else:
            add_in_db = False
        if 'multiple' in function_configuration:
            multiple = function_configuration['multiple']
        else:
            multiple = False
        if 'submit_on_select' in function_configuration:
            submit_on_select = function_configuration['submit_on_select']
        else:
            submit_on_select = False
        max_nb_item = 20
        if 'max_nb_item' in function_configuration:
            max_nb_item = function_configuration['max_nb_item']
        func_lambda = ''
        if 'func_lambda' in function_configuration:
            func_lambda = function_configuration['func_lambda']
        # use this option for no required fields only, to force the user to confirm that the field is empty
        if 'confirm_empty' in function_configuration:
            confirm_empty = function_configuration['confirm_empty']
        else:
            confirm_empty = current.request.vars[
                'confirm_empty_%s' % field.
                name] == 'on' if 'confirm_empty_%s' % field.name in current.request.vars else False

        is_not_a_reference = (field._tablename == self.ref_field._tablename)

        disabled = '_disabled' in self.attributes.keys()
        mylogger.debug(message='add_in_db:%s' % (str(add_in_db)))
        mylogger.debug(message='multiple:%s' % (str(multiple)))
        mylogger.debug(message='disabled:%s' % (str(disabled)))
        mylogger.debug(message='max_nb_item:%s' % (str(max_nb_item)))
        mylogger.debug(message='is_not_a_reference:%s' %
                       (str(is_not_a_reference)))

        if (value) and (type(value) is StringType) and (value == '0'):
            nb_item = 0
        elif (value) and (type(value) is StringType) and (value == '|0|'):
            nb_item = 0
        elif (value) and (type(value) is ListType) and (value[0] == 0):
            nb_item = 0
        elif (value) and (type(value) is ListType) and (value[0] == '|0|'):
            nb_item = 0
        elif (value) and (type(value) is ListType):
            nb_item = len(value)
        elif value and value != '':
            nb_item = 1
        else:
            nb_item = 0

        if value and not type(value) is ListType and value != '':
            value = [value]

        mylogger.debug(message='nb_item:%s' % (str(nb_item)))

        #
        # basic widget structure
        #
        checkboxes_form = DIV()
        suggestions_form = DIV(
            _id='%s_suggestions' % (self.uid),
            _class='CHIMITHEQUE_MULTIPLE_widget_suggestions')
        message_form = DIV(_id='%s_message' % (self.uid),
                           _class='CHIMITHEQUE_MULTIPLE_widget_message',
                           _style='display: none;')

        search_input_form = DIV(INPUT(_name='%s_search' % self.uid,
                                      _type='text',
                                      _title='%s_search' % self.uid),
                                suggestions_form,
                                _id='%s_search' % (self.uid),
                                _class='search_input_form')

        #
        # adding a confirm empty checkbox if needed
        #
        if confirm_empty:

            confirm_empty_form = DIV(
                INPUT(_name='confirm_empty_%s' % field.name,
                      _id='confirm_empty_%s' % field.name,
                      _type='checkbox',
                      _title=self.text_confirm_empty_form_field,
                      _class='CHIMITHEQUE_MULTIPLE_widget_confirm_empty',
                      _onclick='''$('div[id=%(uid)s]').empty();

                                         if ($('input[type=checkbox][name=confirm_empty_%(field_name)s]').is(':checked')) {
                                             $('div[id=%(uid)s]').append('<span id="%(field_name)s_span_no_selected"></span>');
                                         }
                                         else {
                                             $('div[id=%(uid)s]').append('<span id="%(field_name)s_span_no_selected">%(no_item_selected)s</span>');
                                         }
                             ''' % {
                          'uid': self.uid,
                          'field_name': field.name,
                          'no_item_selected': self.text_no_item_selected
                      }))

            confirm_empty_form.append(
                IMG(_src=self.image_disable_url,
                    _alt='disable',
                    _id='%s_disable' % self.uid,
                    _title=self.text_confirm_empty_form_field))
        else:
            confirm_empty_form = DIV()

        #
        # building the AJAX query parameters
        #
        _ajax_parameters = {
            'uid': self.uid,
            'multiple': multiple,
            'disable_validate': disable_validate,
            'add_in_db': add_in_db,
            'field_tablename': field._tablename,
            'ref_field_tablename': self.ref_field._tablename,
            'ref_field_name': self.ref_field.name,
            'max_nb_item': max_nb_item,
            'max_item_length': self.max_item_length,
            'lambda': func_lambda,
            'query': query,
            'text_close_list': str(self.text_close_list),
            'text_submit': str(self.text_submit),
            'image_select_url': self.image_select_url,
            'submit_on_select': submit_on_select
        }
        ajax_parameters = json.dumps(_ajax_parameters)

        #
        # adding the "add" image
        #
        if not disabled and add_in_db:

            search_input_form.append(
                IMG(_src=self.image_insert_url,
                    _alt='submit',
                    _id='%s_add' % self.uid,
                    _title=self.text_submit,
                    _style='visibility: hidden;',
                    _class='CHIMITHEQUE_MULTIPLE_widget_addindb',
                    _onclick='''
                                            // adding the search parameter to the JSON object
                                            ajax_parameters = %(ajax_parameters)s;
                                            ajax_parameters["search"] = $('input[name=%(uid)s_search]').val();
                                            var ret = $.ajax({
                                                       type: "POST",
                                                       url: "/%(application)s/chimitheque_multiple_widget/item_add",
                                                       data: JSON.stringify(ajax_parameters),
                                                       dataType: "json",
                                                       contentType: "application/json; charset=utf-8",
                                                       async: false
                                                     }).done(function(data) {
                                                            var _action = data['action'];
                                                            var _id = data['id'];
                                                            var _val = data['val'];
                                                            var _encval = data['encval'];

                                                            var funcCall = "addReplaceCheckBox%(uid)s" + "('" + _action + "','" + _id + "','" + _val + "','" + _encval + "')";
                                                            eval(funcCall);

                                                            $('img#%(uid)s_add').attr('style', 'visibility: hidden;');
                                                        });
                                                    ''' % {
                        'uid': self.uid,
                        'application': current.request.application,
                        'ajax_parameters': ajax_parameters
                    }))

        #
        # adding the selected items DIV
        #
        if nb_item == 0:

            if 'confirm_empty_%s' % field.name in current.request.vars:
                checkboxes_form.append(SPAN())
            else:
                checkboxes_form.append(
                    SPAN(XML(self.text_no_item_selected),
                         _id='%s_span_no_selected' % field.name))
            hidden_box_form = DIV(
                INPUT(_name='%s' % field.name,
                      _id='%s_hidden' % field.name,
                      _type='checkbox',
                      _value='',
                      _style='visibility: hidden; height: 0px;',
                      _checked='checked',
                      requires=field.requires))
        else:
            hidden_box_form = DIV()

            #
            # prepopulating the form
            #
            for i in range(0, nb_item):

                mylogger.debug(message='i:%i' % (i))

                prepop_value_id = None
                prepop_value_label = None

                if is_not_a_reference:
                    # just populating with the value passed in parameter
                    mylogger.debug(message='case 1')
                    prepop_value_id = value[i]
                    prepop_value_label = value[i]
                else:
                    # the parameter value is an id in the reference table, then querying the table
                    mylogger.debug(message='case 2')
                    prepop_value = current.db(
                        current.db['%s' % self.ref_field._tablename]['id'] == (
                            value[i])).select().first()
                    if prepop_value is not None:
                        prepop_value_label = current.db[
                            '%s' %
                            self.ref_field._tablename]._format(prepop_value)
                        prepop_value_id = value[i]

                mylogger.debug(message='prepop_value_id:%s' % prepop_value_id)
                mylogger.debug(message='prepop_value_label:%s' %
                               prepop_value_label)

                if prepop_value_id:
                    #
                    # adding the checkboxes or radio for the selected items
                    #
                    if multiple:
                        _input = INPUT(
                            _name='%s' % field.name,
                            _id='%s' % field.name,
                            _type='checkbox',
                            _class='CHIMITHEQUE_MULTIPLE_widget_selected',
                            _encvalue=self.uid,
                            _value=prepop_value_id,
                            value=True,
                            requires=field.requires)
                    else:
                        if is_not_a_reference:
                            _input = INPUT(
                                _name='%s' % field.name,
                                _id='%s' % field.name,
                                _type='radio',
                                _class='CHIMITHEQUE_MULTIPLE_widget_selected',
                                _encvalue=self.uid,
                                _value=
                                prepop_value_label,  # or prepop_value_id, don't mind...
                                value=
                                prepop_value_label,  # or prepop_value_id, don't mind...
                                requires=field.requires)
                        else:
                            _input = INPUT(
                                _name='%s' % field.name,
                                _id='%s' % field.name,
                                _type='radio',
                                _class='CHIMITHEQUE_MULTIPLE_widget_selected',
                                _encvalue=self.uid,
                                _value=prepop_value_id,
                                value=prepop_value_id,
                                requires=field.requires)
                    #
                    # then the delete selected item image
                    #
                    if not disabled and not multiple:

                        img_del = IMG(_src=self.image_delete_url,
                                      _alt=self.text_delete,
                                      _title=self.text_delete,
                                      _onclick='deleteItem%s();' % self.uid,
                                      _style='float: left;')

                    else:

                        img_del = SPAN()

                    #
                    # then the label
                    #
                    checkboxes_form.append(
                        DIV(_input,
                            img_del,
                            XML('%s' % prepop_value_label),
                            _class='CHIMITHEQUE_MULTIPLE_widget_selected'))

                else:
                    # TODO: code identical to line 232...

                    if 'confirm_empty_%s' % field.name in current.request.vars:
                        checkboxes_form.append(SPAN())
                    else:
                        checkboxes_form.append(
                            SPAN(XML(self.text_no_item_selected),
                                 _id='%s_span_no_selected' % field.name))
                    hidden_box_form = DIV(
                        INPUT(_name='%s' % field.name,
                              _id='%s_hidden' % field.name,
                              _type='checkbox',
                              _value='',
                              _style='visibility: hidden; height: 0px;',
                              _checked='checked',
                              requires=field.requires))

        #
        # building the final form
        #
        final_form = DIV(
            DIV(
                DIV(checkboxes_form,
                    _id='%s' % self.uid,
                    _class='%s_%s' %
                    (self.ref_field._tablename, self.ref_field.name)),
                **self.attributes))

        if not disabled:
            final_form.insert(0, confirm_empty_form)
            final_form.insert(0, search_input_form)

        # hidden field to export the uid for the pages
        uid_field = INPUT(_name='uid_%s' % field.name,
                          _type='hidden',
                          value='%s' % self.uid,
                          style='visibility: hidden; height: 0px;')

        return DIV(final_form,
                   uid_field,
                   hidden_box_form,
                   message_form,
                   SCRIPT(
                       """
                            function disableAddButton%(uid)s() {
                                $('#%(uid)s_add').attr('style', 'visibility: hidden;');

                            }

                            function displayMessage%(uid)s(message) {
                                $('#%(uid)s_message span').remove();
                                $('#%(uid)s_message').append('<span class="error">' + message + '</span>');

                            }

                            function deleteItem%(uid)s() {
                                $('#%(uid)s').find('div[class=CHIMITHEQUE_MULTIPLE_widget_selected]').remove();

                                console.log($('input[name=%(field_name)s]').length);
                                /* enabling the hidden field if needed */
                                if ($('input[name=%(field_name)s]').length <= 1) {
                                    console.log("input name '%(field_name)s' was the last element");
                                    $('input[id=%(field_name)s_hidden]').removeAttr('disabled');
                                    $('div[id=%(uid)s]').append('<span id="%(field_name)s_span_no_selected">%(no_item_selected)s</span>');
                                }
                                else {
                                    console.log("input name '%(field_name)s' was not the last element");
                                }
                            }

                            function addReplaceCheckBox%(uid)s(action, id, val, encval) {
                                    console.log(arguments.callee.name);
                                    console.log('action:' + action);
                                    console.log('id:' + id);
                                    console.log('val:' + val);
                                    console.log('encval:' + encval);

                                    /* base64 decoding the string */
                                    val = Base64.decode(val);

                                    /* disabling the hidden field */
                                    $('input[id=%(field_name)s_hidden]').attr('disabled','true');
                                    $('span[id=%(field_name)s_span_no_selected]').remove();

                                    if ($('#%(uid)s').find('input[value="'+id+'"][encvalue='+encval+']').length != 0) {
                                        alert('%(text_item_already_selected)s');
                                    }
                                    else {
                                        var newDiv = $('<div class="CHIMITHEQUE_MULTIPLE_widget_selected"/>');
                                        var newDel = $('<img/>').attr({
                                            'src': '%(image_delete_url)s',
                                            'alt': '%(image_delete_alt)s',
                                            'title': '%(image_delete_title)s',
                                            'onclick': 'deleteItem%(uid)s();'
                                        });
                                        var newElem = $('<input/>').attr({
                                            'id': '%(field_name)s',
                                            'type': '%(type)s',
                                            'checked': 'checked',
                                            'name': '%(field_name)s',
                                            'value': id,
                                            'class': 'CHIMITHEQUE_MULTIPLE_widget_selected',
                                            'encvalue': encval,
                                        });
                                        if (action == 'replace') {
                                            newDiv.append(newDel);
                                        }
                                        newDiv.append(newElem);
                                        newDiv.append(val);
                                        if (action == 'replace') {
                                            $('#%(uid)s div').remove();
                                        }
                                        $('#%(uid)s').append(newDiv);
                                    }
                                    $('input[name=%(uid)s_search]').val('');

                                    $('#' + encval + '_suggestions div').remove();

                            }

                            function autocomplete%(uid)s() {
                                   $elem = $('input[type=text][name=%(uid)s_search]')
                                   var inputLength = $elem.val().length;
                                   if (inputLength >= %(minchar)s) {
                                        // adding the search parameter to the JSON object
                                        ajax_parameters = %(ajax_parameters)s;
                                        ajax_parameters["search"] = $elem.val();
                                        var ret = $.ajax({
                                                   type: "POST",
                                                   url: "/%(application)s/chimitheque_multiple_widget/item_selector",
                                                   data: JSON.stringify(ajax_parameters),
                                                   dataType: "json",
                                                   contentType: "application/json; charset=utf-8",
                                                   async: false
                                                 }).responseText;

                                        $('#%(uid)s_suggestions > *').remove();
                                        $('#%(uid)s_message').show();
                                        $('#%(uid)s_message').text('');
                                        if (ret.substr(0, 5) == 'ERROR') {
                                            $('#%(uid)s_message').text(ret);
                                            $('#%(uid)s_add').attr('style', 'visibility: hidden;');
                                        }else if (ret.substr(0, 4) == 'INDB'){
                                            $('#%(uid)s_add').attr('style', 'visibility: hidden;');
                                            $('#%(uid)s_suggestions').append(ret);
                                        }else if (ret.substr(0, 4) == 'NONE'){
                                            $('#%(uid)s_add').attr('style', 'visibility: visible;');
                                        }
                                        else {
                                            $('#%(uid)s_add').attr('style', 'visibility: visible;');
                                            $('#%(uid)s_suggestions').append(ret);
                                        }
                                   }
                            }

                            $(document).ready(function() {

                                jQuery('input[type=text][name=%(uid)s_search]').bind('paste', function(e) {
                                    setTimeout(function() {
                                        autocomplete%(uid)s();
                                    }, 0);
                                });

                                timer = 0;
                                jQuery('input[type=text][name=%(uid)s_search]').bind('keypress click paste input',function() {
                                        if (timer) {
                                            clearTimeout(timer);
                                        }
                                        timer = setTimeout(autocomplete%(uid)s, 400);                                  
                                });

                            });
                          """ % {
                           'disable_validate': disable_validate,
                           'add_in_db': add_in_db,
                           'multiple': multiple,
                           'uid': self.uid,
                           'field_tablename': field._tablename,
                           'field_name': field.name,
                           'field_label': field.label,
                           'ref_field_tablename': self.ref_field._tablename,
                           'ref_field_name': self.ref_field.name,
                           'minchar': self.minchar,
                           'image_delete_url': self.image_delete_url,
                           'image_delete_alt': self.text_delete,
                           'image_delete_title': self.text_delete,
                           'type': 'checkbox' if multiple else 'radio',
                           'max_nb_item': max_nb_item,
                           'max_item_length': self.max_item_length,
                           'lambda': func_lambda,
                           'image_delete_small': self.image_delete_url,
                           'text_item_already_selected':
                           self.text_item_already_selected,
                           'no_item_selected': self.text_no_item_selected,
                           'application': current.request.application,
                           'ajax_parameters': ajax_parameters
                       }),
                   _class='CHIMITHEQUE_MULTIPLE_widget')
Exemple #15
0
    def apply_method(r, **attr):
        """
            Apply method.

            @param r: the S3Request
            @param attr: controller options for this request
        """

        if r.representation == "html":

            from gluon.dal import Field
            from gluon.html import FORM, INPUT, OPTION, SELECT
            from gluon.validators import IS_IN_SET, IS_EMPTY_OR
            from s3fields import s3_datetime
            from s3validators import IS_LOCATION_SELECTOR2
            from s3widgets import S3LocationSelectorWidget2

            T = current.T
            table = r.table
            response = current.response
            session = current.session
            formstyle = current.deployment_settings.get_ui_formstyle()
            tracker = S3Trackable(table, record_id=r.id)

            form = FORM()
            fappend = form.append
            comment = ""

            opts = {
                1: T("Check-In"),
                2: T("Check-Out"),
                3: T("Update Base Location"),
            }
            id = "action"
            label = T("Action")
            widget = SELECT(
                [OPTION(opts[opt], _value=opt) for opt in opts],
                _id=id,
                _name=id,
                _value=1,
                requries=IS_IN_SET(opts),
            )
            row = formstyle("%s__row" % id, label, widget, comment)
            fappend(row)

            field = s3_datetime()
            field.tablename = r.tablename
            id = "timestmp"
            label = T("Time")
            value = current.request.utcnow
            widget = field.widget(field, value)
            row = formstyle("%s__row" % id, label, widget, comment)
            fappend(row)

            field = table.location_id
            field.requires = IS_EMPTY_OR(IS_LOCATION_SELECTOR2())
            value = tracker.get_location(_fields=["id"],
                                         as_rows=True).first().id
            id = "location"
            label = ""  # Replaced by Widget
            widget = S3LocationSelectorWidget2()(field, value)
            row = formstyle("%s__row" % id, label, widget, comment)
            fappend(row)

            id = "submit"
            label = ""
            widget = INPUT(_type="submit", _value=T("Apply"))
            row = formstyle("%s__row" % id, label, widget, comment)
            fappend(row)

            response.view = "create.html"
            title = T("Update Location")
            output = dict(title=title, form=form)

            script = \
'''$("#action").change(function(){
var type=$("#action").val()
if(type==2){$('#location__row').hide()}else{$('#location__row').show()}})'''
            response.s3.jquery_ready.append(script)
            if form.accepts(current.request.vars, current.session):

                form_vars = form.vars
                action = form_vars.get("action", None)
                if action == "1":
                    # Check-In
                    location_id = form_vars.get("location_id", None)
                    if location_id:
                        # We're not Checking-in in S3Track terms (that's about interlocking with another object)
                        #tracker.check_in()
                        timestmp = form_vars.get("timestmp", None)
                        if timestmp:
                            # @ToDo: Convert from string
                            pass
                        tracker.set_location(location_id, timestmp=timestmp)
                        response.confirmation = T("Checked-In successfully!")

                elif action == "2":
                    # Check-Out
                    # We're not Checking-out in S3Track terms (that's about removing an interlock with another object)
                    #tracker.check_out()
                    timestmp = form_vars.get("timestmp", None)
                    if timestmp:
                        # @ToDo: Convert from string
                        pass
                    tracker.set_location(r.record.location_id,
                                         timestmp=timestmp)
                    response.confirmation = T("Checked-Out successfully!")

                elif action == "3":
                    # Update Base Location
                    location_id = form_vars.get("location_id", None)
                    if location_id:
                        tracker.set_base_location(location_id)
                        response.confirmation = T("Base Location Updated!")

            return output

        else:
            raise HTTP(501, current.ERROR.BAD_METHOD)
Exemple #16
0
def create_fieldlist(table):
  fields_lst = []
#   if table=="setting":
#     table="fieldvalue"
  fields = ns.db[table].fields
  for fname in fields:
    fieldcat=1
    if fname in("id","deleted"):
      continue
    
    if ns.db[table][fname].type=="text":
      ns.db[table][fname].widget=lambda field,value: SQLFORM.widgets.string.widget(field,value)
    if type(ns.db[table][fname].requires).__name__=="check_boolean":
      fields_lst.append({"fieldname":fname,"label":ns.db[table][fname].label,
                       "widget":SELECT([OPTION("", _value=""),OPTION(T("YES"), _value="1"),OPTION(T("NO"), _value="0",)], _id=table+"_"+fname, _name=fname),
                       "fieldcat":1})
      continue
    
    if table in("address","contact"):
      if fname=="nervatype":
        ns.db[table].nervatype.requires = IS_IN_SET(('customer', 'employee', 'event', 'place', 'product', 'project', 'tool', 'trans'))
        fieldcat=0
      elif fname=="ref_id":
        fields_lst.append({"fieldname":"refnumber","label":T('Ref.No.'),
                       "widget":INPUT(_type="text",_value="",_name="refnumber",_id=table+"_refnumber",_class="string"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"rownumber","label":T('Row No.'),
                       "widget":INPUT(_type="text",_value="0",_name="rownumber",_id=table+"_rownumber",_class="integer"),
                       "fieldcat":0})
        continue
    elif table=="barcode":
      if fname=="code":
        fields_lst.append({"fieldname":"code","label":T('Barcode'),
                       "widget":INPUT(_type="text",_value="",_name="code",_id=table+"_code",_class="string"),
                       "fieldcat":0})
        continue
      elif fname=="product_id":
        fields_lst.append({"fieldname":"partnumber","label":T('Product No.'),
                       "widget":INPUT(_type="text",_value="",_name="partnumber",_id=table+"_partnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="barcodetype":
        ns.db.barcode.barcodetype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('barcodetype')), ns.db.groups.groupvalue, '%(groupvalue)s')
    elif table=="currency":
      if fname=="curr":
        fieldcat=0
    elif table=="customer":
      if fname=="custnumber":
        fieldcat=0
      elif fname=="custtype":
        ns.db.customer.custtype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('custtype')&(ns.db.groups.groupvalue!="own")), ns.db.groups.groupvalue, '%(groupvalue)s')
    elif table=="deffield":
      if fname=="fieldname":
        fieldcat=0
      elif fname=="nervatype":
        ns.db[table].nervatype.requires = IS_IN_SET(('address', 'barcode', 'contact', 'currency', 'customer', 'employee', 'event', 'item', 'link', 
                                                     'log', 'movement', 'payment', 'price', 'place', 'product', 'project', 'rate', 'tax',
                                                     'tool', 'trans', 'setting'))
      elif fname=="subtype":
        ns.db[table][fname].widget=lambda field,value: SQLFORM.widgets.string.widget(field,value)
      elif fname=="fieldtype":
        ns.db.deffield.fieldtype.requires = IS_IN_DB(ns.db((ns.db.groups.groupname.like('fieldtype'))
          &(ns.db.groups.groupvalue!="checkbox")&(ns.db.groups.groupvalue!="trans")), ns.db.groups.groupvalue, '%(groupvalue)s')
    elif table=="employee":
      if fname=="empnumber":
        fieldcat=0
      elif fname=="usergroup":
        ns.db.employee.usergroup.requires = IS_IN_DB(ns.db((ns.db.groups.groupname.like('usergroup'))&(ns.db.groups.deleted==0)), 
                                                     ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname=="department":
        ns.db.employee.department.requires = IS_EMPTY_OR(IS_IN_DB(ns.db((ns.db.groups.groupname.like('department'))
          &(ns.db.groups.deleted==0)), ns.db.groups.groupvalue, '%(groupvalue)s'))
      elif fname in("password","registration_key","reset_password_key","registration_id"):
        continue
    elif table=="event":
      if fname=="calnumber":
        fieldcat=0
      elif fname=="ref_id":
        fields_lst.append({"fieldname":"refnumber","label":T('Ref. No.'),
                       "widget":INPUT(_type="text",_value="",_name="refnumber",_id=table+"_refnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="nervatype":
        ns.db[table].nervatype.requires = IS_IN_SET(('customer', 'employee', 'place', 'product', 'project', 'tool', 'trans'))
      elif fname=="eventgroup":
        ns.db[table][fname].widget=lambda field,value: SQLFORM.widgets.string.widget(field,value)
    elif table=="groups":
      if fname in("groupname","groupvalue"):
        fieldcat=0
    elif table=="item":
      if fname=="trans_id":
        fields_lst.append({"fieldname":"transnumber","label":T('Doc.No.'),
                       "widget":INPUT(_type="text",_value="",_name="transnumber",_id=table+"_transnumber",_class="string"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"rownumber","label":T('Row No.'),
                       "widget":INPUT(_type="text",_value="0",_name="rownumber",_id=table+"_rownumber",_class="integer"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"inputmode","label":T('Input mode'),
                       "widget":SELECT([OPTION("", _value=""),OPTION(T("fxprice"), _value="fxprice"),
                                        OPTION(T("netamount"), _value="netamount"),OPTION(T("amount"), _value="amount")
                                        ], _id="item_inputmode", _name="inputmode"),
                       "fieldcat":1})
        fields_lst.append({"fieldname":"inputvalue","label":T('Input value'),
                       "widget":INPUT(_type="text",_value="0",_name="inputvalue",_id=table+"_inputvalue",_class="double"),
                       "fieldcat":1})
        continue
      elif fname=="product_id":
        fields_lst.append({"fieldname":"partnumber","label":T('Product No.'),
                       "widget":INPUT(_type="text",_value="",_name="partnumber",_id=table+"_partnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="tax_id":
        taxcode = ns.db(ns.db.tax.inactive==0).select(ns.db.tax.taxcode)
        widget=SELECT(*[OPTION(field.taxcode) for field in taxcode], _id="item_taxcode", _name="taxcode")
        widget.insert(0, OPTION(""))
        fields_lst.append({"fieldname":"taxcode","label":T('Tax'), "widget":widget, "fieldcat":1})
        continue
      elif fname in("fxprice","netamount","vatamount","amount"):
        continue
    elif table=="link":
      nervatype_lst=['address', 'barcode', 'contact', 'currency', 'customer', 'employee', 'event', 'groups', 'item', 
                   'movement', 'payment', 'price', 'place', 'product', 'project', 'rate', 'tax',
                   'tool', 'trans']
      if fname == "nervatype_1":
        widget=SELECT(*[OPTION(nervatype) for nervatype in nervatype_lst], _id="link_nervatype1", _name="nervatype1")
        widget.insert(0, OPTION(""))
        fields_lst.append({"fieldname":"nervatype1","label":T('Nervatype 1'), "widget":widget, "fieldcat":0})
        continue
      elif fname == "nervatype_2":
        widget=SELECT(*[OPTION(nervatype) for nervatype in nervatype_lst], _id="link_nervatype2", _name="nervatype2")
        widget.insert(0, OPTION(""))
        fields_lst.append({"fieldname":"nervatype2","label":T('Nervatype 2'), "widget":widget, "fieldcat":0})
        continue
      elif fname=="ref_id_1":
        fields_lst.append({"fieldname":"refnumber1","label":T('Ref. No. 1'),
                       "widget":INPUT(_type="text",_value="",_name="refnumber1",_id=table+"_refnumber1",_class="string"),
                       "fieldcat":0})
        continue
      elif fname=="ref_id_2":
        fields_lst.append({"fieldname":"refnumber2","label":T('Ref. No. 2'),
                       "widget":INPUT(_type="text",_value="",_name="refnumber2",_id=table+"_refnumber2",_class="string"),
                       "fieldcat":0})
        continue
    elif table=="log":
      nervatype_lst=['address', 'barcode', 'contact', 'currency', 'customer', 'employee', 'deffield',
                     'event', 'groups', 'item', 'link', 'movement', 'payment', 'price', 'place', 'product', 'project', 
                     'rate', 'tax', 'tool', 'trans', 'setting']
      if fname=="employee_id":
        fields_lst.append({"fieldname":"empnumber","label":T('Employee No.'),
                       "widget":INPUT(_type="text",_value="",_name="empnumber",_id=table+"_empnumber",_class="string"),
                       "fieldcat":0})
        continue
      elif fname=="crdate":
        fieldcat=0
      elif fname == "nervatype":
        widget=SELECT(*[OPTION(nervatype) for nervatype in nervatype_lst], _id="log_nervatype", _name="nervatype")
        widget.insert(0, OPTION(""))
        fields_lst.append({"fieldname":"nervatype","label":T('Nervatype'), "widget":widget, "fieldcat":1})
        continue
      elif fname == "logstate":
        widget=SELECT(*[OPTION(logstate.groupvalue) for logstate in ns.db(ns.db.groups.groupname.like('logstate')).select(ns.db.groups.groupvalue)], _id="log_logstate", _name="logstate")
        widget.insert(0, OPTION(""))
        fields_lst.append({"fieldname":"logstate","label":T('State'), "widget":widget, "fieldcat":1})
        continue
      elif fname=="ref_id":
        fields_lst.append({"fieldname":"refnumber","label":T('Ref.No.'),
                       "widget":INPUT(_type="text",_value="",_name="refnumber",_id=table+"_refnumber",_class="string"),
                       "fieldcat":1})
        continue
    elif table=="movement":
      if fname=="trans_id":
        fields_lst.append({"fieldname":"transnumber","label":T('Doc.No.'),
                       "widget":INPUT(_type="text",_value="",_name="transnumber",_id=table+"_transnumber",_class="string"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"rownumber","label":T('Row No.'),
                       "widget":INPUT(_type="text",_value="0",_name="rownumber",_id=table+"_rownumber",_class="integer"),
                       "fieldcat":0})
        continue
      elif fname=="movetype":
        ns.db.movement.movetype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('movetype')
                & ns.db.groups.groupvalue.belongs(('inventory', 'store', 'tool'))
                ), ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname=="product_id":
        fields_lst.append({"fieldname":"partnumber","label":T('Product No.'),
                       "widget":INPUT(_type="text",_value="",_name="partnumber",_id=table+"_partnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="tool_id":
        fields_lst.append({"fieldname":"serial","label":T('Serial'),
                       "widget":INPUT(_type="text",_value="",_name="serial",_id=table+"_serial",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="place_id":
        fields_lst.append({"fieldname":"planumber","label":T('Place No.'),
                       "widget":INPUT(_type="text",_value="",_name="planumber",_id=table+"_planumber",_class="string"),
                       "fieldcat":1})
        continue
    elif table=="numberdef":
      if fname=="numberkey":
        fieldcat=0
    elif table=="pattern":
      if fname=="description":
        fieldcat=0
      elif fname=="transtype":  
        ns.db.pattern.transtype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('transtype')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
    elif table=="payment":
      if fname=="trans_id":
        fields_lst.append({"fieldname":"transnumber","label":T('Doc.No.'),
                       "widget":INPUT(_type="text",_value="",_name="transnumber",_id=table+"_transnumber",_class="string"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"rownumber","label":T('Row No.'),
                       "widget":INPUT(_type="text",_value="0",_name="rownumber",_id=table+"_rownumber",_class="integer"),
                       "fieldcat":0})
        continue
    elif table=="place":
      if fname=="planumber":
        fieldcat=0
      elif fname=="place_id":
        fields_lst.append({"fieldname":"ref_planumber","label":T('Ref. No.'),
                       "widget":INPUT(_type="text",_value="",_name="ref_planumber",_id=table+"_ref_planumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="placetype":  
        ns.db.place.placetype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('placetype')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname=="storetype":
        continue
    elif table=="price":
      if fname=="product_id":
        fields_lst.append({"fieldname":"partnumber","label":T('Product No.'),
                       "widget":INPUT(_type="text",_value="",_name="partnumber",_id=table+"_partnumber",_class="string"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"pricetype","label":T('Type'),
                       "widget":SELECT([OPTION("", _value=""),OPTION(T("price"), _value="price"),
                                        OPTION(T("discount"), _value="discount")
                                        ], _id=table+"_pricetype", _name="pricetype"),
                       "fieldcat":0})
        continue
      elif fname=="validfrom":
        fieldcat=0
      elif fname=="curr":
        fieldcat=0
      elif fname=="qty":
        fieldcat=0
      elif fname=="pricevalue":
        ns.db.price.pricevalue.label = T("Value/limit")
      elif fname=="calcmode":  
        ns.db.price.calcmode.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('calcmode')), 
                                                    ns.db.groups.groupvalue, '%(description)s')
    elif table=="product":
      if fname=="partnumber":
        fieldcat=0
      elif fname=="protype":  
        ns.db.product.protype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('protype')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname=="tax_id":
        taxcode = ns.db(ns.db.tax.inactive==0).select(ns.db.tax.taxcode)
        widget=SELECT(*[OPTION(field.taxcode) for field in taxcode], _id="product_taxcode", _name="taxcode")
        widget.insert(0, OPTION(""))
        fields_lst.append({"fieldname":"taxcode","label":T('Tax'), "widget":widget, "fieldcat":1})
        continue
    elif table=="project":
      if fname=="pronumber":
        fieldcat=0
      elif fname=="customer_id":
        fields_lst.append({"fieldname":"custnumber","label":T('Customer No.'),
                       "widget":INPUT(_type="text",_value="",_name="custnumber",_id=table+"_custnumber",_class="string"),
                       "fieldcat":1})
        continue
    elif table=="rate":
      if fname == "ratetype":
        fieldcat=0
        ns.db.rate.ratetype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('ratetype')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname in("ratedate","curr"):
        fieldcat=0
      elif fname=="place_id":
        fields_lst.append({"fieldname":"planumber","label":T('Place No.'),
                       "widget":INPUT(_type="text",_value="",_name="planumber",_id=table+"_planumber",_class="string"),
                       "fieldcat":0})
        continue
      elif fname == "rategroup":
        ns.db.rate.rategroup.requires = IS_EMPTY_OR(IS_IN_DB(ns.db((ns.db.groups.deleted==0)
          &ns.db.groups.groupname.like('rategroup')), ns.db.groups.groupvalue, '%(groupvalue)s'))
    elif table=="tax":
      if fname=="taxcode":
        fieldcat=0
    elif table=="tool":
      if fname=="serial":
        fieldcat=0
      elif fname=="product_id":
        fields_lst.append({"fieldname":"partnumber","label":T('Product No.'),
                       "widget":INPUT(_type="text",_value="",_name="partnumber",_id=table+"_partnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname == "toolgroup":
        ns.db.tool.toolgroup.requires = IS_EMPTY_OR(IS_IN_DB(ns.db((ns.db.groups.deleted==0)
          &ns.db.groups.groupname.like('toolgroup')), ns.db.groups.groupvalue, '%(groupvalue)s'))
    elif table=="trans":
      if fname=="transnumber":
        fieldcat=0
      elif fname == "transtype":
        ns.db.trans.transtype.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('transtype')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname == "direction":
        ns.db.trans.direction.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('direction')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname == "paidtype":
        ns.db.trans.paidtype.requires = IS_EMPTY_OR(IS_IN_DB(ns.db((ns.db.groups.deleted==0)
          &ns.db.groups.groupname.like('paidtype')), ns.db.groups.groupvalue, '%(groupvalue)s'))
      elif fname == "department":
        ns.db.trans.department.requires = IS_EMPTY_OR(IS_IN_DB(ns.db((ns.db.groups.deleted==0)
          &ns.db.groups.groupname.like('department')), ns.db.groups.groupvalue, '%(groupvalue)s'))
      elif fname == "transtate":
        ns.db.trans.transtate.requires = IS_IN_DB(ns.db(ns.db.groups.groupname.like('transtate')), 
                                                    ns.db.groups.groupvalue, '%(groupvalue)s')
      elif fname=="customer_id":
        fields_lst.append({"fieldname":"custnumber","label":T('Customer No.'),
                       "widget":INPUT(_type="text",_value="",_name="custnumber",_id=table+"_custnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="employee_id":
        fields_lst.append({"fieldname":"empnumber","label":T('Employee No.'),
                       "widget":INPUT(_type="text",_value="",_name="empnumber",_id=table+"_empnumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="project_id":
        fields_lst.append({"fieldname":"pronumber","label":T('Project No.'),
                       "widget":INPUT(_type="text",_value="",_name="pronumber",_id=table+"_pronumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="place_id":
        fields_lst.append({"fieldname":"planumber","label":T('Place No.'),
                       "widget":INPUT(_type="text",_value="",_name="planumber",_id=table+"_planumber",_class="string"),
                       "fieldcat":1})
        continue
      elif fname=="cruser_id":
        continue
    elif table=="fieldvalue":
      if fname=="fieldname":
        fields_lst.append({"fieldname":"fieldname","label":T('Fieldname'),
                       "widget":INPUT(_type="text",_value="",_name="fieldname",_id=table+"_fieldname",_class="string"),
                       "fieldcat":0})
        continue
      elif fname=="ref_id":
        fields_lst.append({"fieldname":"refnumber","label":T('Ref.No.'),
                       "widget":INPUT(_type="text",_value="",_name="refnumber",_id=table+"_refnumber",_class="string"),
                       "fieldcat":0})
        fields_lst.append({"fieldname":"rownumber","label":T('Row No.'),
                       "widget":INPUT(_type="text",_value="1",_name="rownumber",_id=table+"_rownumber",_class="integer"),
                       "fieldcat":0})
        continue
      elif fname=="fieldtype":
        ns.db.fieldvalue.fieldtype.requires = IS_IN_DB(ns.db((ns.db.groups.groupname.like('fieldtype'))
          &(ns.db.groups.groupvalue!="checkbox")&(ns.db.groups.groupvalue!="trans")), ns.db.groups.id, '%(groupvalue)s')
                                                      
    form = SQLFORM(ns.db[table])
    fields_lst.append({"fieldname":fname,"label":form.custom.label[fname],
                       "widget":form.custom.widget[fname],"fieldcat":fieldcat})
  
  if table in("address", "barcode", "contact", "currency", "customer", "employee", "event", "groups", "item", "link", "log", 
              "movement", "price", "place", "product", "project", "rate", "tax", "tool", "trans"):
    nervatype = ns.db((ns.db.groups.groupname=="nervatype")&(ns.db.groups.groupvalue==table)).select().as_list()[0]["id"]
    deffields = ns.db((ns.db.deffield.deleted==0)&(ns.db.deffield.visible==1)&(ns.db.deffield.nervatype==nervatype)
                      &(ns.db.deffield.readonly==0)&(ns.db.deffield.fieldtype==ns.db.groups.id)).select(
                        ns.db.deffield.fieldname,ns.db.groups.groupvalue,ns.db.deffield.description,ns.db.deffield.valuelist)
    for deffield in deffields:
      if deffield.groups.groupvalue=="bool":
        fields_lst.append({"fieldname":deffield.deffield.fieldname,"label":deffield.deffield.description,
                       "widget":INPUT(_type="checkbox",_value="on",_name=deffield.deffield.fieldname,_id=table+"_"+deffield.deffield.fieldname,_class="boolean"),
                       "fieldcat":2})
      elif deffield.groups.groupvalue=="integer":
        fields_lst.append({"fieldname":deffield.deffield.fieldname,"label":deffield.deffield.description,
                       "widget":INPUT(_type="text",_value="0",_name=deffield.deffield.fieldname,_id=table+"_"+deffield.deffield.fieldname,_class="integer"),
                       "fieldcat":2})
      elif deffield.groups.groupvalue=="float":
        fields_lst.append({"fieldname":deffield.deffield.fieldname,"label":deffield.deffield.description,
                       "widget":INPUT(_type="text",_value="0",_name=deffield.deffield.fieldname,_id=table+"_"+deffield.deffield.fieldname,_class="double"),
                       "fieldcat":2})
      elif deffield.groups.groupvalue=="date":
        fields_lst.append({"fieldname":deffield.deffield.fieldname,"label":deffield.deffield.description,
                       "widget":INPUT(_type="text",_value="",_name=deffield.deffield.fieldname,_id=table+"_"+deffield.deffield.fieldname,_class="date"),
                       "fieldcat":2})
      elif deffield.groups.groupvalue=="valuelist":
        widget = SELECT(*[OPTION(field) for field in deffield.deffield.valuelist.split("|")], _name=deffield.deffield.fieldname,_id=table+"_"+deffield.deffield.fieldname)
        widget.insert(0, OPTION("", _value=""))
        fields_lst.append({"fieldname":deffield.deffield.fieldname,"label":deffield.deffield.description,"widget":widget,"fieldcat":2})
      else:
        fields_lst.append({"fieldname":deffield.deffield.fieldname,"label":deffield.deffield.description,
                       "widget":INPUT(_type="text",_value="",_name=deffield.deffield.fieldname,_id=table+"_"+deffield.deffield.fieldname,_class="string"),
                       "fieldcat":2})
  return fields_lst
Exemple #17
0
    def grid(
        query,
        fields=None,
        field_id=None,
        left=None,
        join=None,  #!
        orderby=None,
        groupby=None,
        groupfields=None,  #!
        having=None,  #!
        headers={},
        searchable=False,  #True,
        sortable=True,
        paginate=20,
        pagename="page",  #!
        deletable=False,  #! True,
        editable=True,
        details=False,  #! True,
        selectable=None,
        create=False,  #!True,
        csv=False,  #!True,
        links=None,
        links_in_grid=True,
        upload='<default>',
        args=[],
        user_signature=False,  #!True,
        maxtextlengths={},
        maxtextlength=20,
        onvalidation=None,
        oncreate=None,
        onupdate=None,
        ondelete=None,
        sorter_icons=(XML('&#x2191;'), XML('&#x2193;')),
        ui='web2py',
        showbuttontext=True,
        _class="web2py_grid",
        formname='web2py_grid',
        search_widget='default',
        ignore_rw=False,
        formstyle='table3cols',
        exportclasses=None,
        formargs={},
        createargs={},
        editargs={},
        viewargs={},
    ):

        # jQuery UI ThemeRoller classes (empty if ui is disabled)
        if ui == 'jquery-ui':
            ui = dict(
                widget='ui-widget',
                header='ui-widget-header',
                content='ui-widget-content',
                default='ui-state-default',
                cornerall='ui-corner-all',
                cornertop='ui-corner-top',
                cornerbottom='ui-corner-bottom',
                button='ui-button-text-icon-primary',
                buttontext='ui-button-text',
                buttonadd='ui-icon ui-icon-plusthick',
                buttonback='ui-icon ui-icon-arrowreturnthick-1-w',
                buttonexport='ui-icon ui-icon-transferthick-e-w',
                buttondelete='ui-icon ui-icon-trash',
                buttonedit='ui-icon ui-icon-pencil',
                buttontable='ui-icon ui-icon-triangle-1-e',
                buttonview='ui-icon ui-icon-zoomin',
            )
        elif ui == 'web2py':
            ui = dict(
                widget='',
                header='',
                content='',
                default='',
                cornerall='',
                cornertop='',
                cornerbottom='',
                button='button btn',
                buttontext='buttontext button',
                buttonadd='icon plus icon-plus',
                buttonback='icon leftarrow icon-arrow-left',
                buttonexport='icon downarrow icon-download',
                buttondelete='icon trash icon-trash',
                buttonedit='icon pen icon-pencil',
                buttontable='icon rightarrow icon-arrow-right',
                buttonview='icon magnifier icon-zoom-in',
            )
        elif not isinstance(ui, dict):
            raise RuntimeError, 'SQLFORM.grid ui argument must be a dictionary'

        db = query._db
        T = current.T
        request = current.request
        session = current.session
        response = current.response
        wenabled = (not user_signature or (session.auth and session.auth.user))
        create = wenabled and create
        editable = wenabled and editable
        deletable = wenabled and deletable

        def url(**b):
            b['args'] = args + b.get('args', [])
            b['hash_vars'] = False
            b['user_signature'] = user_signature
            return URL(**b)

        def url2(**b):
            b['args'] = request.args + b.get('args', [])
            b['hash_vars'] = False
            b['user_signature'] = user_signature
            return URL(**b)

        referrer = session.get('_web2py_grid_referrer_' + formname, url())
        # if not user_signature every action is accessible
        # else forbid access unless
        # - url is based url
        # - url has valid signature (vars are not signed, only path_info)
        # = url does not contain 'create','delete','edit' (readonly)
        if user_signature:
            if not ('/'.join(str(a) for a in args) == '/'.join(request.args)
                    #              or
                    #              URL.verify(request,user_signature=user_signature,
                    #                         hash_vars=False)
                    or not ('create' in request.args or 'delete'
                            in request.args or 'edit' in request.args)):
                session.flash = T('not authorized')
                redirect(referrer)

        def gridbutton(buttonclass='buttonadd',
                       buttontext='Add',
                       buttonurl=url(args=[]),
                       callback=None,
                       delete=None,
                       trap=True):
            if showbuttontext:
                if callback:
                    return A(SPAN(_class=ui.get(buttonclass)),
                             SPAN(T(buttontext),
                                  _title=buttontext,
                                  _class=ui.get('buttontext')),
                             callback=callback,
                             delete=delete,
                             _class=trap_class(ui.get('button'), trap))
                else:
                    return A(SPAN(_class=ui.get(buttonclass)),
                             SPAN(T(buttontext),
                                  _title=buttontext,
                                  _class=ui.get('buttontext')),
                             _href=buttonurl,
                             _class=trap_class(ui.get('button'), trap))
            else:
                if callback:
                    return A(SPAN(_class=ui.get(buttonclass)),
                             callback=callback,
                             delete=delete,
                             _title=buttontext,
                             _class=trap_class(ui.get('buttontext'), trap))
                else:
                    return A(SPAN(_class=ui.get(buttonclass)),
                             _href=buttonurl,
                             _title=buttontext,
                             _class=trap_class(ui.get('buttontext'), trap))

        dbset = db(query)
        tablenames = db._adapter.tables(dbset.query)
        #if left!=None: tablenames+=db._adapter.tables(left)

        if left != None:
            if isinstance(left, list):
                for _left in left:
                    tablenames = tablenames + db._adapter.tables(_left)
            else:
                tablenames = tablenames + db._adapter.tables(left)
        if join != None:
            if isinstance(join, list):
                for _join in join:
                    tablenames = tablenames + db._adapter.tables(_join)
            else:
                tablenames = tablenames + db._adapter.tables(join)

        tables = [db[tablename] for tablename in tablenames]
        if not fields:
            fields = reduce(lambda a, b: a + b,
                            [[field for field in table] for table in tables])
        if not field_id:
            field_id = tables[0]._id
        columns = [str(field) for field in fields \
                       if field._tablename in tablenames]

        if not str(field_id) in [str(f) for f in fields]:
            fields.append(field_id)
        table = field_id.table
        tablename = table._tablename
        if upload == '<default>':
            upload = lambda filename: url(args=['download', filename])
            if len(request.args) > 1 and request.args[-2] == 'download':
                stream = response.download(request, db)
                raise HTTP(200, stream, **response.headers)

        def buttons(edit=False, view=False, record=None):
            buttons = DIV(
                gridbutton('buttonback', 'Back', referrer),
                _class='form_header row_buttons %(header)s %(cornertop)s' % ui)
            if edit and (not callable(edit) or edit(record)):
                args = ['edit', table._tablename, request.args[-1]]
                buttons.append(gridbutton('buttonedit', 'Edit',
                                          url(args=args)))
            if view:
                args = ['view', table._tablename, request.args[-1]]
                buttons.append(gridbutton('buttonview', 'View',
                                          url(args=args)))
            if record and links:
                for link in links:
                    if isinstance(link, dict):
                        buttons.append(link['body'](record))
                    elif link(record):
                        buttons.append(link(record))
            return buttons

        formfooter = DIV(
            _class='form_footer row_buttons %(header)s %(cornerbottom)s' % ui)

        create_form = update_form = view_form = search_form = None
        sqlformargs = dict(formargs)

        if create and len(request.args) > 1 and request.args[-2] == 'new':
            table = db[request.args[-1]]
            sqlformargs.update(createargs)
            create_form = SQLFORM(table,
                                  ignore_rw=ignore_rw,
                                  formstyle=formstyle,
                                  _class='web2py_form',
                                  **sqlformargs)
            create_form.process(formname=formname,
                                next=referrer,
                                onvalidation=onvalidation,
                                onsuccess=oncreate)
            res = DIV(buttons(), create_form, formfooter, _class=_class)
            res.create_form = create_form
            res.update_form = update_form
            res.view_form = view_form
            res.search_form = search_form
            return res

        elif details and len(request.args) > 2 and request.args[-3] == 'view':
            table = db[request.args[-2]]
            record = table(request.args[-1]) or redirect(URL('error'))
            sqlformargs.update(viewargs)
            view_form = SQLFORM(table,
                                record,
                                upload=upload,
                                ignore_rw=ignore_rw,
                                formstyle=formstyle,
                                readonly=True,
                                _class='web2py_form',
                                **sqlformargs)
            res = DIV(buttons(edit=editable, record=record),
                      view_form,
                      formfooter,
                      _class=_class)
            res.create_form = create_form
            res.update_form = update_form
            res.view_form = view_form
            res.search_form = search_form
            return res
#      elif editable and len(request.args)>2 and request.args[-3]=='edit':
#          table = db[request.args[-2]]
#          record = table(request.args[-1]) or redirect(URL('error'))
#          sqlformargs.update(editargs)
#          update_form = SQLFORM(table, record, upload=upload, ignore_rw=ignore_rw,
#                              formstyle=formstyle, deletable=deletable,
#                              _class='web2py_form',
#                              submit_button=T('Submit'),
#                              delete_label=T('Check to delete'),
#                              **sqlformargs)
#          update_form.process(formname=formname,
#                            onvalidation=onvalidation,
#                            onsuccess=onupdate,
#                            next=referrer)
#          res = DIV(buttons(view=details, record=record),
#                    update_form, formfooter, _class=_class)
#          res.create_form = create_form
#          res.update_form = update_form
#          res.view_form = view_form
#          res.search_form = search_form
#          return res
        elif deletable and len(
                request.args) > 2 and request.args[-3] == 'delete':
            table = db[request.args[-2]]
            if ondelete:
                ondelete(table, request.args[-1])
            ret = db(table[table._id.name] == request.args[-1]).delete()
            return ret

        exportManager = dict(
            csv_with_hidden_cols=(ExporterCSV,'CSV (hidden cols)'),
            csv=(ExporterCSV,'CSV'),
            xml=(ExporterXML, 'XML'),
            html=(ExporterHTML, 'HTML'),
            tsv_with_hidden_cols=\
                (ExporterTSV,'TSV (Excel compatible, hidden cols)'),
            tsv=(ExporterTSV, 'TSV (Excel compatible)'))
        if not exportclasses is None:
            exportManager.update(exportclasses)

        export_type = request.vars._export_type
        if export_type:
            order = request.vars.order or ''
            if sortable:
                if order and not order == 'None':
                    if order[:1] == '~':
                        sign, rorder = '~', order[1:]
                    else:
                        sign, rorder = '', order
                    tablename, fieldname = rorder.split('.', 1)
                    orderby = db[tablename][fieldname]
                    if sign == '~':
                        orderby = ~orderby

            table_fields = [f for f in fields if f._tablename in tablenames]
            if export_type in ('csv_with_hidden_cols', 'tsv_with_hidden_cols'):
                if request.vars.keywords:
                    try:
                        dbset = dbset(
                            SQLFORM.build_query(
                                fields, request.vars.get('keywords', '')))
                        rows = dbset.select(cacheable=True)
                    except Exception:
                        response.flash = T('Internal Error')
                        rows = []
                else:
                    rows = dbset.select(cacheable=True)
            else:
                rows = dbset.select(left=left,
                                    orderby=orderby,
                                    cacheable=True * columns)

            if export_type in exportManager:
                value = exportManager[export_type]
                clazz = value[0] if hasattr(value, '__getitem__') else value
                oExp = clazz(rows)
                filename = '.'.join(('rows', oExp.file_ext))
                response.headers['Content-Type'] = oExp.content_type
                response.headers['Content-Disposition'] = \
                    'attachment;filename='+filename+';'
                raise HTTP(200, oExp.export(), **response.headers)

        elif request.vars.records and not isinstance(request.vars.records,
                                                     list):
            request.vars.records = [request.vars.records]
        elif not request.vars.records:
            request.vars.records = []

        session['_web2py_grid_referrer_' + formname] = url2(vars=request.vars)
        console = DIV(_class='web2py_console %(header)s %(cornertop)s' % ui)
        error = None

        search_actions = DIV(_class='web2py_search_actions')
        if create:
            search_actions.append(
                gridbutton(buttonclass='buttonadd',
                           buttontext=T('Add'),
                           buttonurl=url(args=['new', tablename])))
            console.append(search_actions)

#      if create:
#          add = gridbutton(
#                  buttonclass='buttonadd',
#                  buttontext='Add',
#                  buttonurl=url(args=['new',tablename]))
#          if not searchable:
#              console.append(add)
        else:
            add = ''

        if searchable:
            sfields = reduce(lambda a, b: a + b,
                             [[f for f in t if f.readable] for t in tables])
            if isinstance(search_widget, dict):
                search_widget = search_widget[tablename]
            if search_widget == 'default':
                search_menu = SQLFORM.search_menu(sfields)
                search_widget = lambda sfield, url: CAT(
                    add,
                    FORM(INPUT(
                        _name='keywords',
                        _value=request.vars.keywords,
                        _id='web2py_keywords',
                        _onfocus=
                        "jQuery('#w2p_query_fields').change();jQuery('#w2p_query_panel').slideDown();"
                    ),
                         INPUT(
                             _type='submit', _value=T('Search'), _class="btn"),
                         INPUT(_type='submit',
                               _value=T('Clear'),
                               _class="btn",
                               _onclick="jQuery('#web2py_keywords').val('');"),
                         _method="GET",
                         _action=url), search_menu)
            form = search_widget and search_widget(sfields, url()) or ''
            console.append(form)
            keywords = request.vars.get('keywords', '')
            try:
                if callable(searchable):
                    subquery = searchable(sfields, keywords)
                else:
                    subquery = SQLFORM.build_query(sfields, keywords)
            except RuntimeError:
                subquery = None
                error = T('Invalid query')
        else:
            subquery = None

        if subquery:
            dbset = dbset(subquery)
        try:
            if groupby:
                nrows = len(
                    dbset.select(*groupfields,
                                 join=join,
                                 left=left,
                                 groupby=groupby,
                                 having=having,
                                 cacheable=True))
            elif left or join:
                nrows = dbset.select('count(*)',
                                     join=join,
                                     left=left,
                                     cacheable=True).first()['count(*)']

#          if left or groupby:
#              c = 'count(*)'
#              nrows = dbset.select(c,left=left,cacheable=True,
#                                   groupby=groupby).first()[c]
            else:
                nrows = dbset.count()
        except:
            nrows = 0
            error = T('Unsupported query')

        order = request.vars.order or ''
        if sortable:
            if order and not order == 'None':
                if groupby:
                    if str(groupby[0]).find(order) > -1:
                        tablename, fieldname = order.split('~')[-1].split(
                            '.', 1)
                        sort_field = db[tablename][fieldname]
                        exception = sort_field.type in ('date', 'datetime',
                                                        'time')
                        if exception:
                            orderby = (order[:1] == '~'
                                       and sort_field) or ~sort_field
                        else:
                            orderby = (order[:1] == '~'
                                       and ~sort_field) or sort_field
                    else:
                        tablename, fieldname = order.split('~')[-1].split(
                            '.', 1)
                        gfields = str(groupfields[0]).split(",")
                        for gfield in gfields:
                            if len(gfield.split(" AS ")) > 1:
                                if gfield.split(" AS ")[1] == fieldname:
                                    if str(gfield.split(" AS ")[0]).find(
                                            "SUM") > -1:
                                        sort_field = db[tablename][
                                            fieldname].sum()
                                    elif str(gfield.split(" AS ")[0]).find(
                                            "COUNT") > -1:
                                        sort_field = db[tablename][
                                            fieldname].count()
                                    elif str(gfield.split(" AS ")[0]).find(
                                            "MIN") > -1:
                                        sort_field = db[tablename][
                                            fieldname].min()
                                    elif str(gfield.split(" AS ")[0]).find(
                                            "MAX") > -1:
                                        sort_field = db[tablename][
                                            fieldname].max()
                                    elif str(gfield.split(" AS ")[0]).find(
                                            "LENGTH") > -1:
                                        sort_field = db[tablename][
                                            fieldname].len()
                                    else:
                                        break
                                    orderby = (order[:1] == '~'
                                               and ~sort_field) or sort_field
                                    break
                else:
                    tablename, fieldname = order.split('~')[-1].split('.', 1)
                    sort_field = db[tablename][fieldname]
                    exception = sort_field.type in ('date', 'datetime', 'time')
                    if exception:
                        orderby = (order[:1] == '~'
                                   and sort_field) or ~sort_field
                    else:
                        orderby = (order[:1] == '~'
                                   and ~sort_field) or sort_field

        head = TR(_class=ui.get('header'))
        if selectable:
            head.append(TH(_class=ui.get('default')))
        for field in fields:
            if columns and not str(field) in columns: continue
            if not field.readable: continue
            key = str(field)
            header = headers.get(
                str(field),
                hasattr(field, 'label') and field.label or key)
            if sortable:
                if key == order:
                    key, marker = '~' + order, sorter_icons[0]
                elif key == order[1:]:
                    marker = sorter_icons[1]
                else:
                    marker = ''
                header = A(
                    header,
                    marker,
                    _href=url(vars=dict(keywords=request.vars.keywords or '',
                                        order=key)),
                    _class=trap_class())
            head.append(TH(header, _class=ui.get('default')))

        if links and links_in_grid:
            for link in links:
                if isinstance(link, dict):
                    head.append(TH(link['header'], _class=ui.get('default')))

        # Include extra column for buttons if needed.
        include_buttons_column = (
            details or editable or deletable
            or (links and links_in_grid
                and not all([isinstance(link, dict) for link in links])))
        if include_buttons_column:
            head.insert(0, TH(_class=ui.get('default', '')))
            #  head.append(TH(_class=ui.get('default')))

        paginator = UL()
        if paginate and paginate < nrows:
            npages, reminder = divmod(nrows, paginate)
            if reminder: npages += 1
            try:
                page = int(request.vars.page or 1) - 1
            except ValueError:
                page = 0
            limitby = (paginate * page, paginate * (page + 1))

            def self_link(name, p):
                d = dict(page=p + 1)
                if order: d['order'] = order
                if request.vars.keywords: d['keywords'] = request.vars.keywords
                return A(name, _href=url(vars=d), _class=trap_class())

            NPAGES = 5  # window is 2*NPAGES
            if page > NPAGES + 1:
                paginator.append(LI(self_link('<<', 0)))
            if page > NPAGES:
                paginator.append(LI(self_link('<', page - 1)))
            pages = range(max(0, page - NPAGES), min(page + NPAGES, npages))
            for p in pages:
                if p == page:
                    paginator.append(
                        LI(A(p + 1, _onclick='return false'),
                           _class=trap_class('current')))
                else:
                    paginator.append(LI(self_link(p + 1, p)))
            if page < npages - NPAGES:
                paginator.append(LI(self_link('>', page + 1)))
            if page < npages - NPAGES - 1:
                paginator.append(LI(self_link('>>', npages - 1)))
        else:
            limitby = None

        try:
            table_fields = [f for f in fields if f._tablename in tablenames]
            if groupby:
                rows = dbset.select(*groupfields,
                                    join=join,
                                    left=left,
                                    groupby=groupby,
                                    having=having,
                                    orderby=orderby,
                                    limitby=limitby,
                                    cacheable=True)
            else:
                rows = dbset.select(join=join,
                                    left=left,
                                    orderby=orderby,
                                    limitby=limitby,
                                    cacheable=True,
                                    *table_fields)


#          rows = dbset.select(left=left,orderby=orderby,
#                              groupby=groupby,limitby=limitby,
#                              cacheable=True,*table_fields)

        except SyntaxError:
            rows = None
            error = T("Query Not Supported")
        if nrows:
            message = error or T('%(nrows)s records found') % dict(nrows=nrows)
            console.append(DIV(message, _class='web2py_counter'))

        if rows:
            htmltable = TABLE(THEAD(head))
            tbody = TBODY()
            numrec = 0
            for row in rows:
                if numrec % 2 == 0:
                    classtr = 'even'
                else:
                    classtr = 'odd'
                numrec += 1
                id = row[field_id]  #@ReservedAssignment
                if id:
                    rid = id
                    if callable(rid):  ### can this ever be callable?
                        rid = rid(row)
                    tr = TR(_id=rid, _class='%s %s' % (classtr, 'with_id'))
                else:
                    tr = TR(_class=classtr)
                if selectable:
                    tr.append(
                        INPUT(_type="checkbox",
                              _name="records",
                              _value=id,
                              value=request.vars.records))
                for field in fields:
                    if not str(field) in columns: continue
                    if not field.readable: continue
                    if field.type == 'blob': continue
                    value = row[field]
                    maxlength = maxtextlengths.get(str(field), maxtextlength)
                    if field.represent:
                        try:
                            value = field.represent(value, row)
                        except Exception:
                            try:
                                value = field.represent(
                                    value, row[field._tablename])
                            except Exception:
                                pass
                    elif field.type == 'boolean':
                        value = INPUT(_type="checkbox",
                                      _checked=value,
                                      _disabled=True)
                    elif field.type == 'upload':
                        if value:
                            if callable(upload):
                                value = A(current.T('file'),
                                          _href=upload(value))
                            elif upload:
                                value = A(current.T('file'),
                                          _href='%s/%s' % (upload, value))
                        else:
                            value = ''
                    if isinstance(value, str):
                        value = truncate_string(value, maxlength)
                    elif not isinstance(value, DIV):
                        value = field.formatter(value)
                    if not include_buttons_column:
                        tr.append(TD(value, _style="padding:10px;"))
                    else:
                        tr.append(TD(value))
                row_buttons = TD(_class='row_buttons')
                if links and links_in_grid:
                    for link in links:
                        if isinstance(link, dict):
                            tr.append(TD(link['body'](row)))
                        else:
                            if link(row):
                                row_buttons.append(link(row))
                if include_buttons_column:
                    if details and (not callable(details) or details(row)):
                        row_buttons.append(
                            gridbutton('buttonview', 'View',
                                       url(args=['view', tablename, id])))
                    if editable and (not callable(editable) or editable(row)):
                        row_buttons.append(
                            gridbutton('buttonedit', 'Edit',
                                       url(args=['edit', tablename, id])))
                    if deletable and (not callable(deletable)
                                      or deletable(row)):
                        row_buttons.append(
                            gridbutton(
                                'buttondelete',
                                'Delete',
                                callback=url(args=['delete', tablename, id]),
                                delete='tr'))
                    #tr.append(row_buttons)
                    tr.insert(0, row_buttons)
                tbody.append(tr)
            htmltable.append(tbody)
            htmltable = DIV(htmltable, _style='width:100%;overflow-x:auto')
            if selectable:
                htmltable = FORM(htmltable, INPUT(_type="submit"))
                if htmltable.process(formname=formname).accepted:  #
                    htmltable.vars.records = htmltable.vars.records or []
                    htmltable.vars.records = htmltable.vars.records if type(
                        htmltable.vars.records) == list else [
                            htmltable.vars.records
                        ]
                    records = [int(r) for r in htmltable.vars.records]
                    selectable(records)
                    redirect(referrer)
        else:
            htmltable = DIV(current.T('No records found'))

        if csv and nrows:
            export_links = []
            for k, v in sorted(exportManager.items()):
                label = v[1] if hasattr(v, "__getitem__") else k
                link = url2(vars=dict(order=request.vars.order or '',
                                      _export_type=k,
                                      keywords=request.vars.keywords or ''))
                export_links.append(A(T(label), _href=link))
            export_menu = \
                DIV(T('Export:'),_class="w2p_export_menu",*export_links)
        else:
            export_menu = None

        res = DIV(console,
                  DIV(htmltable, _class="web2py_table"),
                  _class='%s %s' % (_class, ui.get('widget')))
        if paginator.components:
            res.append(
                DIV(paginator,
                    _class="web2py_paginator %(header)s %(cornerbottom)s" %
                    ui))
        if export_menu: res.append(export_menu)
        res.create_form = create_form
        res.update_form = update_form
        res.view_form = view_form
        res.search_form = search_form
        return res
Exemple #18
0
from gluon.html import INPUT, FORM, LABEL, P, BR, SELECT, OPTION, A, CENTER, BODY, TEXTAREA, OBJECT, TAG
from gluon.validators import IS_NOT_EMPTY, IS_EXPR
from gluon.storage import Storage
from gluon import current

# web2py SQLFORM expects T in current (thread-local data) to translate messages
current.T = lambda x: x

if __name__ == '__main__':
    app = wx.App(False)
    w = gui.HtmlWindow(None, title="test html", visible=False, resizable=True)
    if '--login' in sys.argv:
        form = FORM(
            LABEL("Username", _width="25%"),
            INPUT(_type='text',
                  _name='username',
                  requires=IS_NOT_EMPTY(),
                  _width="75%"), LABEL("Password", _width="25%"),
            INPUT(_type='password',
                  _name='password',
                  requires=IS_NOT_EMPTY(),
                  _width="75%"), LABEL("Options:", _width="25%"),
            INPUT(_type='checkbox', _name='rememberme', _width="10%"),
            LABEL("Remember me", _width="65%"), LABEL("", _width="25%"),
            INPUT(_type='checkbox', _name='superuser', _width="10%"),
            LABEL("Log in as root", _width="65%"),
            CENTER(
                INPUT(_type='submit', _name='login', _value="Login"),
                BR(),
                A("lost password", _href="saraza"),
                " | ",
                A("register", _href="saraza"),