Example #1
0
class IExtraData(Interface):
    dt = zope.schema.TextLine(title=_(u"Posting Date/Time"),
                              required=False,
                              default=u"",
                              missing_value=u"")
    HTTP_X_FORWARDED_FOR = zope.schema.TextLine(
        title=_(
            u"extra_header",
            default=u"${name} Header",
            mapping={u"name": u"HTTP_X_FORWARDED_FOR"},
        ),
        required=False,
        default=u"",
        missing_value=u"",
    )
    REMOTE_ADDR = zope.schema.TextLine(
        title=_(
            u"extra_header",
            default=u"${name} Header",
            mapping={u"name": u"REMOTE_ADDR"},
        ),
        required=False,
        default=u"",
        missing_value=u"",
    )
    HTTP_USER_AGENT = zope.schema.TextLine(
        title=_(
            u"extra_header",
            default=u"${name} Header",
            mapping={u"name": u"HTTP_USER_AGENT"},
        ),
        required=False,
        default=u"",
        missing_value=u"",
    )
Example #2
0
 def __call__(self, value, size=1048576, allowed_types=None,
              forbidden_types=None):
     if not value:
         return False
     if not INamed.providedBy(value):
         return False
     if size and value.getSize() > size:
         return _(
             'msg_file_too_big',
             mapping={'size': size},
             default=u'File is bigger than allowed size of ${size} bytes!'
         )
     ftype = splitext(value.filename)[-1]
     # remove leading dot '.' from file extension
     ftype = ftype and ftype[1:].lower() or ''
     if allowed_types and ftype not in allowed_types:
         return _(
             'msg_file_not_allowed',
             mapping={'ftype': ftype.upper()},
             default=u'File type "${ftype}" is not allowed!'
         )
     if forbidden_types and ftype in forbidden_types:
         return _(
             'msg_file_not_allowed',
             mapping={'ftype': ftype.upper()},
             default=u'File type "${ftype}" is not allowed!'
         )
     return False
Example #3
0
class IExtraData(Interface):
    dt = TextLine(
        title=_(u'Posting Date/Time'),
        required=False,
        default=u'',
        missing_value=u'',
    )
    HTTP_X_FORWARDED_FOR = TextLine(
        title=_(u'extra_header',
                default=u'${name} Header',
                mapping={u'name': u'HTTP_X_FORWARDED_FOR'}),
        required=False,
        default=u'',
        missing_value=u'',
    )
    REMOTE_ADDR = TextLine(
        title=_(u'extra_header',
                default=u'${name} Header',
                mapping={u'name': u'REMOTE_ADDR'}),
        required=False,
        default=u'',
        missing_value=u'',
    )
    HTTP_USER_AGENT = TextLine(
        title=_(u'extra_header',
                default=u'${name} Header',
                mapping={u'name': u'HTTP_USER_AGENT'}),
        required=False,
        default=u'',
        missing_value=u'',
    )
Example #4
0
 def __call__(self, value, size=1048576, allowed_types=None, forbidden_types=None):
     if not value:
         return False
     if not INamed.providedBy(value):
         return False
     if size and value.getSize() > size:
         return _(
             "msg_file_too_big",
             mapping={"size": size},
             default=u"File is bigger than allowed size of ${size} bytes!",
         )
     ftype = splitext(value.filename)[-1]
     # remove leading dot '.' from file extension
     ftype = ftype and ftype[1:].lower() or ""
     if allowed_types and ftype not in allowed_types:
         return _(
             "msg_file_not_allowed",
             mapping={"ftype": ftype.upper()},
             default=u'File type "${ftype}" is not allowed!',
         )
     if forbidden_types and ftype in forbidden_types:
         return _(
             "msg_file_not_allowed",
             mapping={"ftype": ftype.upper()},
             default=u'File type "${ftype}" is not allowed!',
         )
     return False
Example #5
0
def default_thankstitle(context):
    return translate('default_thankstitle',
                     'collective.easyform',
                     default=u'Thank You',
                     context=getRequest())
    foo = _(u'default_thankstitle',
            u'Thank You')  # dummy msgid for i18ndude to translate  # noqa
def isCommaSeparatedEmails(value):
    """Check for one or more E-Mail Addresses separated by commas"""
    portal = getUtility(ISiteRoot)
    reg_tool = getToolByName(portal, 'portal_registration')
    for v in value.split(','):
        if not reg_tool.isValidEmail(v.strip()):
            return _(u'Must be a valid list of email addresses (separated by commas).')
