Exemplo n.º 1
0
Arquivo: fields.py Projeto: a25kk/stv2
    def boolVocabDL(self):
        """ returns DisplayList of vocabulary for fgBooleanValidator """

        # Check for Plone 2.5
        if HAS_PLONE25:
          return DisplayList( (
                ('',
                    _(u'vocabulary_none_text', u'None')
                    ),
                ('isChecked',
                    _(u'vocabulary_ischecked_text', u'Is checked')
                    ),
                ('isUnchecked',
                    _(u'vocabulary_isnotchecked_text', u'Is not checked')
                    ),
                ) )
        else:
            return DisplayList( (
                ('',
                    self.translate( msgid='vocabulary_none_text',
                    domain='ploneformgen',
                    default='None')
                    ),
                ('isChecked',
                    self.translate( msgid='vocabulary_ischecked_text',
                    domain='ploneformgen',
                    default='Is checked')
                    ),
                ('isUnchecked',
                    self.translate( msgid='vocabulary_isnotchecked_text',
                    domain='ploneformgen',
                    default='Is not checked')
                    ),
                ) )
Exemplo n.º 2
0
Arquivo: fields.py Projeto: a25kk/stv2
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        # Check for Plone 2.5
        if HAS_PLONE25:
          return DisplayList( (
                ('flex',
                        _(u'vocabulary_flex_text', u'Flexible (radio for short, select for longer)')
                    ),
                ('select',
                        _(u'vocabulary_selection_text', u'Selection list')
                    ),
                ('radio',
                        _(u'vocabulary_radio_text', u'Radio buttons')
                    ),
            ) )
        else:
            return DisplayList( (
                ('flex',
                    self.translate( msgid='vocabulary_flex_text',
                    domain='ploneformgen',
                    default='Flexible (radio for short, select for longer)')
                    ),
                ('select',
                    self.translate( msgid='vocabulary_selection_text',
                    domain='ploneformgen',
                    default='Selection list')
                    ),
                ('radio',
                    self.translate( msgid='vocabulary_radio_text',
                    domain='ploneformgen',
                    default='Radio buttons')
                    ),
            ) )
Exemplo n.º 3
0
Arquivo: fields.py Projeto: a25kk/stv2
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        # Check for Plone 2.5
        if HAS_PLONE25:
          return DisplayList( (
            ('select',
                    _(u'vocabulary_selection_text', u'Selection list')
                ),
            ('checkbox',
                    _(u'vocabulary_checkbox_text', u'Checkbox list')
                )
            ) )
        else:
            return DisplayList( (
                ('select',
                    self.translate( msgid='vocabulary_selection_text',
                    domain='ploneformgen',
                    default='Selection list')
                    ),
                ('checkbox',
                    self.translate( msgid='vocabulary_checkbox_text',
                    domain='ploneformgen',
                    default='Checkbox list')
                    )
                ) )
Exemplo n.º 4
0
class FGFieldsetStart(BaseFormField):
    """ Marks start of fieldset (no input component) """

    security = ClassSecurityInfo()

    schema = BaseFieldSchema.copy()
    del schema['hidden']
    del schema['placeholder']
    noview = {'view': 'invisible', 'edit': 'invisible'}
    schema['fgTEnabled'].widget.visible = noview
    schema['fgTDefault'].widget.visible = noview
    schema['fgTValidator'].widget.visible = noview
    schema['serverSide'].widget.visible = noview

    schema['required'].default = True
    schema['required'].widget.label = _(u'label_showlegend_text',
                                        default=u'Show Title as Legend')
    schema['required'].widget.description = _(u'help_showlegend_text',
                                              default=u'')

    # Standard content type setup
    portal_type = meta_type = 'FieldsetStart'
    archetype_name = 'Fieldset Beginning'
    content_icon = 'LabelField.gif'
    typeDescription = 'Start a fieldset'

    _at_rename_after_creation = True

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseObject.__init__(self, oid, **kwargs)

        self.fgField = StringField(
            'fg_fieldset_start',
            searchable=0,
            required=0,
            default='1',
            write_permission=View,
            widget=FieldsetStartWidget(),
        )

    security.declareProtected(View, 'isLabel')

    def isLabel(self):
        """ yes, this is just decorative """
        return True

    security.declareProtected(ModifyPortalContent, 'setRequired')

    def setRequired(self, value, **kw):
        """ double purpose required field as show_legend field
            so that we may update easily with the quick editor
        """
        if type(value) == BooleanType:
            self.fgField.widget.show_legend = value
            self.fgField.required = value
        else:
            self.fgField.widget.show_legend = value == '1' or value == 'True'
            self.fgField.required = value == '1' or value == 'True'
Exemplo n.º 5
0
class IImportSchema(Interface):
    """Schema for form import.
    """
    upload = Bytes(title=_(u'Upload'), required=True)

    purge = Bool(title=_(u'Remove Existing Form Items?'),
                 default=False,
                 required=False)
Exemplo n.º 6
0
    def boolVocabDL(self):
        """ returns DisplayList of vocabulary for fgBooleanValidator """

        return DisplayList((
            ('', _(u'vocabulary_none_text', u'None')),
            ('isChecked', _(u'vocabulary_ischecked_text', u'Is checked')),
            ('isUnchecked',
             _(u'vocabulary_isnotchecked_text', u'Is not checked')),
        ))
Exemplo n.º 7
0
Arquivo: fields.py Projeto: vwc/fv
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList(
            (
                ("select", _(u"vocabulary_selection_text", u"Selection list")),
                ("checkbox", _(u"vocabulary_checkbox_text", u"Checkbox list")),
            )
        )
Exemplo n.º 8
0
Arquivo: fields.py Projeto: vwc/fv
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList(
            (
                ("flex", _(u"vocabulary_flex_text", u"Flexible (radio for short, select for longer)")),
                ("select", _(u"vocabulary_selection_text", u"Selection list")),
                ("radio", _(u"vocabulary_radio_text", u"Radio buttons")),
            )
        )
Exemplo n.º 9
0
Arquivo: fields.py Projeto: vwc/fv
    def boolVocabDL(self):
        """ returns DisplayList of vocabulary for fgBooleanValidator """

        return DisplayList(
            (
                ("", _(u"vocabulary_none_text", u"None")),
                ("isChecked", _(u"vocabulary_ischecked_text", u"Is checked")),
                ("isUnchecked", _(u"vocabulary_isnotchecked_text", u"Is not checked")),
            )
        )
