Exemple #1
0
    def testDeleteSavedFormInput(self):
        ''' test manage_deleteData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a few rows
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        saver.addDataRow(dict(zip(fields, ['seven', 'eight', 'nine'])))
        self.assertEqual(saver.itemsSaved(), 3)

        # saver.manage_deleteData(saver._storage.keys()[1])
        saver.delDataRow(saver.getSavedFormInputItems()[1][0])
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three'])))
        self.assertEqual(
            items[1][1],
            dict(zip(['id'] + fields,
                     [items[1][0], 'seven', 'eight', 'nine'])))
Exemple #2
0
 def __init__(self, context, request):
     self.schema = get_schema(context)
     super(EasyFormFieldsView, self).__init__(
         self.schema,
         request,
         name='fields'
     )
Exemple #3
0
    def testDeleteSavedFormInput(self):
        """ test manage_deleteData functionality """

        # set up saver
        self.createSaver()
        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        # save a few rows
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(list(zip(fields, ["one", "two", "three"]))))
        saver.addDataRow(dict(list(zip(fields, ["four", "five", "six"]))))
        saver.addDataRow(dict(list(zip(fields, ["seven", "eight", "nine"]))))
        self.assertEqual(saver.itemsSaved(), 3)

        # saver.manage_deleteData(saver._storage.keys()[1])
        saver.delDataRow(saver.getSavedFormInputItems()[1][0])
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
        self.assertEqual(
            items[1][1],
            dict(
                list(
                    zip(["id"] + fields,
                        [items[1][0], "seven", "eight", "nine"]))),
        )
Exemple #4
0
    def testFgFieldsDisplayOnly(self):
        """ test EasyForm's fgFields displayOnly option """

        ff = self.ff1
        fields = get_schema(ff)
        res = dict([(i, fields[i]) for i in fields])
        len1 = len(res)

        # TODO add label fields
        # ff.invokeFactory('FormLabelField', 'lf')
        # ff.invokeFactory('FormRichLabelField', 'rlf')

        # when displayOnly==True, fgFields should not return label fields
        self.assertEqual(len(get_schema(ff)), len1)
        # when displayOnly is omitted, all fields should be returned
        self.assertEqual(len(ff.fgFields()), len1 + 2)
Exemple #5
0
def migrate_saved_data(ploneformgen, easyform):
    for data_adapter in ploneformgen.objectValues('FormSaveDataAdapter'):
        actions = get_actions(easyform)
        action = actions.get(data_adapter.getId())
        schema = get_schema(easyform)
        if ISaveData.providedBy(action):
            cols = data_adapter.getColumnNames()
            for idx, row in enumerate(data_adapter.getSavedFormInput()):
                if len(row) != len(cols):
                    logger.warning(
                        'Number of columns does not match. Skipping row %s in '
                        'data adapter %s/%s', idx,
                        '/'.join(easyform.getPhysicalPath()),
                        data_adapter.getId())
                    continue
                data = {}
                for key, value in zip(cols, row):
                    field = schema.get(key)
                    value = value.decode('utf8')
                    if IFromUnicode.providedBy(field):
                        value = field.fromUnicode(value)
                    elif IDatetime.providedBy(field) and value:
                        value = DateTime(value).asdatetime()
                    elif IDate.providedBy(field) and value:
                        value = DateTime(value).asdatetime().date()
                    elif ISet.providedBy(field):
                        try:
                            value = set(literal_eval(value))
                        except ValueError:
                            pass
                    elif INamedBlobFileField.providedBy(field):
                        value = None
                    data[key] = value
                action.addDataRow(data)
Exemple #6
0
 def __init__(self, context, request):
     self.schema = get_schema(context)
     super(EasyFormFieldsView, self).__init__(
         self.schema,
         request,
         name='fields'
     )
    def testFgFieldsDisplayOnly(self):
        """ test EasyForm's fgFields displayOnly option """

        ff = self.ff1
        fields = get_schema(ff)
        res = dict([(i, fields[i]) for i in fields])
        len1 = len(res)

        # TODO add label fields
        # ff.invokeFactory('FormLabelField', 'lf')
        # ff.invokeFactory('FormRichLabelField', 'rlf')

        # when displayOnly==True, fgFields should not return label fields
        self.assertEqual(len(get_schema(ff)), len1)
        # when displayOnly is omitted, all fields should be returned
        self.assertEqual(len(ff.fgFields()), len1 + 2)
    def testDeleteSavedFormInput(self):
        ''' test manage_deleteData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a few rows
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        saver.addDataRow(dict(zip(fields, ['seven', 'eight', 'nine'])))
        self.assertEqual(saver.itemsSaved(), 3)

        # saver.manage_deleteData(saver._storage.keys()[1])
        saver.delDataRow(saver.getSavedFormInputItems()[1][0])
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
        self.assertEqual(
            items[1][1],
            dict(zip(['id'] + fields, [items[1][0], 'seven', 'eight', 'nine']))
        )
    def test_set_fields_updates_modified(self):
        # https://github.com/collective/collective.easyform/issues/8
        # Calling set_fields should update the modification date,
        # also in the catalog.
        from collective.easyform.api import set_fields

        # Gather the original data.
        catalog = api.portal.get_tool("portal_catalog")
        path = "/".join(self.ff1.getPhysicalPath())
        orig_modified = self.ff1.modified()
        brain = catalog.unrestrictedSearchResults(path=path)[0]
        orig_counter = catalog.getCounter()
        self.assertEqual(brain.modified, orig_modified)

        # Set the fields.
        fields = get_schema(self.ff1)
        set_fields(self.ff1, fields)

        # The modification date on the form should have been updated.
        new_modified = self.ff1.modified()
        self.assertGreater(new_modified, orig_modified)

        # The catalog brain should have the new date
        brain = catalog.unrestrictedSearchResults(path=path)[0]
        self.assertEqual(brain.modified, new_modified)
        self.assertGreater(self.ff1.modified(), orig_modified)

        # The catalog counter should have been increased.
        # This helps invalidate caches because the catalogCounter ETag changes.
        self.assertEqual(catalog.getCounter(), orig_counter + 1)
    def test_selectiveFieldMailing(self):
        """ Test selective inclusion of fields in the mailing """

        mailer = get_actions(self.ff1)['mailer']
        fields = dict(topic='test subject',
                      replyto='*****@*****.**',
                      comments='test comments')
        request = self.LoadRequestForm(**fields)

        # make sure all fields are sent unless otherwise specified
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertTrue('te=\nst subject' in self.messageBody
                        and '*****@*****.**' in self.messageBody
                        and 'test comments' in self.messageBody)

        # setting some show fields shouldn't change that
        mailer.showFields = (
            'topic',
            'comments',
        )
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertTrue('te=\nst subject' in self.messageBody
                        and '*****@*****.**' in self.messageBody
                        and 'test comments' in self.messageBody)

        # until we turn off the showAll flag
        mailer.showAll = False
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertTrue('te=\nst subject' in self.messageBody
                        and '*****@*****.**' not in self.messageBody
                        and 'test comments' in self.messageBody)

        # check includeEmpties
        mailer.includeEmpties = False

        # first see if everything's still included
        mailer.showAll = True
        self.messageText = ''
        mailer.onSuccess(fields, request)
        # look for labels
        self.assertTrue(
            self.messageBody.find('Subject') > 0
            and self.messageBody.find('Your E-Mail Address') > 0
            and self.messageBody.find('Comments') > 0)

        # now, turn off required for a field and leave it empty
        fields = get_schema(self.ff1)
        fields['comments'].required = False
        set_fields(self.ff1, fields)
        fields = {'topic': 'test subject', 'replyto': '*****@*****.**'}
        request = self.LoadRequestForm(**fields)
        self.messageText = ''
        mailer.onSuccess(fields, request)
        self.assertIn('Subject', self.messageBody)
        self.assertIn('Your E-Mail Address', self.messageBody)
        self.assertNotIn('Comments', self.messageBody)
 def afterSetUp(self):
     super(TestFunctions, self).afterSetUp()
     self.folder.invokeFactory("EasyForm", "ff1")
     self.ff1 = getattr(self.folder, "ff1")
     self.dummy_form = DummyFormView(self.ff1, self.layer["request"])
     self.dummy_form.schema = get_schema(self.ff1)
     self.dummy_form.prefix = "form"
     self.dummy_form._update()