Example #7
0
class IRichLabel(ILabel):
    """Rich Label Field."""
    rich_label = RichText(
        title=_(u'Rich Label'),
        default=u'',
        missing_value=u'',
    )
def isNotLinkSpam(value):
    # validation is optional and configured on the field
    bad_signs = ('<a ', 'www.', 'http:', '.com', )
    value = value.lower()
    for s in bad_signs:
        if s in value:
            return _('Links are not allowed.')
Example #9
0
class INewAction(Interface):

    title = TextLine(title=__(u'Title'), required=True)

    __name__ = ASCIILine(
        title=__(u'Short Name'),
        description=__(u'Used for programmatic access to the field.'),
        required=True,
        constraint=isValidFieldName,
    )

    description = Text(
        title=__(u'Help Text'),
        description=__(u'Shows up in the form as help text for the field.'),
        required=False)

    factory = Choice(
        title=_(u'Action type'),
        vocabulary='EasyFormActions',
        required=True,
    )

    @invariant
    def checkTitleAndDescriptionTypes(data):
        if data.__name__ is not None and data.factory is not None:
            if data.__name__ == 'title' and data.factory.fieldcls is not TextLine:
                raise Invalid(
                    __(u"The 'title' field must be a Text line (string) field."
                       ))
            if data.__name__ == 'description' and data.factory.fieldcls is not Text:
                raise Invalid(
                    __(u"The 'description' field must be a Text field."))
Example #10
0
def default_resetLabel(context):
    return translate('default_resetLabel',
                     'collective.easyform',
                     default=u'Reset',
                     context=getRequest())
    foo = _(u'default_resetLabel',
            u'Reset')  # dummy msgid for i18ndude to translate  # noqa
Example #11
0
def default_thanksdescription(context):
    return translate('default_thanksdescription',
                     'collective.easyform',
                     default=u'Thanks for your input.',
                     context=getRequest())
    foo = _(u'default_thanksdescription', u'Thanks for your input.'
            )  # dummy msgid for i18ndude to translate  # noqa
Example #12
0
class ModelEditorView(BrowserView):
    """ editor view """

    title = _(u"Edit XML Fields Model")

    def modelSource(self):
        return self.context.aq_parent.fields_model
Example #13
0
class INewAction(Interface):

    title = zope.schema.TextLine(title=__(u"Title"), required=True)

    __name__ = zope.schema.ASCIILine(
        title=__(u"Short Name"),
        description=__(u"Used for programmatic access to the field."),
        required=True,
        constraint=isValidFieldName,
    )

    description = zope.schema.Text(
        title=__(u"Help Text"),
        description=__(u"Shows up in the form as help text for the field."),
        required=False,
    )

    factory = zope.schema.Choice(title=_(u"Action type"),
                                 vocabulary="EasyFormActions",
                                 required=True)

    @zope.interface.invariant
    def checkTitleAndDescriptionTypes(data):  # NOQA
        if data.__name__ is not None and data.factory is not None:
            if (data.__name__ == "title"
                    and data.factory.fieldcls is not zope.schema.TextLine):
                raise zope.interface.Invalid(
                    __(u"The 'title' field must be a Text line (string) "
                       u"field."))
            if (data.__name__ == "description"
                    and data.factory.fieldcls is not zope.schema.Text):
                raise zope.interface.Invalid(
                    __(u"The 'description' field must be a Text field."))
def ExtraDataDLVocabularyFactory(context):
    items = [
        (_(u"vocabulary_postingdt_text", default=u"Posting Date/Time"), u"dt"),
        (u"HTTP_X_FORWARDED_FOR", u"HTTP_X_FORWARDED_FOR"),
        (u"REMOTE_ADDR", u"REMOTE_ADDR"),
        (u"HTTP_USER_AGENT", u"HTTP_USER_AGENT"),
    ]
    return _make_vocabulary(items)
def isCommaSeparatedEmails(value):
    """Check for one or more E-Mail Addresses separated by commas"""
    reg_tool = api.portal.get_tool("portal_registration")
    for v in value.split(","):
        if not reg_tool.isValidEmail(v.strip()):
            return _(
                u"Must be a valid list of email addresses " u"(separated by commas)."
            )
Example #16
0
def default_resetLabel(context):
    return translate(
        'default_resetLabel',
        'collective.easyform',
        default=u'Reset',
        context=getRequest()
    )
    foo = _(u'default_resetLabel', u'Reset')  # dummy msgid for i18ndude to translate  # noqa
