class CWUploadForm(FieldsForm): """ Create a submit button. """ __regid__ = "upload-form" title = _("Upload form") form_buttons = [formwidgets.SubmitButton(cwaction="apply")]
class RegistrationForm(forms.FieldsForm): """ Create an anonymous registration form. """ __regid__ = "registration" domid = "registrationForm" title = _("Registration form") form_buttons = [formwidgets.SubmitButton()] @property def action(self): return self._cw.build_url(u"registration_sendmail") # Properly name fields according to validation errors that may be raised by # the register_user service login = formfields.StringField(widget=formwidgets.TextInput(), role="subject", label=_("Login"), help=_("Please enter your CEA login."), required=True) upassword = formfields.StringField(widget=formwidgets.PasswordInput(), role="subject", required=True) captcha = formfields.StringField( widget=captcha.CaptchaWidget(), required=True, label=_("Captcha"), help=_("Please copy the letters from the image"))
class LogFormOrbui(LogForm): """overwrites the original LogForm class to change look and functionality of buttons """ needs_css = () form_buttons = [ fw.SubmitButton(label=_('log in'), attrs={'class': 'btn btn-primary'}) ]
def call(self): req = self._cw.reset_headers() w = self.w title = self._cw._('an error occurred') w(u'<h2>%s</h2>' % title) ex, exclass, excinfo = self._excinfo() if excinfo is not None and self._cw.vreg.config['print-traceback']: if exclass is None: w(u'<div class="tb">%s</div>' % xml_escape(ex).replace("\n", "<br />")) else: w(u'<div class="tb">%s: %s</div>' % (exclass, xml_escape(ex).replace("\n", "<br />"))) w(u'<hr />') w(u'<div class="tb">%s</div>' % html_traceback(excinfo, ex, '')) else: w(u'<div class="tb">%s</div>' % (xml_escape(ex).replace("\n", "<br />"))) # if excinfo is not None, it's probably not a bug if excinfo is None: return if self._cw.cnx: vcconf = self._cw.cnx.repo.get_versions() w(u"<div>") eversion = vcconf.get('cubicweb', self._cw._('no version information')) # NOTE: tuple wrapping needed since eversion is itself a tuple w(u"<b>CubicWeb version:</b> %s<br/>\n" % (eversion, )) cversions = [] for cube in self._cw.vreg.config.cubes(): cubeversion = vcconf.get(cube, self._cw._('no version information')) w(u"<b>Cube %s version:</b> %s<br/>\n" % (cube, cubeversion)) cversions.append((cube, cubeversion)) w(u"</div>") # creates a bug submission link if submit-mail is set if self._cw.vreg.config['submit-mail']: form = self._cw.vreg['forms'].select('base', self._cw, rset=None, mainform=False) binfo = text_error_description(ex, excinfo, req, eversion, cversions) form.add_hidden( 'description', binfo, # we must use a text area to keep line breaks widget=wdgs.TextArea({'class': 'hidden'})) # add a signature so one can't send arbitrary text form.add_hidden('__signature', req.vreg.config.sign_text(binfo)) form.add_hidden('__bugreporting', '1') form.form_buttons = [wdgs.SubmitButton(MAIL_SUBMIT_MSGID)] form.action = req.build_url('reportbug') form.render(w=w)
class ChangeStateForm(forms.CompositeEntityForm): # set dom id to ensure there is no conflict with edition form (see # session_key() implementation) __regid__ = domid = 'changestate' form_renderer_id = 'base' # don't want EntityFormRenderer form_buttons = [ fwdgs.SubmitButton(), fwdgs.Button( stdmsgs.BUTTON_CANCEL, {'class': fwdgs.Button.css_class + ' cwjs-edition-cancel'}) ]
class SparqlForm(forms.FieldsForm): __regid__ = 'sparql' sparql = formfields.StringField(help=_('type here a sparql query')) resultvid = formfields.StringField(choices=((_('table'), 'table'), (_('sparql xml'), 'sparqlxml')), widget=fwdgs.Radio, value='table') form_buttons = [fwdgs.SubmitButton()] @property def action(self): return self._cw.url()
def form_buttons(cls): # we use a property because sub class will need to define their own onclick_args. # Therefor we can't juste make the string formating when instanciating this class onclick = cls.onclick_base % cls.onclick_args form_buttons = [ fw.SubmitButton(label=_('log in'), attrs={'class': 'loginButton'}), fw.ResetButton(label=_('cancel'), attrs={ 'class': 'loginButton', 'onclick': onclick }), ] ## Can't shortcut next access because __dict__ is a "dictproxy" which ## does not support items assignement. # cls.__dict__['form_buttons'] = form_buttons return form_buttons
def owned_by_edit_form(self, entity): self.w('<h3>%s</h3>' % self._cw._('Ownership')) msg = self._cw._('ownerships have been changed') form = self._cw.vreg['forms'].select( 'base', self._cw, entity=entity, form_renderer_id='onerowtable', submitmsg=msg, form_buttons=[wdgs.SubmitButton()], domid='ownership%s' % entity.eid, __redirectvid='security', __redirectpath=entity.rest_path()) field = guess_field(entity.e_schema, self._cw.vreg.schema['owned_by'], req=self._cw) form.append_field(field) form.render(w=self.w, display_progress_div=False)
class TableEditForm(forms.CompositeForm): __regid__ = 'muledit' domid = 'entityForm' onsubmit = "return validateForm('%s', null);" % domid form_buttons = [ fw.SubmitButton(_('validate modifications on selected items')), fw.ResetButton(_('revert changes')) ] def __init__(self, req, rset, **kwargs): kwargs.setdefault('__redirectrql', rset.printable_rql()) super(TableEditForm, self).__init__(req, rset=rset, **kwargs) for row in range(len(self.cw_rset)): form = self._cw.vreg['forms'].select('edition', self._cw, rset=self.cw_rset, row=row, formtype='muledit', copy_nav_params=False, mainform=False) # XXX rely on the EntityCompositeFormRenderer to put the eid input form.remove_field(form.field_by_name('eid')) self.add_subform(form)
class AutomaticEntityForm(forms.EntityFieldsForm): """AutomaticEntityForm is an automagic form to edit any entity. It is designed to be fully generated from schema but highly configurable through uicfg. Of course, as for other forms, you can also customise it by specifying various standard form parameters on selection, overriding, or adding/removing fields in selected instances. """ __regid__ = 'edition' cwtarget = 'eformframe' cssclass = 'entityForm' copy_nav_params = True form_buttons = [ fw.SubmitButton(), fw.Button(stdmsgs.BUTTON_APPLY, cwaction='apply'), fw.Button(stdmsgs.BUTTON_CANCEL, {'class': fw.Button.css_class + ' cwjs-edition-cancel'}) ] # for attributes selection when searching in uicfg.autoform_section formtype = 'main' # set this to a list of [(relation, role)] if you want to explictily tell # which relations should be edited display_fields = None # action on the form tag _default_form_action_path = 'validateform' @iclassmethod def field_by_name(cls_or_self, name, role=None, eschema=None): """return field with the given name and role. If field is not explicitly defined for the form but `eclass` is specified, guess_field will be called. """ try: return super(AutomaticEntityForm, cls_or_self).field_by_name(name, role, eschema) except f.FieldNotFound: if name == '_cw_generic_field' and not isinstance( cls_or_self, type): return cls_or_self._generic_relations_field() raise # base automatic entity form methods ####################################### def __init__(self, *args, **kwargs): super(AutomaticEntityForm, self).__init__(*args, **kwargs) self.uicfg_afs = self._cw.vreg['uicfg'].select( 'autoform_section', self._cw, entity=self.edited_entity) entity = self.edited_entity if entity.has_eid(): entity.complete() for rtype, role in self.editable_attributes(): try: self.field_by_name(str(rtype), role) continue # explicitly specified except f.FieldNotFound: # has to be guessed try: field = self.field_by_name(str(rtype), role, eschema=entity.e_schema) self.fields.append(field) except f.FieldNotFound: # meta attribute such as <attr>_format continue if self.fieldsets_in_order: fsio = list(self.fieldsets_in_order) else: fsio = [None] self.fieldsets_in_order = fsio # add fields for relation whose target should have an inline form for formview in self.inlined_form_views(): field = self._inlined_form_view_field(formview) self.fields.append(field) if field.fieldset not in fsio: fsio.append(field.fieldset) if self.formtype == 'main': # add the generic relation field if necessary if entity.has_eid() and (self.display_fields is None or '_cw_generic_field' in self.display_fields): try: field = self.field_by_name('_cw_generic_field') except f.FieldNotFound: # no editable relation pass else: self.fields.append(field) if field.fieldset not in fsio: fsio.append(field.fieldset) self.maxrelitems = self._cw.property_value('navigation.related-limit') self.force_display = bool(self._cw.form.get('__force_display')) fnum = len(self.fields) self.fields.sort(key=lambda f: f.order is None and fnum or f.order) @property def related_limit(self): if self.force_display: return None return self.maxrelitems + 1 # autoform specific fields ################################################# def _generic_relations_field(self): srels_by_cat = self.editable_relations() if not srels_by_cat: raise f.FieldNotFound('_cw_generic_field') fieldset = 'This %s:' % self.edited_entity.e_schema return GenericRelationsField(self.editable_relations(), fieldset=fieldset, label=None) def _inlined_form_view_field(self, view): # XXX allow more customization kwargs = self.uicfg_affk.etype_get(self.edited_entity.e_schema, view.rtype, view.role, view.etype) if kwargs is None: kwargs = {} return InlinedFormField(view=view, **kwargs) # methods mapping edited entity relations to fields in the form ############ def _relations_by_section(self, section, permission='add', strict=False): """return a list of (relation schema, target schemas, role) matching given category(ies) and permission """ return self.uicfg_afs.relations_by_section(self.edited_entity, self.formtype, section, permission, strict) def editable_attributes(self, strict=False): """return a list of (relation schema, role) to edit for the entity""" if self.display_fields is not None: schema = self._cw.vreg.schema for rtype, role in self.display_fields: yield (schema[rtype], role) return if self.edited_entity.has_eid( ) and not self.edited_entity.cw_has_perm('update'): return action = 'update' if self.edited_entity.has_eid() else 'add' for rtype, _, role in self._relations_by_section( 'attributes', action, strict): yield (rtype, role) def editable_relations(self): """return a sorted list of (relation's label, relation'schema, role) for relations in the 'relations' section """ return sorted(self.iter_editable_relations()) def iter_editable_relations(self): for rschema, _, role in self._relations_by_section('relations', strict=True): yield (rschema.display_name(self.edited_entity._cw, role, self.edited_entity.cw_etype), rschema, role) def inlined_relations(self): """return a list of (relation schema, target schemas, role) matching given category(ies) and permission """ return self._relations_by_section('inlined') # inlined forms control #################################################### def inlined_form_views(self): """Yield inlined form views (hosting the inlined form object) """ entity = self.edited_entity for rschema, ttypes, role in self.inlined_relations(): # show inline forms only if there's one possible target type # for rschema if len(ttypes) != 1: self.warning( 'entity related by the %s relation should have ' 'inlined form but there is multiple target types, ' 'dunno what to do', rschema) continue tschema = ttypes[0] ttype = tschema.type existing = bool(entity.related( rschema, role)) if entity.has_eid() else False for formview in self.inline_edition_form_view( rschema, ttype, role): yield formview existing = True card = rschema.role_rdef(entity.e_schema, ttype, role).role_cardinality(role) if self.should_display_inline_creation_form( rschema, existing, card): for formview in self.inline_creation_form_view( rschema, ttype, role): yield formview existing = True # we can create more than one related entity, we thus display a link # to add new related entities if self.must_display_add_new_relation_link(rschema, role, tschema, ttype, existing, card): addnewlink = self._cw.vreg['views'].select( 'inline-addnew-link', self._cw, etype=ttype, rtype=rschema, role=role, card=card, peid=self.edited_entity.eid, petype=self.edited_entity.e_schema, pform=self) yield addnewlink def should_display_inline_creation_form(self, rschema, existing, card): """return true if a creation form should be inlined by default true if there is no related entity and we need at least one """ return not existing and card in '1+' def should_display_add_new_relation_link(self, rschema, existing, card): """return true if we should add a link to add a new creation form (through ajax call) by default true if there is no related entity or if the relation has multiple cardinality """ return not existing or card in '+*' def must_display_add_new_relation_link(self, rschema, role, tschema, ttype, existing, card): """return true if we must add a link to add a new creation form (through ajax call) by default true if there is no related entity or if the relation has multiple cardinality and it is permitted to add the inlined object and relation. """ return (self.should_display_add_new_relation_link( rschema, existing, card) and self.check_inlined_rdef_permissions( rschema, role, tschema, ttype)) def check_inlined_rdef_permissions(self, rschema, role, tschema, ttype): """return true if permissions are granted on the inlined object and relation""" if not tschema.has_perm(self._cw, 'add'): return False entity = self.edited_entity rdef = entity.e_schema.rdef(rschema, role, ttype) if entity.has_eid(): if role == 'subject': rdefkwargs = {'fromeid': entity.eid} else: rdefkwargs = {'toeid': entity.eid} return rdef.has_perm(self._cw, 'add', **rdefkwargs) return rdef.may_have_permission('add', self._cw) def should_hide_add_new_relation_link(self, rschema, card): """return true if once an inlined creation form is added, the 'add new' link should be hidden by default true if the relation has single cardinality """ return card in '1?' def inline_edition_form_view(self, rschema, ttype, role): """yield inline form views for already related entities through the given relation """ entity = self.edited_entity related = entity.has_eid() and entity.related(rschema, role) if related: vvreg = self._cw.vreg['views'] # display inline-edition view for all existing related entities for i, relentity in enumerate(related.entities()): if relentity.cw_has_perm('update'): yield vvreg.select('inline-edition', self._cw, rset=related, row=i, col=0, etype=ttype, rtype=rschema, role=role, peid=entity.eid, pform=self) def inline_creation_form_view(self, rschema, ttype, role): """yield inline form views to a newly related (hence created) entity through the given relation """ try: yield self._cw.vreg['views'].select( 'inline-creation', self._cw, etype=ttype, rtype=rschema, role=role, peid=self.edited_entity.eid, petype=self.edited_entity.e_schema, pform=self) except NoSelectableObject: # may be raised if user doesn't have the permission to add ttype entities (no checked # earlier) or if there is some custom selector on the view pass