Exemple #12
0
 def afterSetUp(self):
     super(TestFunctions, self).afterSetUp()
     self.folder.invokeFactory('EasyForm', 'ff1')
     self.ff1 = getattr(self.folder, 'ff1')
     self.dummy_form = DummyFormView(self.ff1, self.layer['request'])
     self.dummy_form.schema = get_schema(self.ff1)
     self.dummy_form.prefix = 'form'
     self.dummy_form._update()
 def testActiveAdaptersNotDuplicatedOnFormCopy(self):
     # self.loginAsPortalOwner()
     copy = self.folder.manage_copyObjects('ff1')
     new_id = self.folder.manage_pasteObjects(copy)[0]['new_id']
     ff2 = getattr(self.folder, new_id)
     active_adapters = tuple(get_actions(ff2))
     self.assertEqual(active_adapters, ('mailer',))
     active_fields = tuple(get_schema(ff2))
     self.assertEqual(active_fields, ('replyto', 'topic', 'comments'))
 def testActiveAdaptersNotDuplicatedOnFormCopy(self):
     # self.loginAsPortalOwner()
     copy = self.folder.manage_copyObjects("ff1")
     new_id = self.folder.manage_pasteObjects(copy)[0]["new_id"]
     ff2 = getattr(self.folder, new_id)
     active_adapters = tuple(get_actions(ff2))
     self.assertEqual(active_adapters, ("mailer", ))
     active_fields = tuple(get_schema(ff2))
     self.assertEqual(active_fields, ("replyto", "topic", "comments"))