def isNotLinkSpam(value):
    if not value:
        return    # No value can't be SPAM
    # validation is optional and configured on the field
    value = value.lower()
    for s in BAD_SIGNS:
        if s in value:
            return _('Links are not allowed.')
Example #18
0
def ExtraDataDLVocabularyFactory(context):
    items = [
        (_(u'vocabulary_postingdt_text', default=u'Posting Date/Time'), u'dt'),
        (u'HTTP_X_FORWARDED_FOR', u'HTTP_X_FORWARDED_FOR'),
        (u'REMOTE_ADDR', u'REMOTE_ADDR'),
        (u'HTTP_USER_AGENT', u'HTTP_USER_AGENT'),
    ]
    return _make_vocabulary(items)
Example #19
0
class ModelEditorView(BrowserView):
    """Editor view
    """

    title = _(u"Edit XML Actions Model")

    def modelSource(self):
        return self.context.aq_parent.actions_model
Example #20
0
def default_thanksdescription(context):
    return translate(
        'default_thanksdescription',
        'collective.easyform',
        default=u'Thanks for your input.',
        context=getRequest()
    )
    foo = _(u'default_thanksdescription', u'Thanks for your input.')  # dummy msgid for i18ndude to translate  # noqa
Example #21
0
def default_thankstitle(context):
    return translate(
        'default_thankstitle',
        'collective.easyform',
        default=u'Thank You',
        context=getRequest()
    )
    foo = _(u'default_thankstitle', u'Thank You')  # dummy msgid for i18ndude to translate  # noqa
Example #22
0
def isCommaSeparatedEmails(value):
    """Check for one or more E-Mail Addresses separated by commas"""
    portal = getUtility(ISiteRoot)
    reg_tool = getToolByName(portal, 'portal_registration')
    for v in value.split(','):
        if not reg_tool.isValidEmail(v.strip()):
            return _(u'Must be a valid list of email addresses '
                     u'(separated by commas).')
class ISaveData(IAction):

    """A form action adapter that will save form input data and
       return it in csv- or tab-delimited format."""
    showFields = List(
        title=_(u'label_savefields_text', default=u'Saved Fields'),
        description=_(u'help_savefields_text', default=u''
                      u'Pick the fields whose inputs you\'d like to include in '
                      u'the saved data. If empty, all fields will be saved.'),
        unique=True,
        required=False,
        value_type=Choice(vocabulary=fieldsFactory),
    )
    form.widget(ExtraData=CheckBoxFieldWidget)
    ExtraData = List(
        title=_(u'label_savedataextra_text', default='Extra Data'),
        description=_(u'help_savedataextra_text',
                      default=u'Pick any extra data you\'d like saved with the form input.'),
        unique=True,
        value_type=Choice(vocabulary=vocabExtraDataDL),
    )
    DownloadFormat = Choice(
        title=_(u'label_downloadformat_text', default=u'Download Format'),
        default=u'csv',
        vocabulary=vocabFormatDL,
    )
    UseColumnNames = Bool(
        title=_(u'label_usecolumnnames_text', default=u'Include Column Names'),
        description=_(u'help_usecolumnnames_text',
                      default=u'Do you wish to have column names on the first line of downloaded input?'),
        required=False,
    )
Example #24
0
class SavedDataForm(crud.CrudForm):
    template = ViewPageTemplateFile("saveddata_form.pt")
    addform_factory = crud.NullForm

    @property
    def field(self):
        return self.context.field

    @property
    def name(self):
        return self.field.__name__

    @property
    def get_schema(self):
        return get_schema(get_context(self.field))

    def description(self):
        return _(u"${items} input(s) saved",
                 mapping={"items": self.field.itemsSaved()})

    @property
    def update_schema(self):
        fields = field.Fields(self.get_schema)
        showFields = getattr(self.field, "showFields", [])
        if showFields:
            fields = fields.select(*showFields)
        return fields

    @property
    def view_schema(self):
        ExtraData = self.field.ExtraData
        if ExtraData:
            return field.Fields(IExtraData).select(*ExtraData)

    def get_items(self):
        return [(key, DataWrapper(key, value, self.context))
                for key, value in self.field.getSavedFormInputItems()]

    # def add(self, data):
    # storage = self.context._inputStorage

    def before_update(self, item, data):
        id_ = item.__sid__
        item.update(data)
        self.field.setDataRow(id_, item.copy())

    def remove(self, id_and_item):
        (id, item) = id_and_item
        self.field.delDataRow(id)

    @button.buttonAndHandler(PMF(u"Download"), name="download")
    def handleDownload(self, action):
        pass

    @button.buttonAndHandler(_(u"Clear all"), name="clearall")
    def handleClearAll(self, action):
        self.field.clearSavedFormInput()