Exemplo n.º 10
0
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList((
            ('flex',
             _(u'vocabulary_flex_text',
               u'Flexible (radio for short, select for longer)')),
            ('select', _(u'vocabulary_selection_text', u'Selection list')),
            ('radio', _(u'vocabulary_radio_text', u'Radio buttons')),
        ))
Exemplo n.º 11
0
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList( (
            ('select',
                    _('vocabulary_selection_text', 'Selection list')
                ),
            ('checkbox',
                    _('vocabulary_checkbox_text', 'Checkbox list')
                )
            ) )
Exemplo n.º 12
0
def cleanupMessage(original, context, instance):
    """ Where original is the message from the Archetypes validator,
        return an improved, translatable message if available.
    """

    if type(original) in StringTypes:
        if original.find('is required, please correct.') > 0:
            return newRequiredMessage

        mo = verrorRE.match(original)
        if mo:
            term = mo.groups()[0]
            if term.find('pfgv_') == 0:
                # this is one of the customizable pfg tool validators
                fgt = getToolByName(instance, 'formgen_tool')
                sv = fgt.stringValidators.get(term[5:])
                if sv:
                    # this is already a messagestr
                    return sv['errmsg']

        mo = verror2RE.match(original)
        if mo:
            term = mo.groups()[0]

            nm = newMessages.get(term)
            if nm:
                # this is one of the simple messages for which we have a replacement
                return nm

            if term == 'inExNumericRange':
                mo = enrMessageRE.match(original)
                if mo:
                    return _(u'pfg_not_number', u'Please enter a number here.')
                mo = enrSmallMessageRE.match(original)
                if mo:
                    groups = mo.groups()
                    return _(u'pfg_number_too_small',
                             u"'${value}' is too small. Must be at least ${min}.",
                             mapping={'value': groups[0], 'min': groups[1]})
                mo = enrLargeMessageRE.match(original)
                if mo:
                    groups = mo.groups()
                    return _(u'pfg_number_too_large',
                             u"'${value}' is too large. Must be no greater than ${max}.",
                             mapping={'value': groups[0], 'max': groups[1]})
            elif term == 'isNotTooLong':
                mo = mlTooLongRE.match(original)
                if mo:
                    groups = mo.groups()
                    return _(u'pfg_too_long',
                             u"'Entry too long. It should be no more than ${max} characters.",
                             mapping={'max': groups[0]})

    return original
Exemplo n.º 13
0
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList( (
            ('select',
                    _(u'vocabulary_selection_text', u'Selection list')
                ),
            ('checkbox',
                    _(u'vocabulary_checkbox_text', u'Checkbox list')
                )
            ) )
Exemplo n.º 14
0
    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList( (
            ('flex',
                    _(u'vocabulary_flex_text', u'Flexible (radio for short, select for longer)')
                ),
            ('select',
                    _(u'vocabulary_selection_text', u'Selection list')
                ),
            ('radio',
                    _(u'vocabulary_radio_text', u'Radio buttons')
                ),
        ) )
Exemplo n.º 15
0
 def addableFieldsets(self):
     """ Return a list of fieldset markers """
     return (
         {
             'id': 'FieldsetStart',
             'title': _(u'Fieldset Start'),
             'description': _(u'Begin a fieldset')
         },
         {
             'id': 'FieldsetEnd',
             'title': _(u'Fieldset End'),
             'description': _(u'End a fieldset')
         },
     )
Exemplo n.º 16
0
    def boolVocabDL(self):
        """ returns DisplayList of vocabulary for fgBooleanValidator """

        return DisplayList( (
            ('',
                _(u'vocabulary_none_text', u'None')
                ),
            ('isChecked',
                _(u'vocabulary_ischecked_text', u'Is checked')
                ),
            ('isUnchecked',
                _(u'vocabulary_isnotchecked_text', u'Is not checked')
                ),
            ) )
Exemplo n.º 17
0
    def htmlValidatorsDL(self):
        """ return a display list of string validators.
            this is a hack for 118n
        """

        return DisplayList((
            ('', _(u'vocabulary_none_text', u'None')),
            ('isTidyHtml',
             _(u'vocabulary_istidyhtml_text',
               u'Is Tidy HTML (fails on errors and warnings)')),
            ('isTidyHtmlWithCleanup',
             _(u'vocabulary_istidyhtmlwithcleanup_text',
               u'Tidy HTML With Cleanup (fails on errors, cleans up rest)')),
        ))
Exemplo n.º 18
0
    def initializeArchetype(self, **kwargs):
        """ Translate the adapter in the current langage
        """

        ATCTContent.initializeArchetype(self, **kwargs)

        self.setNoSubmitMessage(zope.i18n.translate(_(u'pfg_thankspage_nosubmitmessage', u'<p>No input was received. Please visit the form.</p>'), context=self.REQUEST))
    def initializeArchetype(self, **kwargs):
        """ Translate the adapter in the current langage
        """

        FormActionAdapter.initializeArchetype(self, **kwargs)

        self.setMsg_subject(zope.i18n.translate(_(u'pfg_formmaileradapter_msg_subject', u'Form Submission'), context=self.REQUEST))
Exemplo n.º 20
0
class FormFolderImportView(formbase.Form):
    """The formlib class for importing of exported PFG form folders
    """
    implements(interfaces.IFormFolderImportView)

    form_fields = form.Fields(interfaces.IImportSchema)
    status = errors = None
    prefix = 'form'

    @form.action(_(u"import"))
    def action_import(self, action, data):
        if data.get('purge', False) == True:
            # user has requested removal of existing fields
            self.context.manage_delObjects(ids=self.context.objectIds())

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

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

        url = getMultiAdapter((self.context, self.request),
                              name='absolute_url')()
        self.request.response.redirect(url)

        return ''
Exemplo n.º 21
0
Arquivo: thanksPage.py Projeto: vwc/fv
    def initializeArchetype(self, **kwargs):
        """ Translate the adapter in the current langage
        """

        ATCTContent.initializeArchetype(self, **kwargs)

        self.setNoSubmitMessage(zope.i18n.translate(_(u'pfg_thankspage_nosubmitmessage', u'<p>No input was received. Please <a title="Test Folder" href=".">visit the form</a>.</p>'), context=self.REQUEST))
Exemplo n.º 22
0
    def initializeArchetype(self, **kwargs):
        """ Translate the adapter in the current langage
        """

        FormActionAdapter.initializeArchetype(self, **kwargs)

        self.setMsg_subject(zope.i18n.translate(_(u'pfg_formmaileradapter_msg_subject', u'Form Submission'), context=self.REQUEST))
