Example #1
0
    def fgFields(self, request=None, displayOnly=False,
                 excludeServerSide=True):
        """ generate fields on the fly; also primes request with
            defaults if request is passed.
            if displayOnly, label fields are excluded.
        """

        self.fgMaybeForceSSL()

        if request and self.getRawOnDisplayOverride():
            # call the tales expression, passing a custom context
            self.getOnDisplayOverride()
            self.cleanExpressionContext(request=request)

        myFields = []
        for obj in self._getFieldObjects(includeFSMarkers=not displayOnly):
            if implementedOrProvidedBy(IField, obj):
                # this is a field -- not a form field -- and may be
                # added directly to the field list.
                if not displayOnly:
                    myFields.append(obj)
            else:
                if request:
                    # prime the request
                    obj.fgPrimeDefaults(request)

                if not (displayOnly and obj.isLabel()) and \
                   not (excludeServerSide and obj.getServerSide()):
                    myFields.append(obj.fgField)

        return myFields
Example #2
0
    def fgFields(self,
                 request=None,
                 displayOnly=False,
                 excludeServerSide=True):
        """ generate fields on the fly; also primes request with
            defaults if request is passed.
            if displayOnly, label fields are excluded.
        """

        self.fgMaybeForceSSL()

        if request and self.getRawOnDisplayOverride():
            # call the tales expression, passing a custom context
            self.getOnDisplayOverride()
            self.cleanExpressionContext(request=request)

        myFields = []
        for obj in self._getFieldObjects(includeFSMarkers=not displayOnly):
            if implementedOrProvidedBy(IField, obj):
                # this is a field -- not a form field -- and may be
                # added directly to the field list.
                if not displayOnly:
                    myFields.append(obj)
            else:
                if request:
                    # prime the request
                    obj.fgPrimeDefaults(request)

                if not (displayOnly and obj.isLabel()) and \
                   not (excludeServerSide and obj.getServerSide()):
                    myFields.append(obj.fgField)

        return myFields
    def displayInputs(self, request):
        """ Returns sequence of dicts {'label':fieldlabel, 'value':input}
        """
        # get a list of all candidate fields
        myFields = []
        for obj in self.aq_parent._getFieldObjects():
            if not (implementedOrProvidedBy(IField, obj) or obj.isLabel()):
                # if field list hasn't been specified explicitly, exclude server side fields
                if self.showAll and obj.getServerSide():
                    continue
                myFields.append(obj)

        # Now, determine which fields we show
        if self.showAll:
            sFields = myFields
        else:
            sFields = []
            # acquire field list from parent
            res = []
            for id in self.showFields:
                # inefficient if we get many fields
                for f in myFields:
                    if f.getId() == id:
                        sFields.append(f)
                        break

        # Now, build the results list
        res = []
        for obj in sFields:
            value = obj.htmlValue(request)
            if self.includeEmpties or (value and (value != "No Input")):
                res.append({"label": obj.fgField.widget.label, "value": value})

        return res
Example #4
0
    def actionAdaptersDL(self):
        """ returns Display List (id, title) tuples of contained adapters """

        # an adapter provides IPloneFormGenActionAdapter
        allAdapters = [(obj.getId(), obj.title) for obj in self.objectValues()
          if implementedOrProvidedBy(IPloneFormGenActionAdapter, obj)]

        if allAdapters:
            return DisplayList(allAdapters)

        return DisplayList()
Example #5
0
    def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
        if fields is None:
            fields = [
                fo for fo in self._getFieldObjects()
                if not implementedOrProvidedBy(IField, fo)
            ]

        if not errors:
            if self.getRawAfterValidationOverride():
                # evaluate the override.
                # In case we end up traversing to a template,
                # we need to make sure we don't clobber
                # the expression context.
                self.getAfterValidationOverride()
                self.cleanExpressionContext(request=self.REQUEST)

            # get a list of adapters with no duplicates, retaining order
            adapters = []
            for adapter in self.getRawActionAdapter():
                if adapter not in adapters:
                    adapters.append(adapter)

            for adapter in adapters:
                actionAdapter = getattr(self.aq_explicit, adapter, None)
                if actionAdapter is None:
                    logger.warn(
                        "Designated action adapter '%s' is missing; ignored. "
                        "Removing it from active list." % adapter)
                    self.toggleActionActive(adapter)
                else:
                    # Now, see if we should execute it.
                    # Check to see if execCondition exists and has contents
                    if safe_hasattr(actionAdapter, 'execCondition') and \
                      len(actionAdapter.getRawExecCondition()):
                        # evaluate the execCondition.
                        # create a context for expression evaluation
                        context = getExprContext(self, actionAdapter)
                        doit = actionAdapter.getExecCondition(
                            expression_context=context)
                    else:
                        # no reason not to go ahead
                        doit = True

                    if doit:
                        result = actionAdapter.onSuccess(fields, \
                                                         REQUEST=REQUEST)
                        if type(result) is type({}) and len(result):
                            # return the dict, which hopefully uses
                            # field ids or FORM_ERROR_MARKER for keys
                            return result

        return errors
