Esempio n. 1
0
 def testDateFieldConvertedToSalesforceFormat(self):
     """ Prove that DateField values get converted to the format
         expected by Salesforce (mm/dd/yyyy).
     """
     self.ff1.invokeFactory('FormDateField', 'date')
     self.ff1.date.setTitle('date')
     
     self.ff1.invokeFactory('SalesforcePFGAdapter', 'salesforce')
     self.ff1.setActionAdapter( ('salesforce',) )
     sf = self.ff1.salesforce
     
     fieldmap = sf.getFieldMap()
     fieldmap[-1]['sf_field'] = 'date'
     sf.setFieldMap(fieldmap)
     
     from DateTime import DateTime
     now = DateTime()
     now_plone = now.strftime('%m-%d-%Y %H:%M')
     
     request = FakeRequest(topic = 'test subject', replyto='*****@*****.**',
                           date = now_plone)
     from Products.Archetypes.interfaces.field import IField
     fields = [fo for fo in self.ff1._getFieldObjects() if not IField.isImplementedBy(fo)]
     sObject = self.ff1.salesforce._buildSObjectFromForm(fields, REQUEST=request)
     
     from time import strptime
     try:
         res = strptime(sObject['date'], '%Y-%m-%dT%H:%M:%SZ')
     except ValueError:
         self.fail("Doesn't look like the date was converted to Salesforce format properly.")
Esempio n. 2
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 (IField.isImplementedBy(obj) or obj.isLabel()):
                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
Esempio n. 3
0
File: form.py Progetto: dtgit/dtedu
    def fgFields(self, request=None, displayOnly=False):
        """ generate fields on the fly; also primes request with
            defaults if request is passed.
            if displayOnly, label fields are excluded.
        """

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

        myFields = []
        for obj in self._getFieldObjects(includeFSMarkers=not displayOnly):
            if IField.isImplementedBy(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() or obj.isFileField()) ):
                if not (displayOnly and obj.isLabel()):
                    myFields.append(obj.fgField)

        return myFields
Esempio n. 4
0
 def _validateOnAdd(self, field):
     """Validates fields on adding and bootstrapping
     """
     # interface test
     if not IField.isImplementedBy(field):
         raise ValueError, "Object doesn't implement IField: %r" % field
     name = field.getName()
     # two primary fields are forbidden
     if getattr(field, "primary", False):
         res = self.hasPrimary()
         if res is not False and name != res.getName():
             raise SchemaException(
                 "Tried to add '%s' as primary field "
                 "but %s already has the primary field '%s'." % (name, repr(self), res.getName())
             )
     for pname in ("accessor", "edit_accessor", "mutator"):
         res = self._checkPropertyDupe(field, pname)
         if res is not False:
             res, value = res
             raise SchemaException(
                 "Tried to add '%s' with property '%s' set "
                 "to %s but '%s' has the same value." % (name, pname, repr(value), res.getName())
             )
     # Do not allowed unqualified references
     if field.type in ("reference",):
         relationship = getattr(field, "relationship", "")
         if type(relationship) is not StringType or len(relationship) == 0:
             raise ReferenceException(
                 "Unqualified relationship or "
                 "unsupported relationship var type in field '%s'. "
                 "The relationship qualifer must be a non empty "
                 "string." % name
             )
Esempio n. 5
0
 def replaceField(self, name, field):
     if IField.isImplementedBy(field):
         oidx = self._names.index(name)
         new_name = field.getName()
         self._names[oidx] = new_name
         del self._fields[name]
         self._fields[new_name] = field
     else:
         raise ValueError, "Object doesn't implement IField: %r" % field
Esempio n. 6
0
File: form.py Progetto: dtgit/dtedu
    def fgvalidate(self, REQUEST=None, errors=None, data=None, metadata=None):
        """Validates the field data from the 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 IField.isImplementedBy(fo)]

        for obj in fields:
            field = obj.fgField

            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 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)

            adapters = self.getRawActionAdapter()
            for adapter in adapters:
                actionAdapter = getattr(self.aq_explicit, adapter, None)
                if actionAdapter is None:
                    logger.warn("Designated action adapter '%s' is missing; ignored." % 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