Exemple #15
0
 def testActiveAdaptersNotDuplicatedOnFormCopy(self):
     # self.loginAsPortalOwner()
     copy = self.folder.manage_copyObjects('ff1')
     new_id = self.folder.manage_pasteObjects(copy)[0]['new_id']
     ff2 = getattr(self.folder, new_id)
     active_adapters = tuple(get_actions(ff2))
     self.assertEqual(active_adapters, ('mailer',))
     active_fields = tuple(get_schema(ff2))
     self.assertEqual(active_fields, ('replyto', 'topic', 'comments'))
    def test_selectiveFieldMailing(self):
        """ Test selective inclusion of fields in the mailing """

        mailer = get_actions(self.ff1)["mailer"]
        fields = dict(topic="test subject",
                      replyto="*****@*****.**",
                      comments="test comments")
        request = self.LoadRequestForm(**fields)

        # make sure all fields are sent unless otherwise specified
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertTrue("te=\nst subject" in self.messageBody
                        and "*****@*****.**" in self.messageBody
                        and "test comments" in self.messageBody)

        # setting some show fields shouldn't change that
        mailer.showFields = ("topic", "comments")
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertTrue("te=\nst subject" in self.messageBody
                        and "*****@*****.**" in self.messageBody
                        and "test comments" in self.messageBody)

        # until we turn off the showAll flag
        mailer.showAll = False
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertTrue("te=\nst subject" in self.messageBody
                        and "*****@*****.**" not in self.messageBody
                        and "test comments" in self.messageBody)

        # check includeEmpties
        mailer.includeEmpties = False

        # first see if everything's still included
        mailer.showAll = True
        self.messageText = ""
        mailer.onSuccess(fields, request)
        # look for labels
        self.assertTrue(
            self.messageBody.find("Subject") > 0
            and self.messageBody.find("Your E-Mail Address") > 0
            and self.messageBody.find("Comments") > 0)

        # now, turn off required for a field and leave it empty
        fields = get_schema(self.ff1)
        fields["comments"].required = False
        set_fields(self.ff1, fields)
        fields = {"topic": "test subject", "replyto": "*****@*****.**"}
        request = self.LoadRequestForm(**fields)
        self.messageText = ""
        mailer.onSuccess(fields, request)
        self.assertIn("Subject", self.messageBody)
        self.assertIn("Your E-Mail Address", self.messageBody)
        self.assertNotIn("Comments", self.messageBody)
    def test_basevalidator2(self):
        fields = get_schema(self.ff1)
        IFieldExtender(fields["comments"]).validators = ["isInt", "isURL"]
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse("view")
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(len(errors), 1)
    def test_talvalidator2(self):
        fields = get_schema(self.ff1)
        IFieldExtender(fields["comments"]).TValidator = "python: !value"
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse("view")
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(len(errors), 1)
    def test_talvalidator2(self):
        fields = get_schema(self.ff1)
        IFieldExtender(fields['comments']).TValidator = "python: !value"
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse('view')
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(len(errors), 1)
    def test_basevalidator2(self):
        fields = get_schema(self.ff1)
        IFieldExtender(fields['comments']).validators = ["isInt", "isURL"]
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse('view')
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(len(errors), 1)
    def test_basevalidator(self):
        fields = get_schema(self.ff1)
        IFieldExtender(fields['replyto']).validators = ["isEmail"]
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse('view')
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(errors, ())
        self.assertEqual(data, FORM_DATA)
 def getColumnNames(self):
     # """Returns a list of column names"""
     context = get_context(self)
     showFields = getattr(self, "showFields", [])
     if showFields is None:
         showFields = []
     names = [name for name, field in getFieldsInOrder(get_schema(context)) if not showFields or name in showFields]
     if self.ExtraData:
         for f in self.ExtraData:
             names.append(f)
     return names
    def testFgFieldsDisplayList(self):
        """ test EasyForm's fgFieldsDisplayList """

        # in v 1.0.2, this caused "'unicode' object has no attribute 'decode'"
        # w/ Plone 2.5.1 and Zope 2.8.7
        fields = get_schema(self.ff1)
        res = dict([(i, fields[i]) for i in fields])

        self.assertEqual(len(res), 3)
        self.assertEqual(res.keys()[0], 'replyto')
        self.assertEqual(res.values()[0]._type, unicode)