Example #6
0
    def actionAdaptersDL(self):
        """ returns Display List (id, title) tuples of contained adapters """

        # an adapter provides IPloneFormGenActionAdapter
        allAdapters = [
            (obj.getId(), obj.title) for obj in self.objectValues()
            if implementedOrProvidedBy(IPloneFormGenActionAdapter, obj)
        ]

        if allAdapters:
            return DisplayList(allAdapters)

        return DisplayList()
Example #7
0
    def fgProcessActionAdapters(self, errors, fields=None, REQUEST=None):
        if fields is None:
            fields = [fo for fo in self._getFieldObjects()
                      if not implementedOrProvidedBy(IField, fo)]

        if not errors:
            if self.getRawAfterValidationOverride():
                # evaluate the override.
                # In case we end up traversing to a template,
                # we need to make sure we don't clobber
                # the expression context.
                self.getAfterValidationOverride()
                self.cleanExpressionContext(request=self.REQUEST)

            # get a list of adapters with no duplicates, retaining order
            adapters = []
            for adapter in self.getRawActionAdapter():
                if adapter not in adapters:
                    adapters.append(adapter)

            for adapter in adapters:
                actionAdapter = getattr(self.aq_explicit, adapter, None)
                if actionAdapter is None:
                    logger.warn(
                      "Designated action adapter '%s' is missing; ignored. "
                      "Removing it from active list." %
                      adapter)
                    self.toggleActionActive(adapter)
                else:
                    # Now, see if we should execute it.
                    # Check to see if execCondition exists and has contents
                    if safe_hasattr(actionAdapter, 'execCondition') and \
                      len(actionAdapter.getRawExecCondition()):
                        # evaluate the execCondition.
                        # create a context for expression evaluation
                        context = getExprContext(self, actionAdapter)
                        doit = actionAdapter.getExecCondition(
                          expression_context=context)
                    else:
                        # no reason not to go ahead
                        doit = True

                    if doit:
                        result = actionAdapter.onSuccess(fields, \
                                                         REQUEST=REQUEST)
                        if type(result) is type({}) and len(result):
                            # return the dict, which hopefully uses
                            # field ids or FORM_ERROR_MARKER for keys
                            return result

        return errors
def form_adapter_pasted(form_adapter, event):
    """If an action adapter is pasted into the form, add it to the form's 
       list of active adapters. We only need to do anything if the action
       adapter isn't newly created in the portal_factory.
    """
    form_adapter = aq_inner(form_adapter)
    if implementedOrProvidedBy(IFactoryTool, aq_parent(aq_parent(form_adapter))):
        return
        
    form = aq_parent(form_adapter)
    adapters = list(form.actionAdapter)
    if form_adapter.id not in adapters:
        adapters.append(form_adapter.id)
        form.setActionAdapter(adapters)
Example #9
0
    def thanksPageVocabulary(self):
        """ returns a DisplayList of contained page-ish documents """

        propsTool = getToolByName(self, 'portal_properties')
        siteProperties = getattr(propsTool, 'site_properties')
        defaultPageTypes = siteProperties.getProperty('default_page_types')

        tpages = [('', _(u'vocabulary_none_text', u'None')), ]

        for obj in self.objectValues():
            if implementedOrProvidedBy(IPloneFormGenThanksPage, obj) or \
              getattr(obj.aq_explicit, 'portal_type', 'none') in defaultPageTypes:
                tpages.append((obj.getId(), obj.title))

        return DisplayList(tpages)