Exemplo n.º 23
0
    def htmlValidatorsDL(self):
        """ return a display list of string validators.
            this is a hack for 118n
        """

        return DisplayList( (
            ('',
                _(u'vocabulary_none_text', u'None')
                ),
            ('isTidyHtml',
                _(u'vocabulary_istidyhtml_text', u'Is Tidy HTML (fails on errors and warnings)')
                ),
            ('isTidyHtmlWithCleanup',
                _(u'vocabulary_istidyhtmlwithcleanup_text', u'Tidy HTML With Cleanup (fails on errors, cleans up rest)')
                ),
            ) )
Exemplo n.º 24
0
    def _initStringValidators(self):
        """ Initialize string validators from config
        """

        self.stringValidators = {}
        self.stringValidatorsDL = DisplayList()
        self.stringValidatorsDL.add('vocabulary_none_text', u'None')

        for kwa in config.stringValidators:
            id = kwa['id']    

            title = kwa.get('title', id)
            i18nid = kwa.get('i18nid', title)

            errmsg = kwa.get('errmsg', 'Validation failed: %s' % id)
            errid = kwa.get('errid', errmsg)
            if HAS_PLONE25:
                errmsg = _(errid, errmsg)

            validatorId = 'pfgv_%s' % id
            self.stringValidators[id] = {
                'title'  : title,
                'i18nid' : i18nid,
                'errmsg' : errmsg,
                'errid'  : errid,
                # 'revalid': revalid,
                'id'     : validatorId,
                }
            
            self.stringValidatorsDL.add( id, title, msgid=i18nid )
Exemplo n.º 25
0
    def _initStringValidators(self):
        """ Initialize string validators from config
        """

        self.stringValidators = {}
        self.stringValidatorsDL = DisplayList()
        self.stringValidatorsDL.add('vocabulary_none_text', u'None')

        for kwa in config.stringValidators:
            id = kwa['id']

            title = kwa.get('title', id)
            i18nid = kwa.get('i18nid', title)

            errmsg = kwa.get('errmsg', 'Validation failed: %s' % id)
            errid = kwa.get('errid', errmsg)
            errmsg = _(errid, errmsg)

            validatorId = 'pfgv_%s' % id
            self.stringValidators[id] = {
                'title'  : title,
                'i18nid' : i18nid,
                'errmsg' : errmsg,
                'errid'  : errid,
                # 'revalid': revalid,
                'id'     : validatorId,
                }

            self.stringValidatorsDL.add( id, title, msgid=i18nid )
Exemplo n.º 26
0
Arquivo: fields.py Projeto: vwc/fv
    def htmlValidatorsDL(self):
        """ return a display list of string validators.
            this is a hack for 118n
        """

        return DisplayList(
            (
                ("", _(u"vocabulary_none_text", u"None")),
                ("isTidyHtml", _(u"vocabulary_istidyhtml_text", u"Is Tidy HTML (fails on errors and warnings)")),
                (
                    "isTidyHtmlWithCleanup",
                    _(
                        u"vocabulary_istidyhtmlwithcleanup_text",
                        u"Tidy HTML With Cleanup (fails on errors, cleans up rest)",
                    ),
                ),
            )
        )
Exemplo n.º 27
0
 def validate(self, value, instance, errors=None, **kwargs):
     error = _(u'pfg_allRequired', u'An answer is required for each question.')
     if not self.required:
         return None
     for index in range(len(self.questionSet)):
         if (index > len(value)) or not value[index]:
             fname = self.getName()
             if fname not in errors:
                 errors[fname] = error
             return error
     return None
Exemplo n.º 28
0
 def validate(self, value, instance, errors=None, **kwargs):
     error = _('pfg_allRequired',
               'An answer is required for each question.')
     if not self.required:
         return None
     for index in range(len(self.questionSet)):
         if (index > len(value)) or not value[index]:
             fname = self.getName()
             if fname not in errors:
                 errors[fname] = error
             return error
     return None
Exemplo n.º 29
0
    def initializeArchetype(self, **kwargs):
        """ Translate the adapter in the current langage
        """

        FormActionAdapter.initializeArchetype(self, **kwargs)

        if HAS_PLONE25:
            self.setMsg_subject(zope.i18n.translate(_(u'pfg_formmaileradapter_msg_subject', u'Form Submission'), context=self.REQUEST))
        else:
            self.setMsg_subject(self.translate(
                                  msgid='pfg_formmaileradapter_msg_subject',
                                  domain='ploneformgen',
                                  default='Form Submission'))
Exemplo n.º 30
0
    def thanksPageVocabulary(self):
        """ returns a DisplayList of contained page-ish documents """

        registry = getUtility(IRegistry)
        defaultPageTypes = registry['plone.default_page_types']
        tpages = [('', _(u'vocabulary_none_text', u'None')), ]

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

        return DisplayList(tpages)
 def action_import(self, action, data):
     if data.get('purge', False) == True:
         # user has requested removal of existing fields
         self.context.manage_delObjects(ids=self.context.objectIds())
     
     ctx = TarballImportContext(self.context, data['upload'])
     IFilesystemImporter(self.context).import_(ctx, 'structure', True)
     
     message = _(u'Form imported.')
     IStatusMessage(self.request).addStatusMessage(message, type='info')
     
     url = getMultiAdapter((self.context, self.request), name='absolute_url')()
     self.request.response.redirect(url)
     
     return ''
Exemplo n.º 32
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)
    def testTranslationBasics(self):
        """ Sanity check i18n setup against some known translations
            This test will fail if .mo files don't exist.
        """

        from Products.PloneFormGen import PloneFormGenMessageFactory 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")
Exemplo n.º 34
0
    def thanksPageVocabulary(self):
        """ returns a DisplayList of contained page-ish documents """

        registry = getUtility(IRegistry)
        defaultPageTypes = registry['plone.default_page_types']
        tpages = [
            ('', _('vocabulary_none_text', 'None')),
        ]

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

        return DisplayList(tpages)
