def render(self): self.req.content.report('header', tags.style(type='text/css')[ "@import '%s';" % self.req.get_path('assets/progress-bar/style.css') ]) assets.activate_jquery(self.req) self.req.content.report('header', tags.script(type='text/javascript', src=self.req.get_path('assets/progress-bar/support.js'))['']) element_id = self.attribs.get('element_id', 'progress-bar') attribs = self.attribs.copy() attribs.pop('element_id', None) content = tags.div(_id=element_id, _class='progress-field', **attribs)[[ tags.div(_class='progress-bar')[''], tags.div(_class='progress-text')[''] ]] if(self.callback_url): content += tags.script(type='text/javascript')[ 'waitForCompletion("%s", "%s", %d);' % (element_id, self.callback_url, self.interval) ] else: content += tags.script(type='text/javascript')[ 'setProgress("%s", %d, %d);' % (element_id, self.value, self.maxvalue) ] return content
def theme_select_autocomplete(self, form_id, element): assets.activate_jquery(self.req) self.req.content.report('header', tags.script(type="text/javascript", src=self.req.get_path("/assets/jquery/jquery.autocomplete.js"))['']) self.req.content.report('header', tags.script(type="text/javascript", src=self.req.get_path("/assets/editable-autocomplete.js"))['']) self.req.content.report('header', tags.style(type="text/css")[ """@import '%s';""" % self.req.get_path('/assets/jquery/jquery.autocomplete.css')]) self.req.content.report('header', tags.script(type="text/javascript")[ """ function formatItem(item, index, totalItems){ return item[0].replace('<', '<').replace('>', '>') } """ ]) ac_id = '%s-%s-autocomplete' % (form_id, element.name) ac_cb_id = '%s-%s-ac-callback' % (form_id, element.name) options = element.attr('options', []) optlist = repr([[v, k] for k, v in options.items()]) prefs = dict( autoFill = 1, selectFirst = 1, matchSubset = 0, selectOnly = 1, formatItem = 'formatItem', ) prefs = ','.join(['%s:%s' % (k, v) for k, v in prefs.items()]) ac_javascript = tags.script(type='text/javascript')[ '$("#%s").autocompleteArray(%s, {onItemSelect:select_item("%s"), %s});' % (ac_id, optlist, ac_cb_id, prefs) ] value = element.attr('value') if(value): label = options.get(value, None) if(label is None): label = value output = tags.input(type="text", name=element.get_element_name() + '[ac]', id=ac_id, value=label) output += tags.input(type="hidden", name=element.get_element_name() + '[value]', id=ac_cb_id, value=value) else: output = tags.input(type="text", name=element.get_element_name() + '[ac]', id=ac_id) output += tags.input(type="hidden", name=element.get_element_name() + '[value]', id=ac_cb_id) output += ac_javascript return output
def get_element(self, req, style, storable): """ @see: L{modu.editable.define.definition.get_element()} """ store = storable.get_store() assets.activate_jquery(req) req.content.report('header', tags.script(src=req.get_path('regex.js'))['']) frm = form.FormNode(self.name)(type='fieldset', style='full') frm['source']( label = 'source text', type = 'textarea', ) frm['matches']( type = 'markup', value = tags.div(id="result-breakdown")[''], ) frm['check']( type = 'submit', value = 'check', attributes = dict( id = 'regex-check-button', ) ) frm['script']( type = 'markup', value = tags.script(type='text/javascript')[""" $(document).ready(function(){ $('#regex-check-button').click(function(){ var url = $('#form-item-origin_url input').val(); var pattern = $('#form-item-item_match textarea').val(); testRegex(url, pattern); return false; }); }); """], ) return frm
def test_foreign_autocomplete_field(self): """ Test for L{modu.editable.datatypes.relational.ForeignAutocompleteField} """ test_itemdef = define.itemdef( name = relational.ForeignAutocompleteField( label = 'Name', fvalue = 'id', flabel = 'title', ftable = 'category', attributes = dict(basic_element=False), ) ) req = self.get_request() req.store.ensure_factory('test') test_storable = storable.Storable('test') test_storable.set_factory(req.store.get_factory('test')) test_storable.name = 'Test Name' itemdef_form = test_itemdef.get_form(req, test_storable) reference_form = form.FormNode('test-form') reference_form['name'](type='fieldset', style='brief', label='Name') reference_form['name']['name-autocomplete'](type='textfield', weight=0, attributes={'id':'test-form-name-autocomplete'}) reference_form['name']['ac-support'](type="markup", weight=1, value=tags.script(type='text/javascript') [("""$("#test-form-name-autocomplete").autocomplete("http://____store-test-domain____:1234567/app-test/autocomplete/test/name", { autoFill:1, selectFirst:1, matchSubset:0, selectOnly:1, formatItem:formatItem, extraParams:{t:%s}, minChars:3});""" + '$("#test-form-name-autocomplete").result(select_item_handler("test-form-name-ac-callback"));') % int(time.time())]) reference_form['name']['name'](type='hidden', weight=2, value=0, attributes={'id':'test-form-name-ac-callback'}) reference_form['save'](type='submit', value='save', weight=1000) reference_form['cancel'](type='submit', value='cancel', weight=1001) reference_form['delete'](type='submit', value='delete', weight=1002, attributes={'onClick':"return confirm('Are you sure you want to delete this record?');"}) itemdef_form_html = itemdef_form.render(req) reference_form_html = reference_form.render(req) self.failUnlessEqual(itemdef_form_html, reference_form_html, "Didn't get expected form output, got:\n%s\n instead of:\n%s" % (itemdef_form_html, reference_form_html) )
def get_element(self, req, style, storable): """ @see: L{modu.editable.define.definition.get_element()} """ frm = form.FormNode(self.name) if(style == 'search'): frm(type='textfield', size=10) else: assets.activate_jquery(req) value = getattr(storable, self.get_column_name(), '') if not(value): value = '(none)' if(style == 'listing'): frm( type = 'label', value = value, ) else: prefix = tags.label(id="%s-label" % self.name)[value] frm( type = 'hidden', value = value, attributes = dict( id = "%s-field" % self.name ), prefix = prefix, suffix = tags.script(type="text/javascript")[""" $('#%s-label').html($('#%s-field').val()); """ % (self.name, self.name) ] ) return frm
def get_element(self, req, style, storable): """ @see: L{modu.editable.define.definition.get_element()} """ mlabel = self.get('flabel', '') if(mlabel.find('.') == -1): mlabel = 'm.%s' % mlabel mlabel = self.get('flabel_sql', mlabel) where = self.get('fwhere', '') if(callable(where)): where = where(storable) elif(isinstance(where, dict)): where = sql.build_where(where) limit = 'LIMIT %d' % self.get('limit_choices', 20) ntom_query = """SELECT m.%s AS value, %s AS label FROM %s m INNER JOIN %s n2m ON m.%s = n2m.%s AND n2m.%s = %%s %s ORDER BY label %s""" % (self['fvalue'], q(mlabel), q(self['ftable']), q(self['ntof']), self.get('fvalue', 'id'), self['ntof_f_id'], self['ntof_n_id'], where, limit) store = storable.get_store() results = store.pool.runQuery(sql.interp(ntom_query, storable.get_id())) if(style == 'listing' or self.get('read_only', False)): label_value = ', '.join([result['label'] for result in results]) return form.FormNode(self.name)(type='label', value=label_value) options = dict([(str(result['value']), result['label']) for result in results]) form_name = '%s-form' % storable.get_table() ac_id = '%s-%s-autocomplete' % (form_name, self.name) select_id = '%s-foreign-select' % self.name ac_url = req.get_path(req.prepath, 'autocomplete', storable.get_table(), self.name) + '?time=' + str(time.time()) hidden_options = '' for value in options: hidden_options += tags.input(type='hidden', name='%s[%s]' % (form_name, self.name), value=value) select_frm = form.FormNode('%s-select-view' % self.name) select_frm(type='select', options=options, size=self.get('size', 5), multiple=None, suffix=hidden_options + '<br/>', attributes={'id':select_id}) prefs = 'autoFill:1, selectFirst:1, matchSubset:0, selectOnly:1, extraParams:{t:%d}, minChars:%d' % (int(time.time()), self.get('min_chars', 3)) # ac_js = '$(document).ready(function(){$("#%s").autocomplete("%s", {onItemSelect:add_foreign_item("%s", "%s"), %s});});' % (ac_id, ac_url, form_name, self.name, prefs) ac_js = """ $(document).ready(function(){ $("#%s").autocomplete("%s", {%s}); $("#%s").result(add_foreign_item("%s", "%s")); }); """ % (ac_id, ac_url, prefs, ac_id, form_name, self.name) ac_controls = tags.script(type='text/javascript')[ac_js] ac_field = form.FormNode('%s-autocomplete' % self.name) ac_field(type='textfield', weight=10, attributes={'id':ac_id}, suffix=ac_controls) req.content.report('header', tags.style(type="text/css")[ """@import '%s';""" % req.get_path('/assets/jquery/jquery.autocomplete.css')]) assets.activate_jquery(req) req.content.report('header', tags.script(type="text/javascript", src=req.get_path("/assets/jquery/jquery.autocomplete.js"))['']) req.content.report('header', tags.script(type="text/javascript", src=req.get_path("/assets/editable-autocomplete.js"))['']) frm = form.FormNode('%s-ac-fieldset' % self.name)(type='fieldset', style='brief') frm[select_frm.name] = select_frm frm[ac_field.name] = ac_field return frm
def get_element(self, req, style, storable): """ @see: L{modu.editable.define.definition.get_element()} """ form_name = '%s-form' % storable.get_table() ac_id = '%s-%s-autocomplete' % (form_name, self.name) ac_cb_id = '%s-%s-ac-callback' % (form_name, self.name) ac_url = req.get_path(req.prepath, 'autocomplete', storable.get_table(), self.name) prefs = """ autoFill:1, selectFirst:1, matchSubset:0, selectOnly:1, formatItem:formatItem, extraParams:{t:%d}, minChars:%d""" % (int(time.time()), self.get('min_chars', 3)) #ac_javascript = '$("#%s").autocomplete("%s", ' #ac_javascript += '{onItemSelect:select_item("%s"), %s});' #ac_javascript = ac_javascript % (ac_id, ac_url, ac_cb_id, prefs) ac_javascript = '$("#%s").autocomplete("%s", {%s});' % (ac_id, ac_url, prefs) ac_javascript += '$("#%s").result(select_item_handler("%s"));' % (ac_id, ac_cb_id) ac_javascript = tags.script(type='text/javascript')[ac_javascript] ac_field = form.FormNode('%s-autocomplete' % self.name) ac_field(type='textfield', weight=0, attributes={'id':ac_id}, suffix=ac_javascript) value_field = form.FormNode(self.name) value_field(type='hidden', weight=2, value=getattr(storable, self.get_column_name(), None), attributes={'id':ac_cb_id}) store = storable.get_store() value = self['fvalue'] label = self['flabel'] table = self['ftable'] if(hasattr(storable, self.get_column_name())): query = 'SELECT %s FROM %s WHERE %s = %%s' % (q(label), q(table), q(value)) field_value = getattr(storable, self.get_column_name()) if(field_value is not None): results = store.pool.runQuery(sql.interp(query, field_value)) if(results): ac_field(value=results[0][label]) else: value_field(value=0) else: value_field(value=0) if(style == 'listing' or self.get('read_only', False)): return form.FormNode(self.name)(type='label', value=ac_field.attr('value', '')) req.content.report('header', tags.style(type="text/css")[ """@import '%s';""" % req.get_path('/assets/jquery/jquery.autocomplete.css')]) req.content.report('header', tags.script(type="text/javascript")[ """ function formatItem(item, index, totalItems){ return item[0].replace('<', '<').replace('>', '>') } """ ]) assets.activate_jquery(req) req.content.report('header', tags.script(type="text/javascript", src=req.get_path("/assets/jquery/jquery.autocomplete.js"))['']) req.content.report('header', tags.script(type="text/javascript", src=req.get_path("/assets/editable-autocomplete.js"))['']) frm = form.FormNode('%s-ac-fieldset' % self.name)(type='fieldset', style='brief') frm[ac_field.name] = ac_field frm[value_field.name] = value_field return frm
def activate_jquery_ui(req): req.content.report('header', tags.script(type="text/javascript", src="//code.jquery.com/ui/%s/jquery-ui.min.js" % DEFAULT_JQUERY_UI_VERSION)[''])
def get_element(self, req, style, storable): """ @see: L{modu.editable.define.definition.get_element()} """ value = getattr(storable, self.get_column_name(), None) if(isinstance(value, (int, long, float))): value = datetime.datetime.utcfromtimestamp(value) if(style == 'search'): frm = form.FormNode(self.name) frm['from'] = self.get_form_element(req, '_detail', storable)( prefix='<div>from date:', suffix=tags.br() + '</div>', ) frm['to'] = self.get_form_element(req, '_detail', storable)( prefix='<div>to date:', suffix='</div>', ) return frm elif(style == 'listing' or (style == 'detail' and self.get('read_only', False))): if(value): output = date.strftime(value, self.get('format_string', '%B %d, %Y at %I:%M%p')) else: output = '' frm = form.FormNode(self.name) frm(type='label', value=output) return frm current_year = datetime.datetime.now().year if(value is not None): current_year = getattr(value, 'year', current_year) start_year = self.get('start_year', current_year - 2) end_year = self.get('end_year', current_year + 5) months, days = date.get_date_arrays() frm = form.FormNode(self.name) frm(type='fieldset', style='brief') frm['null'](type='checkbox', text="no value", weight=-1, suffix=tags.br(), attributes=dict(onChange='enableDateField(this);')) assets.activate_jquery(req) req.content.report('header', tags.script(type='text/javascript')[""" function enableDateField(checkboxField){ var formItem = $(checkboxField).parent().parent(); if($(checkboxField).attr('checked')){ formItem.children(':enabled').attr('disabled', true); } else{ formItem.children(':disabled').attr('disabled', false); } } """]) attribs = {} if(value is None): frm['null'](checked=True) #attribs['disabled'] = None if(self.get('default_now', False)): value = datetime.datetime.now() frm['null'](checked=False) frm['date']( type = self.get('style', 'datetime'), value = value, attributes = attribs, suffix = tags.script(type="text/javascript")[""" enableDateField($('#form-item-%s input')); """ % self.name], ) frm.validate = self.validate return frm
def test_date_field(self): """ Test for L{modu.editable.datatypes.date.DateField} """ from modu.editable.datatypes import date as date_datatype test_itemdef = define.itemdef( start_date = date_datatype.DateField( label = 'start date:', save_format = 'datetime', attributes = dict(basic_element=False), ) ) req = self.get_request([('test-form[start_date][date][month]',8), ('test-form[start_date][date][day]',25), ('test-form[start_date][date][year]',2007), ('test-form[start_date][date][hour]',23), ('test-form[start_date][date][minute]',40) ]) test_storable = storable.Storable('test') # +---------------------------+ # | from_unixtime(1190864400) | # +---------------------------+ # | 2007-09-26 23:40:00 | # +---------------------------+ test_storable.start_date = datetime.datetime.fromtimestamp(1190864400) self.failUnlessEqual(test_storable.start_date.year, 2007, 'Test year was calculated incorrectly as %s' % test_storable.start_date.year) months, days = date.get_date_arrays() hours, minutes = date.get_time_arrays() itemdef_form = test_itemdef.get_form(req, test_storable) reference_form = form.FormNode('test-form') reference_form['start_date'](type='fieldset', style='brief', label='start date:') reference_form['start_date']['null'](type='checkbox', text="no value", weight=-1, suffix=tags.br(), attributes=dict(onChange='enableDateField(this);')) reference_form['start_date']['date'](type='fieldset') reference_form['start_date']['date']['month'](type='select', weight=0, options=months, value=8) reference_form['start_date']['date']['day'](type='select', weight=1, options=days, value=25) reference_form['start_date']['date']['year'](type='textfield', weight=2, size=5, value=2007) reference_form['start_date']['date']['hour'](type='select', weight=3, options=hours, value=23) reference_form['start_date']['date']['minute'](type='select', weight=4, options=minutes, value=40) reference_form['start_date']( suffix = tags.script(type="text/javascript")[""" enableDateField($('#form-item-start_date input')); """], ) reference_form['save'](type='submit', value='save', weight=1000) reference_form['cancel'](type='submit', value='cancel', weight=1001) reference_form['delete'](type='submit', value='delete', weight=1002, attributes=dict(onClick="return confirm('Are you sure you want to delete this record?');")) itemdef_form_html = str(itemdef_form.render(req)) reference_form_html = str(reference_form.render(req)) for i in range(len(itemdef_form_html)): if(reference_form_html[i] != itemdef_form_html[i]): self.fail('Expecting %s (%s) but found %s (%s) at position %d' % ( reference_form_html[i], reference_form_html[i-20:i+20], itemdef_form_html[i], itemdef_form_html[i-20:i+20], i )) self.failUnlessEqual(itemdef_form_html, reference_form_html, "Didn't get expected form output, got:\n%s\n instead of:\n%s" % (itemdef_form_html, reference_form_html) ) test_storable.start_date = datetime.datetime.now() # this just loads the data, since there was # no submit button in the test post data itemdef_form.execute(req) test_itemdef['start_date'].update_storable(req, itemdef_form, test_storable) self.failUnlessEqual(test_storable.start_date, datetime.datetime.fromtimestamp(1190864400), 'Date was calculated incorrectly as %s' % test_storable.start_date)