Example #10
0
    def thanksPageVocabulary(self):
        """ returns a DisplayList of contained page-ish documents """

        propsTool = getToolByName(self, 'portal_properties')
        siteProperties = getattr(propsTool, 'site_properties')
        defaultPageTypes = siteProperties.getProperty('default_page_types')

        tpages = [
            ('', _(u'vocabulary_none_text', u'None')),
        ]

        for obj in self.objectValues():
            if implementedOrProvidedBy(IPloneFormGenThanksPage, obj) or \
              getattr(obj.aq_explicit, 'portal_type', 'none') in defaultPageTypes:
                tpages.append((obj.getId(), obj.title))

        return DisplayList(tpages)
Example #11
0
    def displayInputs(self):
        """ Returns sequence of dicts {'label':fieldlabel, 'value':input}
        """
        # get a list of all candidate fields
        request = self.request
        context = self.context
        myFields = []
        preview_hidden = request.get('preview_hidden', ())
        tp = getattr(context, context.thanksPage, None)
        if not tp:
            return []
        for obj in context._getFieldObjects():
            if (not implementedOrProvidedBy(IField, obj) or obj.isLabel()):
                # if field list hasn't been specified explicitly, exclude server side fields
                if tp.showAll and obj.getServerSide():
                    continue

                if obj.getId() not in preview_hidden:
                    myFields.append(obj)

        # Now, determine which fields we show
        if tp.showAll:
            sFields = myFields
        else:
            sFields = []
            # acquire field list from parent
            res = []
            for id in tp.showFields:
                # inefficient if we get many fields
                for f in myFields:
                    if f.getId() == id:
                        sFields.append(f)
                        break

        # Now, build the results list
        res = []
        for obj in sFields:
            value = obj.htmlValue(request)
            if tp.includeEmpties or (value and (value != 'No Input')):
                res.append({
                    'label': obj.fgField.widget.label,
                    'value': value,
                    })

        return res
Example #12
0
    def displayInputs(self, request):
        """ Returns sequence of dicts {'label':fieldlabel, 'value':input}
        """
        # get a list of all candidate fields
        myFields = []
        for obj in self.aq_parent._getFieldObjects():
            if not (implementedOrProvidedBy(IField, obj) or obj.isLabel()):
                # if field list hasn't been specified explicitly, exclude server side fields
                if self.showAll and obj.getServerSide():
                    continue 
                myFields.append(obj)

        # Now, determine which fields we show
        if self.showAll:
            sFields = myFields
        else:
            sFields = []
            # acquire field list from parent
            res = []
            for id in self.showFields:
                # inefficient if we get many fields
                for f in myFields:
                    if f.getId() == id:
                        sFields.append(f)
                        break

        # Now, build the results list
        res = []
        for obj in sFields:
            value = obj.htmlValue(request)
            if self.includeEmpties or (value and (value != 'No Input')):
                res.append( {
                    'label' : obj.fgField.widget.label,
                    'value' : value, 
                    } )
            
        return res
Example #13
0
    def fgvalidate(self,
                   REQUEST=None,
                   errors=None,
                   data=None,
                   metadata=None,
                   skip_action_adapters=False):
        """Validates the field data from the request.
        """

        if getattr(self, 'checkAuthenticator', True):
            # CSRF check.
            plone.protect.CheckAuthenticator(REQUEST)
            plone.protect.PostOnly(REQUEST)

        _marker = []
        if errors is None:
            errors = {}
        if errors:
            return errors

        # Get all the form fields. Exclude actual IField fields.
        fields = [fo for fo in self._getFieldObjects()
                  if not implementedOrProvidedBy(IField, fo)]
        for obj in fields:
            field = obj.fgField

            if obj.isLabel() and obj.meta_type != 'FormRichLabelField':
                REQUEST.form[obj.__name__] = '1'

            if obj.getServerSide():
                # for server-side only fields, use the default value
                # even if something was in the request
                if obj.__name__ in REQUEST.form:
                    del REQUEST.form[obj.__name__]
                obj.fgPrimeDefaults(REQUEST)

            result = field.widget.process_form(self, field, REQUEST.form,
                                               empty_marker=_marker)

            if result is None or result is _marker:
                #XXX Make this smarter
                value = ''
            else:
                value = result[0]

            # workaround what I consider a Zope marshalling error:
            # the production of lists like ['one', ''] and ['']
            # for list fields. No need to worry about polymorphism here,
            # as this is a very particular case.
            if isinstance(value, type([])) and len(value) and \
              (type(value[-1]) in StringTypes) and (len(value[-1]) == 0):
                value.pop()

            # eliminate trailing white space in string types.
            if safe_hasattr(value, 'rstrip'):
                newvalue = value.rstrip()
                if newvalue != value:
                    value = newvalue
                    # since strings are immutable,
                    # we have to manually store it back to the request
                    if safe_hasattr(REQUEST, 'form'):
                        REQUEST.form[obj.getFieldFormName()] = value

            # Archetypes field validation
            res = field.validate(instance=self, value=value, errors=errors,
                                 REQUEST=REQUEST)

            if not res:
                # give the field itself an opportunity to validate.
                res = obj.specialValidator(value, field, REQUEST, errors)

            if res:
                errors[field.getName()] = \
                  validationMessages.cleanupMessage(res, self.REQUEST, self)
            elif shasattr(obj, 'getFgTValidator') and obj.getRawFgTValidator():
                # process the override validator TALES expression

                # create a context for expression evaluation
                context = getExprContext(self, obj)

                # put this field's input (from request)
                # into the context globals as 'value'
                context.setGlobal('value',
                                  REQUEST.form.get(obj.getFieldFormName(),
                                  None))

                # call the tales expression, passing our custom context
                cerr = obj.getFgTValidator(expression_context=context)
                if cerr:
                    errors[field.getName()] = cerr

        if not skip_action_adapters:
            return self.fgProcessActionAdapters(errors, fields, REQUEST)

        return errors