Exemple #24
0
    def testFgFieldsDisplayList(self):
        """ test EasyForm's fgFieldsDisplayList """

        # in v 1.0.2, this caused "'unicode' object has no attribute 'decode'"
        # w/ Plone 2.5.1 and Zope 2.8.7
        fields = get_schema(self.ff1)
        res = dict([(i, fields[i]) for i in fields])

        self.assertEqual(len(res), 3)
        self.assertEqual(res.keys()[0], 'replyto')
        self.assertEqual(res.values()[0]._type, unicode)
    def test_basevalidator(self):
        fields = get_schema(self.ff1)
        IFieldExtender(fields["replyto"]).validators = ["isEmail"]
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse("view")
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(errors, ())
        self.assertEqual(data, FORM_DATA)
    def get_mail_body(self, unsorted_data, request, context):
        """Returns the mail-body with footer.
        """
        schema = get_schema(context)

        form = DummyFormView(context, request)
        form.schema = schema
        form.prefix = 'form'
        form._update()
        widgets = {name: widget.render() for name, widget in form.w.items()}

        data = filter_fields(self, schema, unsorted_data)

        bodyfield = self.body_pt

        # pass both the bare_fields (fgFields only) and full fields.
        # bare_fields for compatability with older templates,
        # full fields to enable access to htmlValue
        if isinstance(self.body_pre, basestring):
            body_pre = self.body_pre
        else:
            body_pre = self.body_pre.output

        if isinstance(self.body_post, basestring):
            body_post = self.body_post
        else:
            body_post = self.body_post.output

        if isinstance(self.body_footer, basestring):
            body_footer = self.body_footer
        else:
            body_footer = self.body_footer.output

        extra = {
            'data':
            data,
            'fields':
            OrderedDict([(i, j.title) for i, j in getFieldsInOrder(schema)]),
            'widgets':
            widgets,
            'mailer':
            self,
            'body_pre':
            body_pre and lnbr(dollar_replacer(body_pre, data)),
            'body_post':
            body_post and lnbr(dollar_replacer(body_post, data)),
            'body_footer':
            body_footer and lnbr(dollar_replacer(body_footer, data)),
        }
        template = ZopePageTemplate(self.__name__)
        template.write(bodyfield)
        template = template.__of__(context)
        return template.pt_render(extra_context=extra)