class IActionExtender(form.Schema):
    form.fieldset(u'overrides', label=_('Overrides'), fields=['execCondition'])
    form.read_permission(execCondition=MODIFY_PORTAL_CONTENT)
    form.write_permission(execCondition=EDIT_TALES_PERMISSION)
    execCondition = TextLine(
        title=_(u'label_execcondition_text', default=u'Execution Condition'),
        description=(_(u'help_execcondition_text', default=u''
                       u'A TALES expression that will be evaluated to determine whether '
                       u'or not to execute this action. Leave empty if unneeded, and '
                       u'the action will be executed. Your expression should evaluate '
                       u'as a boolean; return True if you wish the action to execute. '
                       u'PLEASE NOTE: errors in the evaluation of this expression will '
                       u'cause an error on form display.')
                     ),
        default=u'',
        constraint=isTALES,
        required=False,
    )
Example #26
0
def isCommaSeparatedEmails(value):
    if value is None:
        # Let the system for required take care of None values
        return
    """Check for one or more E-Mail Addresses separated by commas"""
    reg_tool = api.portal.get_tool("portal_registration")
    for v in value.split(","):
        if not reg_tool.isValidEmail(v.strip()):
            return _(u"Must be a valid list of email addresses "
                     u"(separated by commas).")
Example #27
0
class IActionExtender(Schema):
    fieldset(u'overrides', label=_('Overrides'), fields=['execCondition'])
    directives.read_permission(execCondition=MODIFY_PORTAL_CONTENT)
    directives.write_permission(execCondition=config.EDIT_TALES_PERMISSION)
    execCondition = zope.schema.TextLine(
        title=_(u'label_execcondition_text', default=u'Execution Condition'),
        description=_(
            u'help_execcondition_text',
            default=u'A TALES expression that will be evaluated to determine '
            u'whether or not to execute this action. Leave empty if '
            u'unneeded, and the action will be executed. Your '
            u'expression should evaluate as a boolean; return True '
            u'if you wish the action to execute. PLEASE NOTE: errors '
            u'in the evaluation of this expression will  cause an '
            u'error on form display.'),
        default=u'',
        constraint=isTALES,
        required=False,
    )
Example #28
0
class IActionExtender(Schema):
    fieldset(u"overrides", label=_("Overrides"), fields=["execCondition"])
    directives.read_permission(execCondition=MODIFY_PORTAL_CONTENT)
    directives.write_permission(execCondition=config.EDIT_TALES_PERMISSION)
    execCondition = zope.schema.TextLine(
        title=_(u"label_execcondition_text", default=u"Execution Condition"),
        description=_(
            u"help_execcondition_text",
            default=u"A TALES expression that will be evaluated to determine "
            u"whether or not to execute this action. Leave empty if "
            u"unneeded, and the action will be executed. Your "
            u"expression should evaluate as a boolean; return True "
            u"if you wish the action to execute. PLEASE NOTE: errors "
            u"in the evaluation of this expression will  cause an "
            u"error on form display.",
        ),
        default=u"",
        constraint=isTALES,
        required=False,
    )
def isNotLinkSpam(value):
    # validation is optional and configured on the field
    bad_signs = (
        '<a ',
        'www.',
        'http:',
        '.com',
    )
    value = value.lower()
    for s in bad_signs:
        if s in value:
            return _('Links are not allowed.')
class ICustomScript(IAction):
    """Executes a Python script for form data"""
    directives.read_permission(ProxyRole=MODIFY_PORTAL_CONTENT)
    directives.write_permission(ProxyRole=config.EDIT_PYTHON_PERMISSION)
    ProxyRole = zope.schema.Choice(
        title=_(u'label_script_proxy', default=u'Proxy role'),
        description=_(u'help_script_proxy',
                      default=u'Role under which to run the script.'),
        default=u'none',
        required=True,
        vocabulary='easyform.ProxyRoleChoices',
    )
    directives.read_permission(ScriptBody=MODIFY_PORTAL_CONTENT)
    directives.write_permission(ScriptBody=config.EDIT_PYTHON_PERMISSION)
    ScriptBody = zope.schema.Text(
        title=_(u'label_script_body', default=u'Script body'),
        description=_(u'help_script_body', default=u'Write your script here.'),
        default=config.DEFAULT_SCRIPT,
        required=False,
        missing_value=u'',
    )