Example #14
0
    def fgvalidate(self,
                   REQUEST=None,
                   errors=None,
                   data=None,
                   metadata=None,
                   skip_action_adapters=False):
        """Validates the field data from the request.
        """

        if getattr(self, 'checkAuthenticator', True):
            # CSRF check.
            plone.protect.CheckAuthenticator(REQUEST)
            plone.protect.PostOnly(REQUEST)

        _marker = []
        if errors is None:
            errors = {}
        if errors:
            return errors

        # Get all the form fields. Exclude actual IField fields.
        fields = [
            fo for fo in self._getFieldObjects()
            if not implementedOrProvidedBy(IField, fo)
        ]
        for obj in fields:
            field = obj.fgField

            if obj.isLabel() and obj.meta_type != 'FormRichLabelField':
                REQUEST.form[obj.__name__] = '1'

            if obj.getServerSide():
                # for server-side only fields, use the default value
                # even if something was in the request
                if obj.__name__ in REQUEST.form:
                    del REQUEST.form[obj.__name__]
                obj.fgPrimeDefaults(REQUEST)

            result = field.widget.process_form(self,
                                               field,
                                               REQUEST.form,
                                               empty_marker=_marker)

            if result is None or result is _marker:
                #XXX Make this smarter
                value = ''
            else:
                value = result[0]

            # workaround what I consider a Zope marshalling error:
            # the production of lists like ['one', ''] and ['']
            # for list fields. No need to worry about polymorphism here,
            # as this is a very particular case.
            if isinstance(value, type([])) and len(value) and \
              (type(value[-1]) in StringTypes) and (len(value[-1]) == 0):
                value.pop()

            # eliminate trailing white space in string types.
            if safe_hasattr(value, 'rstrip'):
                newvalue = value.rstrip()
                if newvalue != value:
                    value = newvalue
                    # since strings are immutable,
                    # we have to manually store it back to the request
                    if safe_hasattr(REQUEST, 'form'):
                        REQUEST.form[obj.getFieldFormName()] = value

            # Archetypes field validation
            res = field.validate(instance=self,
                                 value=value,
                                 errors=errors,
                                 REQUEST=REQUEST)

            if not res:
                # give the field itself an opportunity to validate.
                res = obj.specialValidator(value, field, REQUEST, errors)

            if res:
                errors[field.getName()] = \
                  validationMessages.cleanupMessage(res, self.REQUEST, self)
            elif shasattr(obj, 'getFgTValidator') and obj.getRawFgTValidator():
                # process the override validator TALES expression

                # create a context for expression evaluation
                context = getExprContext(self, obj)

                # put this field's input (from request)
                # into the context globals as 'value'
                context.setGlobal(
                    'value', REQUEST.form.get(obj.getFieldFormName(), None))

                # call the tales expression, passing our custom context
                cerr = obj.getFgTValidator(expression_context=context)
                if cerr:
                    errors[field.getName()] = cerr

        if not skip_action_adapters:
            return self.fgProcessActionAdapters(errors, fields, REQUEST)

        return errors