Exemplo n.º 35
0
Arquivo: fields.py Projeto: a25kk/stv2
    def htmlValidatorsDL(self):
        """ return a display list of string validators.
            this is a hack for 118n
        """

        # Check for Plone 2.5
        if HAS_PLONE25:
            return DisplayList( (
                ('',
                    _(u'vocabulary_none_text', u'None')
                    ),
                ('isTidyHtml',
                    _(u'vocabulary_istidyhtml_text', u'Is Tidy HTML (fails on errors and warnings)')
                    ),
                ('isTidyHtmlWithCleanup',
                    _(u'vocabulary_istidyhtmlwithcleanup_text', u'Tidy HTML With Cleanup (fails on errors, cleans up rest)')
                    ),
                ) )
        else:
            return DisplayList( (
                ('',
                    self.translate( msgid='vocabulary_none_text',
                    domain='ploneformgen',
                    default='None')
                    ),
                ('isTidyHtml',
                    self.translate( msgid='vocabulary_istidyhtml_text',
                    domain='ploneformgen',
                    default='Is Tidy HTML (fails on errors and warnings)')
                    ),
                ('isTidyHtmlWithCleanup',
                    self.translate( msgid='vocabulary_istidyhtmlwithcleanup_text',
                    domain='ploneformgen',
                    default='Tidy HTML With Cleanup (fails on errors, cleans up rest)')
                    ),
                ) )
Exemplo n.º 36
0
def _registerStringValidators():

    for kwa in config.stringValidators:
        id = kwa['id']

        errmsg = kwa.get('errmsg', _('Validation failed: $id',
                                     mapping={'id': id}))

        # create a validator to match, register it.
        validatorId = 'pfgv_%s' % id
        revalid = RegexValidator(validatorId,
            kwa.get('regex', '.+'),
            ignore=kwa.get('ignore', ''),
            )
        validation.register(revalid)
    def testTranslationBasics(self):
        """ Sanity check i18n setup against some known translations
            This test will fail if .mo files don't exist.
        """

        from Products.PloneFormGen import PloneFormGenMessageFactory 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" )
Exemplo n.º 38
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 IPloneFormGenThanksPage.providedBy(obj) or \
              getattr(obj.aq_explicit, 'portal_type', 'none') in defaultPageTypes:
                tpages.append((obj.getId(), obj.title))

        return DisplayList(tpages)
Exemplo n.º 39
0
    def action_import(self, action, data):
        if data.get('purge', False) == True:
            # user has requested removal of existing fields
            self.context.manage_delObjects(ids=self.context.objectIds())

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

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

        url = getMultiAdapter((self.context, self.request),
                              name='absolute_url')()
        self.request.response.redirect(url)

        return ''
Exemplo n.º 40
0
def _registerStringValidators():

    for kwa in config.stringValidators:
        id = kwa['id']

        errmsg = kwa.get('errmsg', 'Validation failed: %s' % id)
        errid = kwa.get('errid', errmsg)
        errmsg = _(errid, errmsg)

        # create a validator to match, register it.
        validatorId = 'pfgv_%s' % id
        revalid = RegexValidator(validatorId,
            kwa.get('regex', '.+'),
            ignore=kwa.get('ignore', ''),
            )
        validation.register(revalid)
Exemplo n.º 41
0
Arquivo: form.py Projeto: dtgit/dtedu
    def fgFieldsDisplayList(self, withNone=False, noneValue='', objTypes=None):
        """ returns display list of fields """

        myFields = []
        if withNone:
            if HAS_PLONE25:
                myFields.append( (noneValue, _(u'vocabulary_none_text', u'None')) )
            else:
                myFields.append( (noneValue, self.translate( msgid='vocabulary_none_text', domain='ploneformgen', default='None')) )

        for obj in self._getFieldObjects(objTypes):
            if isinstance(obj.title, unicode):
                myFields.append( (obj.getId(), obj.title) )
            else:
                myFields.append( (obj.getId(), obj.title.decode(self.getCharset())) )

        return DisplayList( myFields )
Exemplo n.º 42
0
def _registerStringValidators():

    for kwa in config.stringValidators:
        id = kwa['id']    

        errmsg = kwa.get('errmsg', 'Validation failed: %s' % id)
        errid = kwa.get('errid', errmsg)
        if HAS_PLONE25:
            errmsg = _(errid, errmsg)

        # create a validator to match, register it.
        validatorId = 'pfgv_%s' % id
        revalid = RegexValidator(validatorId,
            kwa.get('regex', '.+'),
            ignore=kwa.get('ignore', ''),
            )
        validation.register(revalid)
Exemplo n.º 43
0
    def fgFieldsDisplayList(self, withNone=False, noneValue='', objTypes=None):
        """ returns display list of fields """

        myFields = []
        if withNone:
            myFields.append((noneValue, _(u'vocabulary_none_text', u'None')))

        for obj in self._getFieldObjects(objTypes):
            if obj.getServerSide() or obj.isLabel():
                continue
            if isinstance(obj.title, unicode):
                myFields.append((obj.getId(), obj.title))
            else:
                myFields.append(
                    (obj.getId(), obj.title.decode(self.getCharset())))

        return DisplayList(myFields)
Exemplo n.º 44
0
    def fgFieldsDisplayList(self, withNone=False, noneValue='', objTypes=None):
        """ returns display list of fields """

        myFields = []
        if withNone:
            myFields.append((noneValue, _(u'vocabulary_none_text', u'None')))

        for obj in self._getFieldObjects(objTypes):
            if obj.getServerSide() or obj.isLabel():
                continue
            if isinstance(obj.title, unicode):
                myFields.append((obj.getId(), obj.title))
            else:
                myFields.append((obj.getId(),
                                 obj.title.decode(self.getCharset())))

        return DisplayList(myFields)
Exemplo n.º 45
0
Arquivo: form.py Projeto: dtgit/dtedu
    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')

        if HAS_PLONE25:
            tpages = [('', _(u'vocabulary_none_text', u'None')),]
        else:
            tpages = [('', self.translate( msgid='vocabulary_none_text', domain='ploneformgen', default='None')),]

        for obj in self.objectValues():
            if IPloneFormGenThanksPage in providedBy(obj) or \
              getattr(obj.aq_explicit, 'portal_type', 'none') in defaultPageTypes:
                tpages.append( (obj.getId(), obj.title) )
                
        return DisplayList( tpages )
Exemplo n.º 46
0
    def testTranslationBasics(self):
        """Sanity check i18n setup against some known translations"""

        from Products.PloneFormGen import PloneFormGenMessageFactory 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" )

        xlation = translate(msg, target_language='fr')
        self.assertEqual( xlation, 'Effacer les entr\xc3\xa9es sauvegard\xc3\xa9es'.decode('utf8') )

        xlation = translate(msg, target_language='de')
        self.assertEqual( xlation, 'Die gespeicherten Eingaben l\xc3\xb6schen'.decode('utf8') )