def FieldsVocabularyFactory(context):
    terms = []
    if hasattr(context, "interface"):
        form = get_context(context)
    elif hasattr(context, "fields_model"):
        form = context
    else:
        return SimpleVocabulary(terms)
    fields = getFieldsInOrder(get_schema(form))
    for name, field in fields:
        terms.append(SimpleVocabulary.createTerm(name, str(name), field.title))
    return SimpleVocabulary(terms)
    def get_mail_body(self, unsorted_data, request, context):
        """Returns the mail-body with footer.
        """
        schema = get_schema(context)

        form = DummyFormView(context, request)
        form.schema = schema
        form.prefix = "form"
        form._update()
        widgets = filter_widgets(self, form.w)
        data = filter_fields(self, schema, unsorted_data)

        bodyfield = self.body_pt

        # pass both the bare_fields (fgFields only) and full fields.
        # bare_fields for compatability with older templates,
        # full fields to enable access to htmlValue
        if isinstance(self.body_pre, six.string_types):
            body_pre = self.body_pre
        else:
            body_pre = self.body_pre.output

        if isinstance(self.body_post, six.string_types):
            body_post = self.body_post
        else:
            body_post = self.body_post.output

        if isinstance(self.body_footer, six.string_types):
            body_footer = self.body_footer
        else:
            body_footer = self.body_footer.output

        extra = {
            "data":
            data,
            "fields":
            OrderedDict([(i, j.title) for i, j in getFieldsInOrder(schema)]),
            "widgets":
            widgets,
            "mailer":
            self,
            "body_pre":
            body_pre and lnbr(dollar_replacer(body_pre, data)),
            "body_post":
            body_post and lnbr(dollar_replacer(body_post, data)),
            "body_footer":
            body_footer and lnbr(dollar_replacer(body_footer, data)),
        }
        template = ZopePageTemplate(self.__name__)
        template.write(bodyfield)
        template = template.__of__(context)
        return template.pt_render(extra_context=extra)
 def __call__(self, context):
     terms = []
     if hasattr(context, 'interface'):
         form = get_context(context)
     elif hasattr(context, 'fields_model'):
         form = context
     else:
         return SimpleVocabulary(terms)
     fields = getFieldsInOrder(get_schema(form))
     for name, field in fields:
         terms.append(
             SimpleVocabulary.createTerm(name, str(name), field.title))
     return SimpleVocabulary(terms)
Exemple #30
0
 def __call__(self, context):
     terms = []
     if hasattr(context, 'interface'):
         form = get_context(context)
     elif hasattr(context, 'fields_model'):
         form = context
     else:
         return SimpleVocabulary(terms)
     fields = getFieldsInOrder(get_schema(form))
     for name, field in fields:
         terms.append(
             SimpleVocabulary.createTerm(name, str(name), field.title))
     return SimpleVocabulary(terms)
Exemple #31
0
 def getColumnNames(self):
     # """Returns a list of column names"""
     context = get_context(self)
     showFields = getattr(self, 'showFields', [])
     if showFields is None:
         showFields = []
     names = [
         name for name, field in getFieldsInOrder(get_schema(context))
         if not showFields or name in showFields
     ]
     if self.ExtraData:
         for f in self.ExtraData:
             names.append(f)
     return names
    def test_basevalidator4(self):

        request = self.layer["request"]
        request.form["form.widgets.replyto"] = None

        fields = get_schema(self.ff1)

        IFieldExtender(fields["replyto"]).validators = ["isEmail"]
        set_fields(self.ff1, fields)
        view = self.ff1.restrictedTraverse("view")
        form = view.form_instance
        form.update()

        data, errors = form.extractData()
        self.assertEqual(len(errors), 1)