Example #31
0
class IEasyFormControlPanel(Interface):

    migrate_all_forms = schema.Bool(
        title=u'migrate all the forms to dexterity',
        description=u'This will migrate all the forms already present '
        u'in the site from archetype to dexterity',
        required=False,
        default=False,
    )

    allowedFields = schema.List(
        title=_(u"Allowed Fields"),
        description=_(u"This Fields are available for your forms."),
        value_type=schema.Choice(
            description=_(
                u"help_registry_items",
                default=u"Select the registry items you desire to modify"),
            required=False,
            vocabulary='collective.easyform.FieldsVocabulary',
        ),
        default=[],
    )
    def testTranslationBasics(self):
        """ Sanity check i18n setup against some known translations
            This test will fail if .mo files don't exist.
        """

        from collective.easyform import EasyFormMessageFactory as _
        from zope.i18n import translate

        # test with:
        # msgid "clear-save-input"

        msg = _(u'clear-save-input', u'Clear Saved Input')

        xlation = translate(msg, target_language='en')
        self.assertEqual(xlation, u'Clear Saved Input')
    def testTranslationBasics(self):
        """ Sanity check i18n setup against some known translations
            This test will fail if .mo files don't exist.
        """

        from collective.easyform import EasyFormMessageFactory as _
        from zope.i18n import translate

        # test with:
        # msgid "clear-save-input"

        msg = _(u'clear-save-input', u'Clear Saved Input')

        xlation = translate(msg, target_language='en')
        self.assertEqual(xlation, u'Clear Saved Input')
    def handleImport(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        ctx = TarballImportContext(self.context, data['upload'])
        IFilesystemImporter(self.context).import_(ctx, 'structure', True)

        self.status = _(u'Form imported.')
        IStatusMessage(self.request).addStatusMessage(self.status, type='info')

        url = getMultiAdapter(
            (self.context, self.request), name='absolute_url')()
        self.request.response.redirect(url)
Example #35
0
class IPostgresData(IAction):
    """A form action adapter that will save form input data in postgresql table """

    postgres_con = zope.schema.TextLine(
        title=_(
            u'Postgres Connection String',
            default=u"Individual Default Postgres Connection String",
        ),
        description=_(
            u'<br> Database connection string <br>'
            ' dbname="xxx" user="******",host= "xxx" password = "******"',
            default=u'<br> Database connection string <br>'
            ' dbname="xxx" user="******",host= "xxx" password = "******"',
        ),
        default=u'',
        missing_value=u'',
        required=True,
    )
    postgres_table_name = zope.schema.TextLine(
        title=_(u'label_postgres_table_name', default=u"Postgres Table Name"),
        description=_(u'....', default=u'....'),
        default=u'',
        missing_value=u'',
        required=True,
    )
    decimal_separator = zope.schema.Bool(
        title=_(
            u'decimal separator',
            default=u'Treat comma also as decimal separator for Float',
        ),
        default=False,
        required=True,
    )

    ExtraData = zope.schema.List(
        title=_(u'label_savedataextra_text', default='Extra Data'),
        description=_(
            u'help_savedataextra_text',
            default=u'Pick any extra data you\'d like saved with the form '
            u'input.',
        ),
        unique=True,
        value_type=zope.schema.Choice(vocabulary='easyform.ExtraDataDL'),
    )
Example #36
0
class ISaveData(IAction):
    """A form action adapter that will save form input data and
       return it in csv- or tab-delimited format."""

    showFields = zope.schema.List(
        title=_(u"label_savefields_text", default=u"Saved Fields"),
        description=_(
            u"help_savefields_text",
            default=u"Pick the fields whose inputs you'd like to include in "
            u"the saved data. If empty, all fields will be saved.",
        ),
        unique=True,
        required=False,
        value_type=zope.schema.Choice(vocabulary="easyform.Fields"),
    )
    directives.widget(ExtraData=CheckBoxFieldWidget)
    ExtraData = zope.schema.List(
        title=_(u"label_savedataextra_text", default="Extra Data"),
        description=_(
            u"help_savedataextra_text",
            default=u"Pick any extra data you'd like saved with the form "
            u"input.",
        ),
        unique=True,
        value_type=zope.schema.Choice(vocabulary="easyform.ExtraDataDL"),
    )
    DownloadFormat = zope.schema.Choice(
        title=_(u"label_downloadformat_text", default=u"Download Format"),
        default=u"csv",
        vocabulary="easyform.FormatDL",
    )
    UseColumnNames = zope.schema.Bool(
        title=_(u"label_usecolumnnames_text", default=u"Include Column Names"),
        description=_(
            u"help_usecolumnnames_text",
            default=u"Do you wish to have column names on the first line of "
            u"downloaded input?",
        ),
        default=True,
        required=False,
    )
class EasyFormImportForm(form.Form):
    """The form class for importing of exported easyforms
    """
    fields = field.Fields(IEasyFormImportFormSchema)
    ignoreContext = True
    ignoreReadonly = True

    @button.buttonAndHandler(_(u'import'), name='import')
    def handleImport(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return

        ctx = TarballImportContext(self.context, data['upload'])
        IFilesystemImporter(self.context).import_(ctx, 'structure', True)

        self.status = _(u'Form imported.')
        IStatusMessage(self.request).addStatusMessage(self.status, type='info')

        url = getMultiAdapter((self.context, self.request),
                              name='absolute_url')()
        self.request.response.redirect(url)
Example #38
0
 def handleSubmit(self, action):
     messages = IStatusMessage(self.request)
     data, errors = self.extractData()
     if errors:
         self.status = self.formErrorsMessage
         return
     data = self.updateServerSideData(data)
     errors = self.processActions(data)
     if errors:
         return self.setErrorsMessage(errors)
     thanksPageOverride = self.context.thanksPageOverride
     if thanksPageOverride:
         thanksPageOverrideAction = self.context.thanksPageOverrideAction
         thanksPage = get_expression(self.context, thanksPageOverride)
         if thanksPageOverrideAction == 'redirect_to':
             self.request.response.redirect(thanksPage)
         elif thanksPageOverrideAction == 'traverse_to':
             thanksPage = self.context.restrictedTraverse(
                 thanksPage.encode('utf-8'))
             thanksPage = mapply(
                 thanksPage, self.request.args, self.request).encode('utf-8')
             self.request.response.write(thanksPage)
     else:
         self.thanksPage = True
         messages.add(_(u'Form successfully submitted'), type=u'success')
         replacer = DollarVarReplacer(data).sub
         self.thanksPrologue = self.context.thanksPrologue and replacer(
             self.context.thanksPrologue.output)
         self.thanksEpilogue = self.context.thanksEpilogue and replacer(
             self.context.thanksEpilogue.output)
         if not self.context.showAll:
             self.fields = self.setThanksFields(self.base_fields)
             for group in self.groups:
                 group.fields = self.setThanksFields(
                     self.base_groups.get(group.label))
         self.setDisplayMode(DISPLAY_MODE)
         self.updateActions()
Example #39
0
def default_resetLabel(context):
    return translate(_(u'default_resetLabel', u'Reset'))
Example #40
0
class FieldsSchemaListing(SchemaListing):
    template = ViewPageTemplateFile('fields_listing.pt')

    @property
    def default_fieldset_label(self):
        return (
            self.context.aq_parent.default_fieldset_label or
            super(FieldsSchemaListing, self).default_fieldset_label
        )

    def handleModelEdit(self, action):
        self.request.response.redirect('@@modeleditor')


if HAVE_RESOURCE_EDITOR:
    but = button.Button("modeleditor", title=_(u'Edit XML Fields Model'))
    FieldsSchemaListing.buttons += button.Buttons(but)
    handler = button.Handler(but, FieldsSchemaListing.handleModelEdit)
    FieldsSchemaListing.handlers.addHandler(but, handler)


class EasyFormFieldsListingPage(SchemaListingPage):

    """ Form wrapper so we can get a form with layout.

        We define an explicit subclass rather than using the wrap_form method
        from plone.z3cform.layout so that we can inject the schema name into
        the form label.
    """
    form = FieldsSchemaListing
    index = ViewPageTemplateFile('model_listing.pt')
Example #41
0
 def description(self):
     return _(
         u"${items} input(s) saved",
         mapping={'items': self.field.itemsSaved()}
     )
Example #42
0
 def label(self):
     return _(
         u"Edit Action '${fieldname}'",
         mapping={'fieldname': self.field.__name__}
     )
from zope.schema.interfaces import IContextSourceBinder
from zope.schema.interfaces import IVocabulary
from zope.schema.vocabulary import SimpleVocabulary

from collective.easyform import easyformMessageFactory as _
from collective.easyform.api import get_context
from collective.easyform.api import get_fields


PMF = MessageFactory("plone")

_make_vocabulary = lambda items: SimpleVocabulary(
    [SimpleVocabulary.createTerm(token, token, name) for (name, token) in items]
)

customActions = _make_vocabulary(((_(u"Traverse to"), u"traverse_to"), (_(u"Redirect to"), u"redirect_to")))

MIME_LIST = _make_vocabulary(((u"HTML", u"html"), (PMF(u"Text"), u"plain")))

FORM_METHODS = SimpleVocabulary.fromValues((u"post", u"get"))

XINFO_HEADERS = SimpleVocabulary.fromValues(
    (u"HTTP_X_FORWARDED_FOR", u"REMOTE_ADDR", u"PATH_INFO", u"HTTP_USER_AGENT", u"HTTP_REFERER")
)

getProxyRoleChoices = _make_vocabulary(((u"No proxy role", u"none"), (u"Manager", u"Manager")))

vocabExtraDataDL = _make_vocabulary(
    (
        (_(u"vocabulary_postingdt_text", default=u"Posting Date/Time"), u"dt"),
        (u"HTTP_X_FORWARDED_FOR", u"HTTP_X_FORWARDED_FOR"),
Example #44
0
    # def add(self, data):
        # storage = self.context._inputStorage

    def before_update(self, item, data):
        id_ = item.__sid__
        item.update(data)
        self.field.setDataRow(id_, item.copy())

    def remove(self, (id, item)):
        self.field.delDataRow(id)

    @button.buttonAndHandler(PMF(u'Download'), name='download')
    def handleDownload(self, action):
        self.field.download(self.request.response)

    @button.buttonAndHandler(_(u'Clear all'), name='clearall')
    def handleClearAll(self, action):
        self.field.clearSavedFormInput()


@implementer(ISavedDataFormWrapper)
class SavedDataFormWrapper(layout.FormWrapper):
    pass


ActionSavedDataView = layout.wrap_form(
    SavedDataForm,
    __wrapper_class=SavedDataFormWrapper
)

Example #45
0
def default_thanksdescription(context):
    return translate(
        _(u'default_thanksdescription', u'Thanks for your input.'))
Example #46
0
def default_thankstitle(context):
    return translate(_(u'default_thankstitle', u'Thank You'))
Example #47
0
from zope.schema.interfaces import IVocabulary
from zope.schema.vocabulary import SimpleVocabulary


PMF = MessageFactory('plone')


def _make_vocabulary(items):
    return SimpleVocabulary([
        SimpleVocabulary.createTerm(token, token, name)
        for (name, token) in items
    ])


customActions = _make_vocabulary((
    (_(u'Traverse to'), u'traverse_to'),
    (_(u'Redirect to'), u'redirect_to'),
))

MIME_LIST = _make_vocabulary((
    (u'HTML', u'html'),
    (PMF(u'Text'), u'plain'),
))

FORM_METHODS = SimpleVocabulary.fromValues((
    u'post',
    u'get',
))

XINFO_HEADERS = SimpleVocabulary.fromValues((
    u'HTTP_X_FORWARDED_FOR',
def isChecked(value):
    if not (
        (isinstance(value, bool) and value) or
        (isinstance(value, basestring) and value == '1')
    ):
        return _(u'Must be checked.')
Example #49
0
                # if target is not None and target.meta_type == 'FormSaveDataAdapter':
                    #target.onSuccess(fields, request, loopstop=True)
                    # return
        data = {}
        showFields = getattr(self, 'showFields', []) or self.getColumnNames()
        for f in fields:
            if f not in showFields:
                continue
            data[f] = fields[f]

        if self.ExtraData:
            for f in self.ExtraData:
                if f == 'dt':
                    data[f] = str(DateTime())
                else:
                    data[f] = getattr(request, f, '')

        self.addDataRow(data)


MailerAction = ActionFactory(
    Mailer, _(u'label_mailer_action', default=u'Mailer'), 'collective.easyform.AddMailers')
CustomScriptAction = ActionFactory(
    CustomScript, _(u'label_customscript_action', default=u'Custom Script'), 'collective.easyform.AddCustomScripts')
SaveDataAction = ActionFactory(
    SaveData, _(u'label_savedata_action', default=u'Save Data'), 'collective.easyform.AddDataSavers')

MailerHandler = BaseHandler(Mailer)
CustomScriptHandler = BaseHandler(CustomScript)
SaveDataHandler = BaseHandler(SaveData)
Example #50
0
        # target.onSuccess(fields, request, loopstop=True)
        # return
        data = {}
        showFields = getattr(self, "showFields", []) or self.getColumnNames()
        for f in fields:
            if f not in showFields:
                continue
            data[f] = fields[f]

        if self.ExtraData:
            for f in self.ExtraData:
                if f == "dt":
                    data[f] = str(DateTime())
                else:
                    data[f] = getattr(request, f, "")

        self.addDataRow(data)


MailerAction = ActionFactory(Mailer, _(u"label_mailer_action", default=u"Mailer"), "collective.easyform.AddMailers")
CustomScriptAction = ActionFactory(
    CustomScript, _(u"label_customscript_action", default=u"Custom Script"), "collective.easyform.AddCustomScripts"
)
SaveDataAction = ActionFactory(
    SaveData, _(u"label_savedata_action", default=u"Save Data"), "collective.easyform.AddDataSavers"
)

MailerHandler = BaseHandler(Mailer)
CustomScriptHandler = BaseHandler(CustomScript)
SaveDataHandler = BaseHandler(SaveData)
def isUnchecked(value):
    if not isChecked(value):
        return _(u'Must be unchecked.')
def isChecked(value):
    if (type(value) == BooleanType) and value or (type(value) in StringTypes) and (value == '1'):
        return
    return _(u'Must be checked.')
def isUnchecked(value):
    if (type(value) == BooleanType) and not value or (type(value) in StringTypes) and (value == '0'):
        return
    return _(u'Must be unchecked.')
Example #54
0
        """
        return


class RichLabel(Label):

    """A Rich Label field
    """
    implements(IRichLabel)
    rich_label = u''

    def __init__(self, rich_label=u'', **kw):
        self.rich_label = rich_label
        super(RichLabel, self).__init__(**kw)

LabelFactory = FieldFactory(Label, _(u'label_label_field', default=u'Label'))
RichLabelFactory = FieldFactory(
    RichLabel, _(u'label_richlabel_field', default=u'Rich Label'))

LabelHandler = BaseHandler(Label)
RichLabelHandler = BaseHandler(RichLabel)


class ReCaptcha(TextLine):

    """A ReCaptcha field
    """
    implements(IReCaptcha)

ReCaptchaFactory = FieldFactory(
    ReCaptcha, _(u'label_recaptcha_field', default=u'ReCaptcha'))
Example #55
0
def default_submitLabel(context):
    return translate(_(u'default_submitLabel', u'Submit'))
Example #56
0
            if f not in showFields:
                continue
            data[f] = fields[f]

        if self.ExtraData:
            for f in self.ExtraData:
                if f == 'dt':
                    data[f] = str(DateTime())
                else:
                    data[f] = getattr(request, f, '')

        self.addDataRow(data)


MailerAction = ActionFactory(
    Mailer, _
    (u'label_mailer_action', default=u'Mailer'),
    'collective.easyform.AddMailers'
)
CustomScriptAction = ActionFactory(
    CustomScript, _
    (u'label_customscript_action', default=u'Custom Script'),
    'collective.easyform.AddCustomScripts'
)
SaveDataAction = ActionFactory(
    SaveData, _
    (u'label_savedata_action', default=u'Save Data'),
    'collective.easyform.AddDataSavers'
)

MailerHandler = BaseHandler(Mailer)
CustomScriptHandler = BaseHandler(CustomScript)
PMF = zope.i18nmessageid.MessageFactory('plone')


@provider(zope.schema.interfaces.IContextAwareDefaultFactory)
def default_submitLabel(context):
    return translate(
        'default_submitLabel',
        'collective.easyform',
        default=u'Submit',
        context=getRequest()
    )


# dummy msgid for i18ndude to translate
dummy = _(u'default_submitLabel', u'Submit')


@provider(zope.schema.interfaces.IContextAwareDefaultFactory)
def default_resetLabel(context):
    return translate(
        'default_resetLabel',
        'collective.easyform',
        default=u'Reset',
        context=getRequest()
    )


# dummy msgid for i18ndude to translate
dummy = _(u'default_resetLabel', u'Reset')