Exemplo n.º 47
0
    def _initStringValidators(self):
        """ Initialize string validators from config
        """

        self.stringValidators = {}
        self.stringValidatorsDL = DisplayList()
        self.stringValidatorsDL.add('vocabulary_none_text', u'None')

        for kwa in config.stringValidators:
            id = kwa['id']

            title = kwa.get('title', id)

            errmsg = kwa.get('errmsg', _('Validation failed: $id',
                                         mapping={'id': id}))
            validatorId = 'pfgv_%s' % id
            self.stringValidators[id] = {
                'title'  : title,
                'errmsg' : errmsg,
                'id'     : validatorId}

            self.stringValidatorsDL.add(id, title)
Exemplo n.º 48
0
    def _initStringValidators(self):
        """ Initialize string validators from config
        """

        self.stringValidators = {}
        self.stringValidatorsDL = DisplayList()
        self.stringValidatorsDL.add('vocabulary_none_text', u'None')

        for kwa in config.stringValidators:
            id = kwa['id']

            title = kwa.get('title', id)

            errmsg = kwa.get('errmsg',
                             _('Validation failed: $id', mapping={'id': id}))
            validatorId = 'pfgv_%s' % id
            self.stringValidators[id] = {
                'title': title,
                'errmsg': errmsg,
                'id': validatorId
            }

            self.stringValidatorsDL.add(id, title)