Exemple #33
0
    def getColumns(self):
        """ 
        Returns a list of tuples (column names, column type name) 
        in correct order of the fields in the form
        """

        context = get_context(self)
        showFields = getattr(self, 'showFields', [])
        if showFields is None:
            showFields = []
        columns = [
            (name, type(field).__name__)
            for name, field in getFieldsInOrder(get_schema(context))
        ]
        return columns
    def getColumnTitles(self):
        # """Returns a list of column titles"""
        context = get_context(self)
        showFields = getattr(self, "showFields", [])
        if showFields is None:
            showFields = []

        names = [
            field.title
            for name, field in getFieldsInOrder(get_schema(context))
            if not showFields or name in showFields
        ]
        if self.ExtraData:
            for f in self.ExtraData:
                names.append(IExtraData[f].title)
        return names
    def getColumnTitles(self):
        # """Returns a list of column titles"""
        context = get_context(self)
        showFields = getattr(self, 'showFields', [])
        if showFields is None:
            showFields = []

        names = [
            field.title
            for name, field in getFieldsInOrder(get_schema(context))
            if not showFields or name in showFields
        ]
        if self.ExtraData:
            for f in self.ExtraData:
                names.append(IExtraData[f].title)
        return names
Exemple #36
0
    def testEditSavedFormInput(self):
        ''' test manage_saveData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a row
        fields = list(get_schema(self.ff1))
        # saver.savedFormInput = 'one,two,three'
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three'])))
Exemple #37
0
    def testSetSavedFormInput(self):
        """ test setSavedFormInput functionality """

        # set up saver
        self.createSaver()
        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]
        self.assertEqual(saver.getSavedFormInputForEdit(), "")

        # save a row
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(list(zip(fields, ["one", "two", "three"]))))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
        self.assertEqual(saver.getSavedFormInputForEdit(), "one,two,three\r\n")

        # save a couple of \n-delimited rows - \n eol
        saver.addDataRow(dict(list(zip(fields, ["four", "five", "six"]))))
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
        self.assertEqual(
            items[1][1],
            dict(
                list(zip(["id"] + fields,
                         [items[1][0], "four", "five", "six"]))),
        )
        self.assertEqual(saver.getSavedFormInputForEdit(),
                         "one,two,three\r\nfour,five,six\r\n")

        # save empty string
        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
        self.assertEqual(saver.getSavedFormInputForEdit(), "")
    def testEditSavedFormInput(self):
        ''' test manage_saveData functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']

        # save a row
        fields = list(get_schema(self.ff1))
        # saver.savedFormInput = 'one,two,three'
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
Exemple #39
0
    def testEditSavedFormInput(self):
        """ test manage_saveData functionality """

        # set up saver
        self.createSaver()
        self.assertTrue("saver" in get_actions(self.ff1))
        saver = get_actions(self.ff1)["saver"]

        # save a row
        fields = list(get_schema(self.ff1))
        # saver.savedFormInput = 'one,two,three'
        saver.addDataRow(dict(list(zip(fields, ["one", "two", "three"]))))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(
                list(zip(["id"] + fields,
                         [items[0][0], "one", "two", "three"]))),
        )