Exemplo n.º 49
0
class FGStringField(BaseFormField):
    """ A string entry field """

    security  = ClassSecurityInfo()

    schema = BaseFieldSchemaStringDefault.copy() + Schema((
        maxlengthField,
        sizeField,
        StringField('fgStringValidator',
            vocabulary='stringValidatorsDL',
            enforceVocabulary=1,
            widget=SelectionWidget(label=_('label_fgstringvalidator_text',
                                           default='Validator'),
                description=_('help_fgstringvalidator_text',
                  default="""Tests input against simple string patterns."""),
                ),
        ),
    ))

    # hide references & discussion
    finalizeFieldSchema(schema, folderish=True, moveDiscussion=False)

    # Standard content type setup
    portal_type = meta_type = 'FormStringField'
    archetype_name = 'String Field'
    content_icon = 'StringField.gif'
    typeDescription= 'A string field'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseFormField.__init__(self, oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = StringField('fg_string_field',
            searchable=0,
            required=0,
            write_permission = View,
            validators=('isNotTooLong',),
            )


    def stringValidatorsDL(self):
        """ return a display list of string validators.
        """

        fgt = getToolByName(self, 'formgen_tool')
        return fgt.getStringValidatorsDL()


    def setFgStringValidator(self, value, **kw):
        """ set simple validator """

        fgt = getToolByName(self, 'formgen_tool')

        if value and (value != 'vocabulary_none_text'):
            fgtid = fgt.stringValidators[value].get('id')
            if fgtid:
                self.fgField.validators = ('isNotTooLong', fgtid)
        else:
            self.fgField.validators = ('isNotTooLong',)
        self.fgField._validationLayer()

        self.fgStringValidator = value
Exemplo n.º 50
0
class FGBooleanField(BaseFormField):
    """ Boolean (checkbox) field """

    security  = ClassSecurityInfo()

    schema = BaseFieldSchema.copy() + Schema((
        StringField('fgDefault',
            searchable=0,
            required=0,
            widget=BooleanWidget(
                label=_('label_fgdefault_text', default='Default'),
                description=_('help_fgdefault_text', default="The value the "
                    "field should contain when the form is first displayed."
                    "Note that this may be overridden dynamically."),
                ),
        ),
        StringField('fgBooleanValidator',
            vocabulary='boolVocabDL',
            enforceVocabulary=1,
            widget=SelectionWidget(label=_('label_fgbooleanvalidator_text', default='Validator'),
                description=_('help_fgbooleanvalidator_text', default="""Choose a validator to require a particular response."""),
                ),
        ),
        StringField('fgBoolTrueString',
            required=0,
            searchable=0,
            default='1',
            widget=StringWidget(
                label=_('label_fgbooleantruestring_text', default="True Display String"),
                description=_('help_fgbooleantruestring_text', default=\
                    "String to use in thanks page and mail when the field's "
                    "checkbox is checked."),
                ),
            ),
        StringField('fgBoolFalseString',
            required=0,
            searchable=0,
            default='0',
            widget=StringWidget(
                label=_('label_fgbooleanfalsestring_text', default="False Display String"),
                description=_('help_fgbooleanfalsestring_text', default="""String to use in thanks page and mail when the field's checkbox is unchecked."""),
                ),
            ),
    ))
    schema['required'].widget.description = \
        _('help_boolrequired_text', default="""NOTE: For a checkbox field, the required flag doesn't do anything beyond
           putting a 'required' marker next to the label. If you wish to require a
           particular input, choose a validator below.
        """)

    # attributes that are not really useful for Boolean field.
    del schema['hidden']
    del schema['serverSide']
    del schema['placeholder']

    # hide references & discussion
    finalizeFieldSchema(schema, folderish=True, moveDiscussion=False)

    # Standard content type setup
    portal_type = meta_type = 'FormBooleanField'
    archetype_name = 'Boolean Field'
    content_icon = 'CheckBoxField.gif'
    typeDescription= 'A CheckBox (Boolean) field'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseFormField.__init__(self, oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = NRBooleanField('fg_boolean_field',
            searchable=0,
            required=0,
            write_permission = View,
            )

    security.declareProtected(ModifyPortalContent, 'setFgBooleanValidator')
    def setFgBooleanValidator(self, value, **kw):
        """ set boolean validator """

        if value:
            self.fgField.validators = (value,)
        else:
            self.fgField.validators = ()
        self.fgField._validationLayer()

        self.fgBooleanValidator = value


    def boolVocabDL(self):
        """ returns DisplayList of vocabulary for fgBooleanValidator """

        return DisplayList( (
            ('',
                _('vocabulary_none_text', 'None')
                ),
            ('isChecked',
                _('vocabulary_ischecked_text', 'Is checked')
                ),
            ('isUnchecked',
                _('vocabulary_isnotchecked_text', 'Is not checked')
                ),
            ) )


    def htmlValue(self, REQUEST):
        """ Return value instead of key """

        value = REQUEST.form.get(self.__name__, 'No Input')
        if type(value) == BooleanType:
            if value:
                return self.fgBoolTrueString
        elif value == '1':
            return self.fgBoolTrueString

        return self.fgBoolFalseString
Exemplo n.º 51
0
class FGSelectionField(BaseFormField):
    """ Selection Field (radio buttons or select) """

    security  = ClassSecurityInfo()

    schema = BaseFieldSchemaStringDefault.copy() + Schema((
        vocabularyField,
        vocabularyOverrideField,
        StringField('fgFormat',
            searchable=0,
            required=0,
            default='flex',
            enforceVocabulary=1,
            vocabulary='formatVocabDL',
            widget=SelectionWidget(
                label=_('label_fgformat_text', default='Presentation Widget'),
                description=_('help_fgformat_text', default=''),
                ),
        ),
    ))

    # attributes that are not really useful for a selection field.
    # Just use a hidden string field if you really need this.
    del schema['hidden']
    del schema['serverSide']
    del schema['placeholder']

    # hide references & discussion
    finalizeFieldSchema(schema, folderish=True, moveDiscussion=False)

    # Standard content type setup
    portal_type = meta_type = 'FormSelectionField'
    archetype_name = 'Selection Field'
    content_icon = 'ListField.gif'
    typeDescription= 'A selection field'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseFormField.__init__(self, oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = StringVocabularyField('fg_selection_field',
            searchable=0,
            required=0,
            widget=SelectionWidget(),
            vocabulary = '_get_selection_vocab',
            enforceVocabulary=1,
            write_permission = View,
            )


    security.declareProtected(ModifyPortalContent, 'setFgFormat')
    def setFgFormat(self, value, **kw):
        """ set selection format """

        self.fgField.widget.format = value
        self.fgFormat = value


    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList( (
            ('flex',
                    _('vocabulary_flex_text', 'Flexible (radio for short, select for longer)')
                ),
            ('select',
                    _('vocabulary_selection_text', 'Selection list')
                ),
            ('radio',
                    _('vocabulary_radio_text', 'Radio buttons')
                ),
        ) )


    def htmlValue(self, REQUEST):
        """ Return value instead of key """

        charset = 'utf-8'

        value = REQUEST.form.get(self.__name__, '')

        # note that vocabulary items are in unicode;
        # so, we must decode before lookup
        vu = value.decode(charset)

        vocabulary = self.fgField.Vocabulary(self)
        v = vocabulary.getValue(vu) or vu

        # v might be unicode or string.  We need string.
        if isinstance(v, str):
            v = v.encode(charset)
        return cgi.escape(v)
Exemplo n.º 52
0
class FGDateField(BaseFormField):
    """ Date/Time Entry Field """

    security  = ClassSecurityInfo()

    schema = BaseFieldSchemaStringDefault.copy() + Schema((
        BooleanField('fgShowHM',
            searchable=0,
            required=0,
            default=1,
            widget=BooleanWidget(
                label=_('label_fgshowhm_text', default='Show Time Selection Options'),
                description=_('help_fgshowhm_text', default=''),
                ),
        ),
        IntegerField('fgStartingYear',
            searchable=0,
            required=0,
            default='1999',
            widget=IntegerWidget(
                label=_('label_fgstartingyear_text', default='Starting Year'),
                description = _("help_fgstartingyear_text"),
                ),
        ),
        IntegerField('fgEndingYear',
            searchable=0,
            required=0,
            default=None,
            widget=IntegerWidget(
                label=_('label_fgendingyear_text', default='Ending Year'),
                description = _('help_fgendingyear_text', default="""The last year to offer in the year drop-down.
                 Leave this empty if you wish to instead use a number of future years."""),
                ),
        ),
        IntegerField('fgFutureYears',
            searchable=0,
            required=0,
            default='5',
            widget=IntegerWidget(
                label=_('label_fgfutureyears_text', default='Future Years To Display'),
                description = _('help_fgfutureyears_text', default="""The number of future years to offer in the year drop-down.
                 (This is only applicable if you have not specified an ending year.)"""),
                ),
        ),
))

    # attributes that are not really useful for Date/Time field.
    del schema['hidden']
    del schema['serverSide']
    del schema['placeholder']

    # hide references & discussion
    finalizeFieldSchema(schema, folderish=True, moveDiscussion=False)

    # Standard content type setup
    portal_type = meta_type = 'FormDateField'
    archetype_name = 'Date/Time Field'
    content_icon = 'DateTimeField.gif'
    typeDescription= 'A date/time field. Time component is optional.'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseFormField.__init__(self, oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = DateTimeField('fg_date_field',
            searchable=0,
            required=0,
            write_permission = View,
            widget=CalendarWidget(),
            )


    security.declareProtected(ModifyPortalContent, 'setFgShowHM')
    def setFgShowHM(self, value, **kw):
        """ set show_hm """

        if type(value) == BooleanType:
            self.fgField.widget.show_hm = value
        else:
            self.fgField.widget.show_hm = value == '1'

        self.fgShowHM = value


    security.declareProtected(ModifyPortalContent, 'setFgStartingYear')
    def setFgStartingYear(self, value, **kw):
        """ set starting_year """

        if value:
            try:
                self.fgField.widget.starting_year = int(value)
                self.fgStartingYear = value
            except ValueError:
                pass
        else:
            self.fgField.widget.starting_year = None
            self.fgStartingYear = value


    security.declareProtected(ModifyPortalContent, 'setFgEndingYear')
    def setFgEndingYear(self, value, **kw):
        """ set ending_year """

        if value:
            try:
                self.fgField.widget.ending_year = int(value)
                self.fgEndingYear = value
            except ValueError:
                pass
        else:
            self.fgField.widget.ending_year = None
            self.fgEndingYear = value


    security.declareProtected(ModifyPortalContent, 'setFgFutureYears')
    def setFgFutureYears(self, value, **kw):
        """ set future_years """

        if value:
            try:
                self.fgField.widget.future_years = int(value)
                self.fgFutureYears = value
            except ValueError:
                pass
        else:
            self.fgField.widget.future_years = None
            self.fgFutureYears = value


    def _toLocalizedTime(self, time, long_format=None):
        tool = getToolByName(self, 'translation_service')
        return tool.ulocalized_time(time, long_format=long_format)


    def htmlValue(self, REQUEST):
        """ return from REQUEST, this field's value, rendered as XHTML.
        """

        value = REQUEST.form.get(self.__name__, 'No Input')

        # The replace('-','/') keeps the DateTime routine from
        # interpreting this as UTC. Odd, but true.

        try:
            dt = DateTime(value.replace('-','/'))
        except (DateTimeSyntaxError, DateError):
            # probably better to simply return the input
            return cgi.escape(value)

        if self.fgField.widget.show_hm:
            value = self._toLocalizedTime(dt, long_format=True)
        else:
            value = self._toLocalizedTime(dt)

        return cgi.escape(value)


    def specialValidator(self, value, field, REQUEST, errors):
        """ Archetypes isn't validating non-required dates --
            so we need to.
        """

        fname = field.getName()
        month = REQUEST.form.get('%s_month'%fname, '01')
        day = REQUEST.form.get('%s_month'%fname, '01')

        if (month == '00') and (day == '00'):
            value = ''
            REQUEST.form[fname] = ''

        if value and not field.required:
            try:
                dt = DateTime(value)
            except (DateTimeSyntaxError, DateError):
                return "Validation failed(isValidDate): this is not a valid date."
        return 0
Exemplo n.º 53
0
        schema[afield].widget.visible = {'view': 'invisible', 'edit': 'invisible'}
        schema[afield].schemata = 'default'


###
# we use these fields in several schemata

validatorOverrideField = \
        TALESString('fgTValidator',
            schemata='overrides',
            searchable=0,
            required=0,
            validators=('talesvalidator',),
            default="python:False",
            write_permission=EDIT_TALES_PERMISSION,
            widget=StringWidget(label=_(u'label_fgtvalidator_text', default=u"Custom Validator"),
                description=_(u'help_fgtvalidator_text', default=\
                    u"A TALES expression that will be evaluated when the form is validated."
                    "Validate against 'value', which will contain the field input."
                    "Return False if valid; if not valid return a string error message."
                    "E.G., \"python: test(value=='eggs', False, 'input must be eggs')\" will"
                    "require \"eggs\" for input."
                    "PLEASE NOTE: errors in the evaluation of this expression will cause"
                    "an error on form display."),
                size=70,
                ),
            )

rowsField = \
    IntegerField('fgRows',
        searchable=0,
Exemplo n.º 54
0
from Products.PloneFormGen.config import *
from Products.PloneFormGen.widgets import \
    FieldsetStartWidget, FieldsetEndWidget

from Products.PloneFormGen.interfaces import IPloneFormGenFieldset
from Products.PloneFormGen import PloneFormGenMessageFactory as _

import zope.i18n

FieldsetFolderSchema = ATFolderSchema.copy() + Schema((BooleanField(
    'useLegend',
    required=0,
    searchable=0,
    default='1',
    widget=BooleanWidget(
        label=_(u'label_showlegend_text', default=u'Show Title as Legend'),
        description=_(u'help_showlegend_text', default=u''),
    ),
), ))

FieldsetFolderSchema['description'].widget.label = _(
    u'label_fieldsethelp_text', default=u'Fieldset Help')
FieldsetFolderSchema['description'].widget.description = None
FieldsetFolderSchema.moveField('description', after='useLegend')


class FieldsetFolder(ATFolder):
    """A folder which groups form fields as a fieldset."""
    implements(IPloneFormGenFieldset)

    schema = FieldsetFolderSchema
Exemplo n.º 55
0
class FGMultiSelectField(BaseFormField):
    """ Multiple selection field (select with multiple or check boxes) """

    security  = ClassSecurityInfo()

    schema = BaseFieldSchemaLinesDefault.copy() + Schema((
        vocabularyField,
        vocabularyOverrideField,
        StringField('fgFormat',
            searchable=0,
            required=0,
            default='select',
            enforceVocabulary=1,
            vocabulary='formatVocabDL',
            widget=SelectionWidget(
                label=_('label_fgmsformat_text', default='Presentation Widget'),
                description=_('help_fgmsformat_text', default="""Useful for stopping spam"""),
                ),
        ),
    ))

    # current Archetypes doesn't really support hidden for
    # multi-select. Use a lines field if you really need this
    del schema['hidden']
    del schema['serverSide']
    del schema['placeholder']

    # hide references & discussion
    finalizeFieldSchema(schema, folderish=True, moveDiscussion=False)

    # Standard content type setup
    portal_type = meta_type = 'FormMultiSelectionField'
    archetype_name = 'Multi-Select Field'
    content_icon = 'MultipleListField.gif'
    typeDescription= 'A multiple-selection field'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseFormField.__init__(self, oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = LinesVocabularyField('fg_mselection_field',
            searchable=0,
            required=0,
            widget=MultiSelectionWidget(),
            vocabulary = '_get_selection_vocab',
            enforceVocabulary=1,
            write_permission = View,
            )


    security.declareProtected(ModifyPortalContent, 'setFgFormat')
    def setFgFormat(self, value, **kw):
        """ set selection format """

        self.fgField.widget.format = value
        self.fgFormat = value


    security.declareProtected(ModifyPortalContent, 'setFgRows')
    def setFgRows(self, value, **kw):
        """ sets widget rows """

        self.fgField.widget.size = value


    security.declareProtected(View, 'getFgRows')
    def getFgRows(self, **kw):
        """ gets widget rows """

        return self.fgField.widget.size


    def formatVocabDL(self):
        """ returns vocabulary for fgFormat """

        return DisplayList( (
            ('select',
                    _('vocabulary_selection_text', 'Selection list')
                ),
            ('checkbox',
                    _('vocabulary_checkbox_text', 'Checkbox list')
                )
            ) )


    def htmlValue(self, REQUEST):
        """ Return value instead of key """

        charset = 'utf-8'

        value = REQUEST.form.get(self.__name__, [])

        vocabulary = self.fgField.Vocabulary(self)
        result = []
        for k in value:
            # there'll be an empty string to avoid
            if len(k):
                # vocabulary items are in unicode;
                # so decode the key before lookup
                ku = k.decode(charset)
                v = vocabulary.getValue(ku) or ku
                # v might be unicode or string.  We need string.
                if isinstance(v, str):
                    v = v.encode(charset)
                result.append(v)

        value = ', '.join(result)

        return cgi.escape(value)
Exemplo n.º 56
0
class FGTextField(BaseFormField):
    """ Text (textarea) field """

    security  = ClassSecurityInfo()

    schema = BaseFieldSchemaTextDefault.copy()
    schema += Schema((
        BooleanField('validateNoLinkSpam',
            searchable=0,
            required=0,
            default=False,
            widget=BooleanWidget(
                label=_('label_validate_link_spam_text', default="Reject Text with Links?"),
                description=_('help_validate_link_spam_text', default="""Useful for stopping spam"""),
                ),
            ),
        ))

    # Standard content type setup
    portal_type = meta_type = 'FormTextField'
    archetype_name = 'Text Field'
    content_icon = 'TextAreaField.gif'
    typeDescription= 'A text area field'

    def __init__(self, oid, **kwargs):
        """ initialize class """

        BaseFormField.__init__(self, oid, **kwargs)

        # set a preconfigured field as an instance attribute
        self.fgField = PlainTextField('fg_text_field',
            searchable=0,
            required=0,
            write_permission = View,
            validators=('isNotTooLong','isNotLinkSpam',),
            default_content_type = 'text/plain',
            allowable_content_types = ('text/plain',),
            widget = TextAreaWidget(
                maxlength=0,
                ),
            validate_no_link_spam = 0,
            )

    security.declareProtected(View, 'isBinary')
    def isBinary(self, key):
        return False

    security.declareProtected(View, 'getContentType')
    def getContentType(self, key=None):
        return 'text/plain'

    def setValidateNoLinkSpam(self, value):
        """
        for BBB, to make sure the validator gets enabled on legacy text fields
        """
        self.fgField.validators = ('isNotTooLong', 'isNotLinkSpam')
        self.fgField._validationLayer()

        self.fgField.validate_no_link_spam = value

    def getValidateNoLinkSpam(self):
        return getattr(self.fgField, 'validate_no_link_spam', 0)
Exemplo n.º 57
0
        }
        schema[afield].schemata = 'default'


###
# we use these fields in several schemata

validatorOverrideField = \
        TALESString('fgTValidator',
            schemata='overrides',
            searchable=0,
            required=0,
            validators=('talesvalidator',),
            default="python:False",
            write_permission=EDIT_TALES_PERMISSION,
            widget=StringWidget(label=_(u'label_fgtvalidator_text', default=u"Custom Validator"),
                description=_(u'help_fgtvalidator_text', default=u"""
                    A TALES expression that will be evaluated when the form is validated.
                    Validate against 'value', which will contain the field input.
                    Return False if valid; if not valid return a string error message.
                    E.G., "python: test(value=='eggs', False, 'input must be eggs')" will
                    require "eggs" for input.
                    PLEASE NOTE: errors in the evaluation of this expression will cause
                    an error on form display.
                """),
                size=70,
                ),
            )

rowsField = \
    IntegerField('fgRows',
Exemplo n.º 58
0
from Products.PloneFormGen import HAS_PLONE40

from types import StringTypes

import zope.i18n

logger = logging.getLogger("PloneFormGen")

FormFolderSchema = ATFolderSchema.copy() + Schema((
    StringField(
        'submitLabel',
        required=0,
        searchable=0,
        default="Submit",
        widget=StringWidget(
            label=_(u'label_submitlabel_text', default=u"Submit Button Label"),
            description=_(u'help_submitlabel_text', default=u""),
        ),
    ),
    BooleanField(
        'useCancelButton',
        required=0,
        searchable=0,
        default='0',
        languageIndependent=1,
        widget=BooleanWidget(
            label=_(u'label_showcancel_text', default=u'Show Reset Button'),
            description=_(u'help_showcancel_text'),
        ),
    ),
    StringField(
Exemplo n.º 59
0
    def initializeArchetype(self, **kwargs):
        """ Create sample content that may help folks
            figure out how this gadget works.
        """

        ATFolder.initializeArchetype(self, **kwargs)

        self.setSubmitLabel(
            zope.i18n.translate(_(u'pfg_formfolder_submit', u'Submit'),
                                context=self.REQUEST))
        self.setResetLabel(
            zope.i18n.translate(_(u'pfg_formfolder_reset', u'Reset'),
                                context=self.REQUEST))

        oids = self.objectIds()

        # if we have *any* content already, we don't need
        # the sample content
        if not oids:

            haveMailer = False
            # create a mail action
            try:
                self.invokeFactory('FormMailerAdapter', 'mailer')
                mailer = self['mailer']

                mailer.setTitle(
                    zope.i18n.translate(_(u'pfg_mailer_title', u'Mailer'),
                                        context=self.REQUEST))
                mailer.setDescription(
                    zope.i18n.translate(_(u'pfg_mailer_description',
                                          u'E-Mails Form Input'),
                                        context=self.REQUEST))

                self._pfFixup(mailer)

                self.actionAdapter = ('mailer', )
                haveMailer = True
            except Unauthorized:
                logger.warn(
                    'User not authorized to create mail adapters. Form Folder created with no action adapter.'
                )

            # create a replyto field
            self.invokeFactory('FormStringField', 'replyto')
            obj = self['replyto']
            obj.fgField.__name__ = 'replyto'

            obj.setTitle(
                zope.i18n.translate(_(u'pfg_replytofield_title',
                                      u'Your E-Mail Address'),
                                    context=self.REQUEST))

            obj.fgField.required = True
            obj.setFgStringValidator('isEmail')
            obj.setFgTDefault('here/memberEmail')
            obj.setFgDefault('dynamically overridden')

            self._pfFixup(obj)

            if haveMailer:
                mailer.replyto_field = 'replyto'

            # create a subject field
            self.invokeFactory('FormStringField', 'topic')
            obj = self['topic']
            obj.fgField.__name__ = 'topic'

            obj.setTitle(
                zope.i18n.translate(_(u'pfg_topicfield_title', u'Subject'),
                                    context=self.REQUEST))

            obj.fgField.required = True

            self._pfFixup(obj)

            if haveMailer:
                mailer.subject_field = 'topic'

            # create a comments field
            self.invokeFactory('FormTextField', 'comments')
            obj = self['comments']
            obj.fgField.__name__ = 'comments'

            obj.setTitle(
                zope.i18n.translate(_(u'pfg_commentsfield_title', u'Comments'),
                                    context=self.REQUEST))

            obj.fgField.required = True

            self._pfFixup(obj)

            # create a thanks page
            self.invokeFactory('FormThanksPage', 'thank-you')
            obj = self['thank-you']

            obj.setTitle(
                zope.i18n.translate(_(u'pfg_thankyou_title', u'Thank You'),
                                    context=self.REQUEST))
            obj.setDescription(
                zope.i18n.translate(_(u'pfg_thankyou_description',
                                      u'Thanks for your input.'),
                                    context=self.REQUEST))

            self._pfFixup(obj)

            self.thanksPage = 'thank-you'