Exemple #40
0
    def testSetSavedFormInput(self):
        ''' test setSavedFormInput functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.getSavedFormInputForEdit(), '')

        # save a row
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
        self.assertEqual(saver.getSavedFormInputForEdit(), 'one,two,three\r\n')

        # save a couple of \n-delimited rows - \n eol
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
        self.assertEqual(
            items[1][1],
            dict(zip(['id'] + fields, [items[1][0], 'four', 'five', 'six']))
        )
        self.assertEqual(
            saver.getSavedFormInputForEdit(),
            'one,two,three\r\nfour,five,six\r\n'
        )

        # save empty string
        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
        self.assertEqual(saver.getSavedFormInputForEdit(), '')
    def testSetSavedFormInput(self):
        ''' test setSavedFormInput functionality '''

        # set up saver
        self.createSaver()
        self.assertTrue('saver' in get_actions(self.ff1))
        saver = get_actions(self.ff1)['saver']
        self.assertEqual(saver.getSavedFormInputForEdit(), '')

        # save a row
        fields = list(get_schema(self.ff1))
        saver.addDataRow(dict(zip(fields, ['one', 'two', 'three'])))
        self.assertEqual(saver.itemsSaved(), 1)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
        self.assertEqual(saver.getSavedFormInputForEdit(), 'one,two,three\r\n')

        # save a couple of \n-delimited rows - \n eol
        saver.addDataRow(dict(zip(fields, ['four', 'five', 'six'])))
        self.assertEqual(saver.itemsSaved(), 2)
        items = saver.getSavedFormInputItems()
        self.assertEqual(
            items[0][1],
            dict(zip(['id'] + fields, [items[0][0], 'one', 'two', 'three']))
        )
        self.assertEqual(
            items[1][1],
            dict(zip(['id'] + fields, [items[1][0], 'four', 'five', 'six']))
        )
        self.assertEqual(
            saver.getSavedFormInputForEdit(),
            'one,two,three\r\nfour,five,six\r\n'
        )

        # save empty string
        saver.clearSavedFormInput()
        self.assertEqual(saver.itemsSaved(), 0)
        self.assertEqual(saver.getSavedFormInputForEdit(), '')
Exemple #42
0
def getAllExtraFields(signupSheet):
    result = []

    extraFormReference = signupSheet.extraFieldsForm
    if extraFormReference is None:
        return result

    formObj = extraFormReference.to_object
    if formObj is None:
        return result

    schema = get_schema(formObj)
    for fieldName in schema:
        widget = schema.get(fieldName)
        item = {}
        item['name'] = fieldName
        item['label'] = widget.title
        item['description'] = widget.description
        item['required'] = widget.required
        result.append(item)

    return result
    def test_selectiveFieldMailing(self):
        """ Test selective inclusion of fields in the mailing """

        mailer = get_actions(self.ff1)['mailer']
        request = self.LoadRequestForm(
            topic='test subject',
            replyto='*****@*****.**',
            comments='test comments'
        )

        # make sure all fields are sent unless otherwise specified
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            self.messageBody.find('test subject') > 0 and
            self.messageBody.find('*****@*****.**') > 0 and
            self.messageBody.find('test comments') > 0
        )

        # setting some show fields shouldn't change that
        mailer.showFields = ('topic', 'comments',)
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            self.messageBody.find('test subject') > 0 and
            self.messageBody.find('*****@*****.**') > 0 and
            self.messageBody.find('test comments') > 0
        )

        # until we turn off the showAll flag
        mailer.showAll = False
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            self.messageBody.find('test subject') > 0 and
            self.messageBody.find('*****@*****.**') < 0 and
            self.messageBody.find('test comments') > 0
        )

        # check includeEmpties
        mailer.includeEmpties = False

        # first see if everything's still included
        mailer.showAll = True
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        # look for labels
        self.assertTrue(
            self.messageBody.find('Subject') > 0 and
            self.messageBody.find('Your E-Mail Address') > 0 and
            self.messageBody.find('Comments') > 0
        )

        # now, turn off required for a field and leave it empty
        fields = get_schema(self.ff1)
        fields['comments'].required = False
        set_fields(self.ff1, fields)
        request = self.LoadRequestForm(
            topic='test subject', replyto='*****@*****.**',)
        self.messageText = ''
        mailer.onSuccess(request.form, request)
        self.assertTrue(
            self.messageBody.find('Subject') > 0
        )
        self.assertTrue(
            self.messageBody.find('Your E-Mail Address') > 0
        )
        self.assertEqual(self.messageBody.find('Comments'), -1)
    def get_mail_body(self, unsorted_data, request, context):
        """Returns the mail-body with footer.
        """

        schema = get_schema(context)
        data = OrderedDict(
            [x for x in getFieldsInOrder(schema) if x[0] in unsorted_data]
        )

        data.update(unsorted_data)

        all_data = [
            f for f in data
            # TODO
            # if not (f.isLabel() or f.isFileField()) and not (getattr(self,
            # 'showAll', True) and f.getServerSide())]
            if not (self._is_file_data(data[f])) and not (
                getattr(self, 'showAll', True) and
                IFieldExtender(schema[f]).serverSide
            )
        ]

        # which data should we show?
        if getattr(self, 'showAll', True):
            live_data = all_data
        else:
            showFields = getattr(self, 'showFields', [])
            if showFields is None:
                showFields = []

            live_data = [
                f for f in all_data if f in showFields]

        if not getattr(self, 'includeEmpties', True):
            all_data = live_data
            live_data = [f for f in all_data if data[f]]
            for f in all_data:
                value = data[f]
                if value:
                    live_data.append(f)

        bare_data = OrderedDict([(f, data[f]) for f in live_data])
        bodyfield = self.body_pt

        # pass both the bare_fields (fgFields only) and full fields.
        # bare_fields for compatability with older templates,
        # full fields to enable access to htmlValue
        replacer = DollarVarReplacer(data).sub
        extra = {
            'data': bare_data,
            'fields': OrderedDict([
                (i, j.title)
                for i, j in getFieldsInOrder(schema)
            ]),
            'mailer': self,
            'body_pre': self.body_pre and replacer(self.body_pre),
            'body_post': self.body_post and replacer(self.body_post),
            'body_footer': self.body_footer and replacer(self.body_footer),
        }
        template = ZopePageTemplate(self.__name__)
        template.write(bodyfield)
        template = template.__of__(context)
        body = template.pt_render(extra_context=extra)

        # if isinstance(body, unicode):
        # body = body.encode("utf-8")

        # keyid = getattr(self, 'gpg_keyid', None)
        # encryption = gpg and keyid

        # if encryption:
        # bodygpg = gpg.encrypt(body, keyid)
        # if bodygpg.strip():
        # body = bodygpg

        return body
Exemple #45
0
    def get_mail_body(self, unsorted_data, request, context):
        """Returns the mail-body with footer.
        """
        schema = get_schema(context)

        form = DummyFormView(context, request)
        form.schema = schema
        form.prefix = 'form'
        form._update()
        widgets = {name: widget.render() for name, widget in form.w.items()}
        data = OrderedDict(
            [x for x in getFieldsInOrder(schema) if x[0] in unsorted_data]
        )

        data.update(unsorted_data)
        all_data = [
            f for f in data
            # TODO
            # if not (f.isLabel() or f.isFileField()) and not (getattr(self,
            # 'showAll', True) and f.getServerSide())]
            if not (self._is_file_data(data[f])) and not (
                getattr(self, 'showAll', True) and
                IFieldExtender(schema[f]).serverSide
            )
        ]

        # which data should we show?
        if getattr(self, 'showAll', True):
            live_data = all_data
        else:
            showFields = getattr(self, 'showFields', [])
            if showFields is None:
                showFields = []

            live_data = [
                f for f in all_data if f in showFields]

        if not getattr(self, 'includeEmpties', True):
            all_data = live_data
            live_data = [f for f in all_data if data[f]]
            for f in all_data:
                value = data[f]
                if value:
                    live_data.append(f)

        bare_data = OrderedDict([(f, data[f]) for f in live_data])
        bodyfield = self.body_pt

        # pass both the bare_fields (fgFields only) and full fields.
        # bare_fields for compatability with older templates,
        # full fields to enable access to htmlValue
        if isinstance(self.body_pre, basestring):
            body_pre = self.body_pre
        else:
            body_pre = self.body_pre.output

        if isinstance(self.body_post, basestring):
            body_post = self.body_post
        else:
            body_post = self.body_post.output

        if isinstance(self.body_footer, basestring):
            body_footer = self.body_footer
        else:
            body_footer = self.body_footer.output

        extra = {
            'data': bare_data,
            'fields': OrderedDict([
                (i, j.title)
                for i, j in getFieldsInOrder(schema)
            ]),
            'widgets': widgets,
            'mailer': self,
            'body_pre': body_pre and lnbr(dollar_replacer(body_pre, data)),
            'body_post': body_post and lnbr(dollar_replacer(body_post, data)),
            'body_footer': body_footer and lnbr(
                dollar_replacer(body_footer, data)),
        }
        template = ZopePageTemplate(self.__name__)
        template.write(bodyfield)
        template = template.__of__(context)
        return template.pt_render(extra_context=extra)
Exemple #46
0
 def schema(self):
     return get_schema(self.context)
 def get_schema(self):
     return get_schema(get_context(self.field))
Exemple #48
0
 def schema(self):
     return get_schema(self.context)