Ejemplo n.º 1
0
class IExcludeFromNavigation(model.Schema):
    """Behavior interface to exclude items from navigation.
    """

    model.fieldset(
        'settings',
        label=_(u"Settings"),
        fields=['exclude_from_nav']
    )

    exclude_from_nav = schema.Bool(
        title=_(
            u'label_exclude_from_nav',
            default=u'Exclude from navigation'
        ),
        description=_(
            u'help_exclude_from_nav',
            default=u'If selected, this item will not appear in the ' +
                    u'navigation tree'
        ),
        default=False
    )

    form.omitted('exclude_from_nav')
    form.no_omit(IEditForm, 'exclude_from_nav')
    form.no_omit(IAddForm, 'exclude_from_nav')
 def description(self):
     if self.get_items():
         return _(u'The following custom content types are available for '
                  u'your site.')
     else:
         return _(u'Click the "Add Content Type" button to begin creating '
                  u' a new custom content type.')
Ejemplo n.º 3
0
 def description(self):
     if self.get_items():
         return _(u'The following custom content types are available for '
                  u'your site.')
     else:
         return _('help_addcontenttype_button',
                  default=HELP)
Ejemplo n.º 4
0
class IPublication(model.Schema):
    # dates fieldset
    model.fieldset(
        'dates',
        label=_(u'label_schema_dates', default=u'Dates'),
        fields=['effective', 'expires'],
    )

    effective = schema.Datetime(
        title=_(u'label_effective_date', u'Publishing Date'),
        description=_(
            u'help_effective_date',
            default=u"If this date is in the future, the content will "
            u"not show up in listings and searches until this date."),
        required=False)
    directives.widget('effective', DatetimeFieldWidget)

    expires = schema.Datetime(
        title=_(u'label_expiration_date', u'Expiration Date'),
        description=_(u'help_expiration_date',
                      default=u"When this date is reached, the content will no"
                      u"longer be visible in listings and searches."),
        required=False)
    directives.widget('expires', DatetimeFieldWidget)

    @invariant
    def validate_start_end(data):
        if data.effective and data.expires and data.effective > data.expires:
            raise EffectiveAfterExpires(
                _("error_expiration_must_be_after_effective_date",
                  default=u"Expiration date must be after publishing date."))

    directives.omitted('effective', 'expires')
    directives.no_omit(IEditForm, 'effective', 'expires')
    directives.no_omit(IAddForm, 'effective', 'expires')
Ejemplo n.º 5
0
 def description(self):
     if self.get_items():
         return _(u'The following custom content types are available for '
                  u'your site.')
     else:
         return _('help_addcontenttype_button',
                  default=HELP)
class TypeProfileImportForm(form.AddForm):

    label = _(u'Import Content Types')
    description = _(
        u"You may import types by uploading a zip archive containing type "
        u"profiles. The import archive should contain a types.xml file and a "
        u"types directory containing one or more Dexterity type information "
        u"files. For a sample, create a content type and export it from the "
        u"Dexterity Content Types page.")
    fields = field.Fields(ITypeProfileImport)
    id = 'import-types-form'

    def create(self, data):
        return TypeProfileImport(**data)

    def add(self, profile_import):
        # initialize import context
        types_tool = getToolByName(self.context, 'portal_types')
        import_context = ZipFileImportContext(
            types_tool, StringIO(profile_import.profile_file.data))
        # run the profile
        setup_tool = getToolByName(self.context, 'portal_setup')
        handler = setup_tool.getImportStep(u'typeinfo')
        handler(import_context)
        self.status = _(u"Imported successfully.")

    def nextURL(self):
        url = self.context.absolute_url()
        return url
Ejemplo n.º 7
0
class IFieldType(interface.Interface):

    field_type = schema.Choice(title=_(u'Field type'),
                               description=_(u'Select field type'),
                               required=True,
                               default=u'select',
                               vocabulary=field_types)
Ejemplo n.º 8
0
class ICategorization(model.Schema):

    # categorization fieldset
    model.fieldset(
        'categorization',
        label=_(u'label_schema_categorization', default=u'Categorization'),
        fields=['subjects', 'language'],
    )

    subjects = schema.Tuple(
        title=_(u'label_tags', default=u'Tags'),
        description=_(
            u'help_tags',
            default=u'Tags are commonly used for ad-hoc organization of ' +
            u'content.'),
        value_type=schema.TextLine(),
        required=False,
        missing_value=(),
    )
    directives.widget('subjects',
                      AjaxSelectFieldWidget,
                      vocabulary='plone.app.vocabularies.Keywords')

    language = schema.Choice(
        title=_(u'label_language', default=u'Language'),
        vocabulary='plone.app.vocabularies.AvailableContentLanguages',
        required=False,
        missing_value='',
        defaultFactory=default_language,
    )
    directives.widget('language', SelectFieldWidget)

    directives.omitted('subjects', 'language')
    directives.no_omit(IEditForm, 'subjects', 'language')
    directives.no_omit(IAddForm, 'subjects', 'language')
Ejemplo n.º 9
0
    def __call__(self):
        """Handle AJAX save post.
        """

        if not authorized(self.context, self.request):
            raise Unauthorized

        source = self.request.form.get("source")
        if source:
            # Is it valid XML?
            try:
                root = etree.fromstring(source)
            except etree.XMLSyntaxError, e:
                return json.dumps({"success": False, "message": "XMLSyntaxError: %s" % e.message.encode("utf8")})

            # a little more sanity checking, look at first two element levels
            if root.tag != NAMESPACE + "model":
                return json.dumps({"success": False, "message": _(u"Error: root tag must be 'model'")})
            for element in root.getchildren():
                if element.tag != NAMESPACE + "schema":
                    return json.dumps({"success": False, "message": _(u"Error: all model elements must be 'schema'")})

            # can supermodel parse it?
            # This is mainly good for catching bad dotted names.
            try:
                plone.supermodel.loadString(source, policy=u"dexterity")
            except SupermodelParseError, e:
                message = e.args[0].replace('\n  File "<unknown>"', "")
                return json.dumps({"success": False, "message": u"SuperModelParseError: %s" % message})
Ejemplo n.º 10
0
class TypeBehaviorsForm(form.EditForm):

    template = ViewPageTemplateFile('behaviors.pt')
    label = _(u'Behaviors')
    description = _(u'Select the behaviors to enable for this content type.')
    successMessage = _(u'Behaviors successfully updated.')
    noChangesMessage = _(u'No changes were made.')
    buttons = deepcopy(form.EditForm.buttons)
    buttons['apply'].title = PMF(u'Save')

    def getContent(self):
        return BehaviorConfigurationAdapter(self.context)

    @property
    def fields(self):
        fields = []
        for name, reg in getUtilitiesFor(IBehavior):
            if name == 'plone.app.dexterity.behaviors.related.IRelatedItems':
                # skip deprecated behavior
                continue

            f = schema.Bool(__name__=str(name),
                            title=reg.title,
                            description=reg.description,
                            required=False)
            fields.append(f)
        fields = sorted(fields, key=lambda x: x.title)
        fields = field.Fields(*fields)

        for f in fields.values():
            f.widgetFactory = SingleCheckBoxFieldWidget
        return fields
class IRootNavigationPortlet(model.Schema):
    
    model.fieldset(
        'navigation',
        label=_(u"Navigation"),
        fields=['portlet_nav_root', 'portlet_nav_root_title',
                'portlet_nav_topLevel',
        ]
    )
    
    portlet_nav_root = schema.Bool(
        title=_(
            u'label_portlet_nav_root',
            default=u'Navigation root'
        ),
        description=_(
            u"help_portlet_nav_root",
            default=u"Use as root of the navigation tree"
        ),
        required=False,
    )
    
    portlet_nav_root_title = schema.TextLine(
        title=_(
            u'label_portlet_nav_root_title',
            default=u'Navigation root title'
        ),
        description=_(
            u"help_portlet_nav_root_title",
            default=u"if selected, use this as title "
                     "of the navigation root, instead of content title"
        ),
        required=False,
    )
    
    portlet_nav_topLevel = schema.Int(
        title=_navigation(u"label_navigation_startlevel", default=u"Start level"),
        description=_navigation(u"help_navigation_start_level",
            default=u"An integer value that specifies the number of folder "
                     "levels below the site root that must be exceeded "
                     "before the navigation tree will display. 0 means "
                     "that the navigation tree should be displayed "
                     "everywhere including pages in the root of the site. "
                     "1 means the tree only shows up inside folders "
                     "located in the root and downwards, never showing "
                     "at the top level."),
        required=False,
    )
    
    directives.omitted(
        'portlet_nav_root', 'portlet_nav_root_title', 'portlet_nav_topLevel'
    )
    directives.no_omit(
        IEditForm, 'portlet_nav_root', 'portlet_nav_root_title',
        'portlet_nav_topLevel'
    )
    directives.no_omit(
        IEditForm, 'portlet_nav_root', 'portlet_nav_root_title',
        'portlet_nav_topLevel'
    )
Ejemplo n.º 12
0
class IRelatedItems(model.Schema):
    """Behavior interface to make a Dexterity type support related items.
    """

    relatedItems = RelationList(
        title=_(u'label_related_items', default=u'Related Items'),
        default=[],
        value_type=RelationChoice(
            title=u'Related',
            vocabulary='plone.app.vocabularies.Catalog'
        ),
        required=False
    )
    form.widget(
        'relatedItems',
        RelatedItemsFieldWidget,
        vocabulary='plone.app.vocabularies.Catalog',
        pattern_options={
            'recentlyUsed': True,  # Just turn on. Config in plone.app.widgets.
        }
    )

    fieldset(
        'categorization',
        label=_(u'Categorization'),
        fields=['relatedItems']
    )
Ejemplo n.º 13
0
 def description(self):
     if self.get_items():
         return _(u'The following custom content types are available for '
                  u'your site.')
     else:
         return _(
             'help_addcontenttype_button',
             default=u'Click the "Add Content Type" button to begin creating '
             u' a new custom content type.')
Ejemplo n.º 14
0
 def description(self):
     if self.get_items():
         return _(u'The following custom content types are available for '
                  u'your site.')
     else:
         return _('help_addcontenttype_button',
                  default= u'Content types show up on Plone's \"Add Item\" menu and allow '
                           u'you to store custom data in your site. Click the \"Add Content '
                           u'Type\" button to begin creating a new content type with its '
                           u'own fields.')
Ejemplo n.º 15
0
class ITestimonial(model.Schema):

    # categorization fieldset
    model.fieldset(
        'testimonial',
        label=_(u'label_schema_testimonial', default=u'Testimonial'),
        fields=['person'],
    )

    person = schema.TextLine(title=_(u'label_person', default=u'Person'),
                             required=False)
Ejemplo n.º 16
0
    def handleClone(self, action):
        selected = self.selected_items()

        if len(selected) > 1:
            self.status = _(u'Please select a single type to clone.')
        elif len(selected) == 1:
            id = selected[0][0]
            url = '%s/%s/@@clone' % (self.context.context.absolute_url(), id)
            self.request.response.redirect(url)
        else:
            self.status = _(u'Please select a type to clone.')
Ejemplo n.º 17
0
    def handleClone(self, action):
        selected = self.selected_items()

        if len(selected) > 1:
            self.status = _(u'Please select a single type to clone.')
        elif len(selected) == 1:
            id = selected[0][0]
            url = '%s/%s/@@clone' % (self.context.context.absolute_url(), id)
            self.request.response.redirect(url)
        else:
            self.status = _(u'Please select a type to clone.')
Ejemplo n.º 18
0
 def description(self):
     if self.get_items():
         return _(
             u'The following custom content types are available for your '
             u'site.')
     return _(
         'help_addcontenttype_button',
         default=u'Content types show up on Plone\'s "Add Item" menu and '
         u'allow you to store custom data in your site. Click the '
         u'"Add Content Type" button to begin creating a new '
         u'content type with its own fields.')
Ejemplo n.º 19
0
 def description(self):
     if self.get_items():
         return _(
             u'The following custom content types are available for your '
             u'site.'
         )
     return _(
         'help_addcontenttype_button',
         default= u'Content types show up on Plone\'s "Add Item" menu and '
                  u'allow you to store custom data in your site. Click the '
                  u'"Add Content Type" button to begin creating a new '
                  u'content type with its own fields.')
Ejemplo n.º 20
0
class TypeEditForm(crud.EditForm):
    """Content type edit form.

    Just a normal CRUD form without the form title or edit button.
    """

    label = None
    editsubform_factory = TypeEditSubForm

    buttons = crud.EditForm.buttons.copy().omit('edit')
    handlers = crud.EditForm.handlers.copy()

    @button.buttonAndHandler(_(u'Clone'))
    def handleClone(self, action):
        selected = self.selected_items()

        if len(selected) > 1:
            self.status = _(u'Please select a single type to clone.')
        elif len(selected) == 1:
            id = selected[0][0]
            url = '{0}/{1}/@@clone'.format(
                self.context.context.absolute_url(),
                id
            )
            self.request.response.redirect(url)
        else:
            self.status = _(u'Please select a type to clone.')

    @button.buttonAndHandler(_(u'Export Type Profiles'))
    def handleExport(self, action):
        selected = ','.join([items[0] for items in self.selected_items()])

        if len(selected) == 0:
            self.status = _(u'Please select types to export.')
        elif len(selected) > 0:
            url = '{0}/@@types-export?selected={1}'.format(
                self.context.context.absolute_url(),
                urllib.quote(selected),
            )
            self.request.response.redirect(url)

    @button.buttonAndHandler(_(u'Export Schema Models'))
    def handleExportModels(self, action):
        selected = ','.join([items[0] for items in self.selected_items()])

        if len(selected) == 0:
            self.status = _(u'Please select types to export.')
        elif len(selected) > 0:
            url = '{0}/@@models-export?selected={1}'.format(
                self.context.context.absolute_url(),
                urllib.quote(selected)
            )
            self.request.response.redirect(url)
Ejemplo n.º 21
0
class IShortName(model.Schema):

    model.fieldset(
        'settings',
        label=_(u"Settings"),
        fields=['id'],
    )

    id = schema.ASCIILine(
        title=_(u'Short name'),
        description=_(u'This name will be displayed in the URL.'),
        required=False,
    )
    directives.write_permission(id='cmf.AddPortalContent')
    def __call__(self):
        """Handle AJAX save post.
        """

        if not authorized(self.context, self.request):
            raise Unauthorized

        source = self.request.form.get('source')
        if source:
            # Is it valid XML?
            try:
                root = etree.fromstring(source)
            except etree.XMLSyntaxError, e:
                return json.dumps({
                    'success':
                    False,
                    'message':
                    "XMLSyntaxError: %s" % e.message.encode('utf8')
                })

            # a little more sanity checking, look at first two element levels
            if root.tag != NAMESPACE + 'model':
                return json.dumps({
                    'success':
                    False,
                    'message':
                    _(u"Error: root tag must be 'model'")
                })
            for element in root.getchildren():
                if element.tag != NAMESPACE + 'schema':
                    return json.dumps({
                        'success':
                        False,
                        'message':
                        _(u"Error: all model elements must be 'schema'")
                    })

            # can supermodel parse it?
            # This is mainly good for catching bad dotted names.
            try:
                plone.supermodel.loadString(source, policy=u"dexterity")
            except SupermodelParseError, e:
                message = e.args[0].replace('\n  File "<unknown>"', '')
                return json.dumps({
                    'success':
                    False,
                    'message':
                    u"SuperModelParseError: %s" % message
                })
Ejemplo n.º 23
0
class IAllowDiscussion(model.Schema):

    model.fieldset(
        'settings',
        label=_(u"Settings"),
        fields=['allow_discussion'],
    )

    allow_discussion = schema.Choice(
        title=_(u'Allow discussion'),
        description=_(u'Allow discussion for this content object.'),
        vocabulary=options,
        required=False,
        default=None,
    )
Ejemplo n.º 24
0
    def validate(self, value):
        super(TypeIdValidator, self).validate(value)

        ttool = getToolByName(self.context, "portal_types")
        if value in ttool.objectIds():
            msg = u"There is already a content type named '${name}'"
            raise Invalid(_(msg, mapping={"name": value}))
Ejemplo n.º 25
0
class TypeCloneForm(form.AddForm):

    label = _(u'Clone Content Type')
    fields = field.Fields(ITypeSettings).select('title', 'id')
    id = 'clone-type-form'

    def create(self, data):
        type_id = data.pop('id')
        props = dict(self.context.fti.propertyItems())
        # make sure we don't share the factory
        if props['factory'] == self.context.fti.getId():
            del props['factory']

        props['title'] = data['title']
        props['add_view_expr'] = props['add_view_expr'].replace(self.context.fti.getId(), type_id)
        fti = DexterityFTI(type_id, **props)
        return fti

    def add(self, fti):
        ttool = getToolByName(self.context, 'portal_types')
        ttool._setObject(fti.id, fti)
        self.status = _(u"Type cloned successfully.")

    def nextURL(self):
        return self.context.aq_parent.absolute_url()
Ejemplo n.º 26
0
    def validate(self, value):
        super(TypeIdValidator, self).validate(value)

        ttool = getToolByName(self.context, 'portal_types')
        if value in ttool.objectIds():
            raise Invalid(_(u"There is already a content type named '${name}'",
                          mapping={'name': value}))
Ejemplo n.º 27
0
    def validate(self, value):
        super(TypeIdValidator, self).validate(value)

        ttool = getToolByName(self.context, 'portal_types')
        if value in ttool.objectIds():
            msg = u"There is already a content type named '${name}'"
            raise Invalid(_(msg, mapping={'name': value}))
Ejemplo n.º 28
0
    def isGoodImportFile(data):
        nfile = getattr(data, 'profile_file', None)
        if nfile is None:
            # let required validator handle this
            return None
        try:
            archive = ZipFile(StringIO(data.profile_file.data), 'r')
        except BadZipfile:
            raise Invalid(
                _(u"Error: The file submitted must be a zip archive."),
            )
        name_list = archive.namelist()
        for fname in name_list:
            if fname == 'types.xml':
                continue
            if os.path.dirname(fname) != 'types' \
               or os.path.splitext(fname)[1] != '.xml':
                raise Invalid(
                    _(u"Error: The file submitted must be a zip archive "
                      u"containing only type profile information.")
                )

        # check XML for basic integrity
        with archive.open('types.xml', 'rU') as f:
            source = f.read()
            root = etree.fromstring(source)
            if root.tag != 'object':
                raise Invalid(_(u'types.xml in archive is invalid.'))

        # check against existing types; don't allow overwrites
        site = getSite()
        existing_types = getToolByName(site, 'portal_types').listContentTypes()
        for element in root.getchildren():
            if element.tag == 'object':
                attribs = element.attrib
                if not attribs['meta_type'] == 'Dexterity FTI':
                    raise Invalid(_(
                        'Types in archive must be only Dexterity types.'
                    ),)
                if attribs['name'] in existing_types:
                    msg = (
                        u'One or more types in the import archive is an '
                        u'existing type. Delete "%s" if you '
                        u'really wish to replace it.'
                    )
                    raise Invalid(_(msg, attribs['name']), )
Ejemplo n.º 29
0
    def isGoodImportFile(data):
        nfile = getattr(data, 'profile_file', None)
        if nfile is None:
            # let required validator handle this
            return None
        try:
            archive = ZipFile(StringIO(data.profile_file.data), 'r')
        except BadZipfile:
            raise Invalid(
                _(u"Error: The file submitted must be a zip archive."),
            )
        name_list = archive.namelist()
        for fname in name_list:
            if fname == 'types.xml':
                continue
            if os.path.dirname(fname) != 'types' \
               or os.path.splitext(fname)[1] != '.xml':
                raise Invalid(
                    _(u"Error: The file submitted must be a zip archive "
                      u"containing only type profile information.")
                )

        # check XML for basic integrity
        with archive.open('types.xml', 'rU') as f:
            source = f.read()
            root = etree.fromstring(source)
            if root.tag != 'object':
                raise Invalid(_(u'types.xml in archive is invalid.'))

        # check against existing types; don't allow overwrites
        site = getSite()
        existing_types = getToolByName(site, 'portal_types').listContentTypes()
        for element in root.getchildren():
            if element.tag == 'object':
                attribs = element.attrib
                if not attribs['meta_type'] == 'Dexterity FTI':
                    raise Invalid(_(
                        'Types in archive must be only Dexterity types.'
                    ),)
                if attribs['name'] in existing_types:
                    msg = (
                        u'One or more types in the import archive is an '
                        u'existing type. Delete "%s" if you '
                        u'really wish to replace it.'
                    )
                    raise Invalid(_(msg, attribs['name']), )
Ejemplo n.º 30
0
def reValidate(value, recls):
    if recls.ignore:
        tvalue = recls.ignore.sub(u"", value)
    else:
        tvalue = value
    if not recls.regex.match(tvalue):
        raise zope.interface.Invalid(_(recls.msgid, recls.errmsg, mapping={u"value": value}))
    return True
Ejemplo n.º 31
0
 def validate_start_end(data):
     if data.effective and data.expires and data.effective > data.expires:
         raise EffectiveAfterExpires(
             _(
                 "error_expiration_must_be_after_effective_date",
                 default=u"Expiration date must be after publishing date.",
             )
         )
Ejemplo n.º 32
0
class IOwnership(model.Schema):

    # ownership fieldset
    model.fieldset(
        'ownership',
        label=_(
            'label_schema_ownership',
            default=u'Ownership'
        ),
        fields=['creators', 'contributors', 'rights'],
    )

    creators = schema.Tuple(
        title=_(u'label_creators', u'Creators'),
        description=_(
            u'help_creators',
            default=u'Persons responsible for creating the content of '
                    u'this item. Please enter a list of user names, one '
                    u'per line. The principal creator should come first.'
        ),
        value_type=schema.TextLine(),
        required=False,
        missing_value=(),
    )
    directives.widget(
        'creators',
        AjaxSelectFieldWidget,
        vocabulary='plone.app.vocabularies.Users'
    )

    contributors = schema.Tuple(
        title=_(u'contributors', u'Contributors'),
        description=_(
            u'help_contributors',
            default=u'The names of people that have contributed '
                    u'to this item. Each contributor should '
                    u'be on a separate line.'),
        value_type=schema.TextLine(),
        required=False,
        missing_value=(),
    )
    directives.widget(
        'contributors',
        AjaxSelectFieldWidget,
        vocabulary='plone.app.vocabularies.Users'
    )

    rights = schema.Text(
        title=_(u'label_copyrights', default=u'Rights'),
        description=_(
            u'help_copyrights',
            default=u'Copyright statement or other rights information on this '
                    u'item.'
        ),
        required=False,
    )

    directives.omitted('creators', 'contributors', 'rights')
    directives.no_omit(IEditForm, 'creators', 'contributors', 'rights')
    directives.no_omit(IAddForm, 'creators', 'contributors', 'rights')
Ejemplo n.º 33
0
    def __init__(self, context, request):
        super(TypesContext, self).__init__(context, request)

        # make sure that breadcrumbs will be correct
        self.id = None
        self.Title = lambda: _(u'Dexterity Content Types')

        # turn off green edit border for anything in the type control panel
        request.set('disable_border', 1)
Ejemplo n.º 34
0
    def __init__(self, context, request):
        super(TypesContext, self).__init__(context, request)

        # make sure that breadcrumbs will be correct
        self.id = None
        self.Title = lambda: _(u'Dexterity Content Types')

        # turn off green edit border for anything in the type control panel
        request.set('disable_border', 1)
Ejemplo n.º 35
0
class TypeFieldsPage(TypeFormLayout):
    label = _(u'Fields')

    @property
    def form(self):
        if self.context.fti.hasDynamicSchema:
            return EnhancedSchemaListing
        else:
            return ReadOnlySchemaListing
Ejemplo n.º 36
0
class IExcludeFromNavigationForm(IExcludeFromNavigation):
    """Behavior interface to exclude items from navigation.
    """
    model.fieldset('new', label=_(u"New Setting"), fields=['exclude_from_nav'])

    exclude_from_nav = schema.Bool(
        title=_(u'label_exclude_from_nav',
                default=u'Exclude from TEST navigation'),
        description=_(
            u'help_exclude_from_nav',
            default=u'If selected, this item will not appear in the ' +
            u'navigation tree'),
        default=True,
        readonly=True,
    )

    form.omitted('exclude_from_nav')
    form.omitted(IEditForm, 'exclude_from_nav')
class ITypeSettings(Interface):
    """ Define the fields for the content type add form
    """
    title = schema.TextLine(
        title=_(u'Type Name'),
    )

    id = schema.ASCIILine(
        title=_(u'Short Name'),
        description=_(u'Used for programmatic access to the type.'),
        required=True,
        constraint=isValidId,
    )

    description = schema.Text(
        title=_(u'Description'),
        required=False
    )

    container = schema.Bool(
        title=_(u'Container'),
        description=_(
            u'Items of this type will be able to contain other items.'),
        required=True,
        default=False,
    )

    filter_content_types = schema.Choice(
        title=_(u'Filter Contained Types'),
        description=_(
            'label_filter_contained_types',
            default=(
                u'Items of this type can act as a folder containing other '
                u' items. What content types should be allowed inside?')
        ),
        values=('none', 'all', 'some'),
        default='none',
        required=True
    )

    allowed_content_types = schema.Set(
        title=_(u'Allowed Content Types'),
        required=False,
        value_type=schema.Choice(
            vocabulary='plone.app.vocabularies.ReallyUserFriendlyTypes',
            required=False
        )
    )
Ejemplo n.º 38
0
    def handleExportModels(self, action):
        selected = ",".join([items[0] for items in self.selected_items()])

        if len(selected) == 0:
            self.status = _(u'Please select types to export.')
        elif len(selected) > 0:
            url = '%s/@@models-export?selected=%s' % \
                (self.context.context.absolute_url(),
                 urllib.quote(selected))
            self.request.response.redirect(url)
Ejemplo n.º 39
0
    def handleExportModels(self, action):
        selected = ",".join([items[0] for items in self.selected_items()])

        if len(selected) == 0:
            self.status = _(u'Please select types to export.')
        elif len(selected) > 0:
            url = '%s/@@models-export?selected=%s' % \
                (self.context.context.absolute_url(),
                 urllib.quote(selected))
            self.request.response.redirect(url)
 def add(self, profile_import):
     # initialize import context
     types_tool = getToolByName(self.context, 'portal_types')
     import_context = ZipFileImportContext(
         types_tool, StringIO(profile_import.profile_file.data))
     # run the profile
     setup_tool = getToolByName(self.context, 'portal_setup')
     handler = setup_tool.getImportStep(u'typeinfo')
     handler(import_context)
     self.status = _(u"Imported successfully.")
Ejemplo n.º 41
0
    def handleExport(self, action):
        selected = ','.join([items[0] for items in self.selected_items()])

        if len(selected) == 0:
            self.status = _(u'Please select types to export.')
        elif len(selected) > 0:
            url = '{0}/@@types-export?selected={1}'.format(
                self.context.context.absolute_url(),
                urllib.quote(selected),
            )
            self.request.response.redirect(url)
Ejemplo n.º 42
0
    def validate(self, value):
        super(TypeTitleValidator, self).validate(value)

        ttool = getToolByName(self.context, 'portal_types')
        for existing_fti in ttool.objectValues():
            if aq_base(existing_fti) is aq_base(self.context):
                continue

            if existing_fti.Title() == value:
                raise Invalid(_(u"There is already a content type named '${name}'",
                              mapping={'name': value}))
Ejemplo n.º 43
0
    def validate(self, value):
        super(TypeTitleValidator, self).validate(value)

        ttool = getToolByName(self.context, 'portal_types')
        for existing_fti in ttool.objectValues():
            if aq_base(existing_fti) is aq_base(self.context):
                continue

            if existing_fti.Title() == value:
                msg = u"There is already a content type named '${name}'"
                raise Invalid(_(msg, mapping={'name': value}))
Ejemplo n.º 44
0
class IBasic(model.Schema):

    # default fieldset
    title = schema.TextLine(title=_(u'label_title', default=u'Title'),
                            required=True)

    description = schema.Text(
        title=_(u'label_description', default=u'Summary'),
        description=_(u'help_description',
                      default=u'Used in item listings and search results.'),
        required=False,
        missing_value=u'',
    )

    directives.order_before(description='*')
    directives.order_before(title='*')

    directives.omitted('title', 'description')
    directives.no_omit(IEditForm, 'title', 'description')
    directives.no_omit(IAddForm, 'title', 'description')
Ejemplo n.º 45
0
 def add(self, profile_import):
     # initialize import context
     types_tool = getToolByName(self.context, 'portal_types')
     import_context = ZipFileImportContext(
         types_tool,
         StringIO(profile_import.profile_file.data)
     )
     # run the profile
     setup_tool = getToolByName(self.context, 'portal_setup')
     handler = setup_tool.getImportStep(u'typeinfo')
     handler(import_context)
     self.status = _(u"Imported successfully.")
Ejemplo n.º 46
0
    def validate(self, value):
        super(RegExValidator, self).validate(value)

        if value is None:
            return

        if self.ignore:
            tvalue = self.ignore.sub(u'', value)
        else:
            tvalue = value

        if not self.regex.match(tvalue):
            raise zope.interface.Invalid(_(self.msgid, self.errmsg, mapping={u'value': value}))
Ejemplo n.º 47
0
 def tabs(self):
     return ((_("Overview"), "@@overview"), (_("Fields"), "@@fields"), (_("Behaviors"), "@@behaviors"))
Ejemplo n.º 48
0
    if HAS_CONTENTTREE and not HAS_WIDGETS:

        relatedItems = RelationList(
            title=_(u'label_related_items', default=u'Related Items'),
            default=[],
            value_type=RelationChoice(
                title=u"Related",
                source=ObjPathSourceBinder()
            ),
            required=False
        )

    else:

        relatedItems = RelationList(
            title=_(u'label_related_items', default=u'Related Items'),
            default=[],
            value_type=RelationChoice(
                title=u"Related",
                vocabulary="plone.app.vocabularies.Catalog"
            ),
            required=False
        )

fieldset = Fieldset('categorization',
                    label=_(u'Categorization'), fields=['relatedItems'])
IRelatedItems.setTaggedValue(FIELDSETS_KEY, [fieldset])

alsoProvides(IRelatedItems, IFormFieldProvider)
Ejemplo n.º 49
0
from z3c.relationfield.schema import RelationChoice, RelationList
from plone.formwidget.contenttree import ObjPathSourceBinder

from plone.supermodel.interfaces import FIELDSETS_KEY
from plone.supermodel.model import Fieldset

from plone.autoform.interfaces import IFormFieldProvider

try:
    from plone.app.dexterity import MessageFactory as _
except ImportError:
    _ = unicode


class IRelatedItems(Interface):
    """Behavior interface to make a Dexterity type support related items.
    """

    relatedItems = RelationList(
        title=_(u'label_related_items', default=u'Related Items'),
        default=[],
        value_type=RelationChoice(title=u"Related",
                      source=ObjPathSourceBinder()),
        required=False,
        )

fieldset = Fieldset('categorization', label=_(u'Categorization'), fields=['relatedItems'])
IRelatedItems.setTaggedValue(FIELDSETS_KEY, [fieldset])

alsoProvides(IRelatedItems, IFormFieldProvider)
Ejemplo n.º 50
0
 def add(self, fti):
     ttool = getToolByName(self.context, 'portal_types')
     ttool._setObject(fti.id, fti)
     self.status = _(u"Type cloned successfully.")
Ejemplo n.º 51
0
# -*- coding: utf-8 -*-
from plone.app.dexterity import _
from plone.autoform import directives
from plone.autoform.interfaces import IFormFieldProvider
from plone.supermodel import model
from z3c.form.interfaces import IAddForm
from z3c.form.interfaces import IEditForm
from zope import schema
from zope.interface import provider
from zope.schema.vocabulary import SimpleTerm
from zope.schema.vocabulary import SimpleVocabulary


options = SimpleVocabulary([SimpleTerm(value=True, title=_(u"Yes")), SimpleTerm(value=False, title=_(u"No"))])


@provider(IFormFieldProvider)
class IAllowDiscussion(model.Schema):

    model.fieldset("settings", label=_(u"Settings"), fields=["allow_discussion"])

    allow_discussion = schema.Choice(
        title=_(u"Allow discussion"),
        description=_(u"Allow discussion for this content object."),
        vocabulary=options,
        required=False,
        default=None,
    )

    directives.omitted("allow_discussion")
    directives.no_omit(IEditForm, "allow_discussion")
Ejemplo n.º 52
0
 def tabs(self):
     return (
         (_('Overview'), '@@overview'),
         (_('Fields'), '@@fields'),
         (_('Behaviors'), '@@behaviors'),
         )
Ejemplo n.º 53
0
    def remove(self, (id, item)):
        """ Remove a content type.
        """
        ttool = getToolByName(self.context, 'portal_types')
        ttool.manage_delObjects([id])

    def link(self, item, field):
        """ Generate links to the edit page for each type.
            (But only for types with schemata that can be edited through the web.)
        """
        if field == 'title':
            return '%s/%s' % (self.context.absolute_url(), item.__name__)

# Create a form wrapper so the form gets layout.
TypesListingPage = layout.wrap_form(TypesListing, __wrapper_class=TypesEditFormWrapper, label=_(u'Dexterity content types'))


class TypeSchemaContext(SchemaContext):
    implements(ITypeSchemaContext)

    fti = None
    schemaName = u''
    schemaEditorView = 'fields'
    
    def browserDefault(self, request):
        return self, ('@@overview',)
    
    @property
    def additionalSchemata(self):
        return getAdditionalSchemata(portal_type=self.fti.getId())
Ejemplo n.º 54
0
    def link(self, item, field):
        """Generate links to the edit page for each type.

        (But only for types with schemata that can be edited through the web.)
        """
        if field == 'title':
            return '{0}/{1}'.format(
                self.context.absolute_url(),
                urllib.quote(item.__name__)
            )

# Create a form wrapper so the form gets layout.
TypesListingPage = layout.wrap_form(
    TypesListing, __wrapper_class=TypesEditFormWrapper,
    label=_(u'Dexterity Content Types'))


@implementer(ITypeSchemaContext)
class TypeSchemaContext(SchemaContext):

    fti = None
    schemaName = u''
    schemaEditorView = 'fields'

    def browserDefault(self, request):
        return self, ('@@overview',)

    @property
    def additionalSchemata(self):
        return getAdditionalSchemata(portal_type=self.fti.getId())
Ejemplo n.º 55
0
    def remove(self, (id, item)):
        """ Remove a content type.
        """
        ttool = getToolByName(self.context, 'portal_types')
        ttool.manage_delObjects([id])

    def link(self, item, field):
        """ Generate links to the edit page for each type.
            (But only for types with schemata that can be edited through the web.)
        """
        if field == 'title':
            return '%s/%s' % (self.context.absolute_url(), item.__name__)

# Create a form wrapper so the form gets layout.
TypesListingPage = layout.wrap_form(TypesListing, label=_(u'Dexterity content types'))


class TypeSchemaContext(SchemaContext):
    implements(ITypeSchemaContext)

    fti = None
    schemaName = u''
    schemaEditorView = 'fields'
    
    def browserDefault(self, request):
        return self, ('@@overview',)
    
    @property
    def additionalSchemata(self):
        return getAdditionalSchemata(portal_type=self.fti.getId())
Ejemplo n.º 56
0
 def no_items_message(self):
     return _(
         'description_no_items_in_folder',
         default=u'There are currently no items in this folder.'
     )
Ejemplo n.º 57
0
 def tabs(self):
     return (
         (_('Fields'), None),
         (_('Behaviors'), '@@behaviors'),
         )
Ejemplo n.º 58
0
    def link(self, item, field):
        """Generate links to the edit page for each type.

        (But only for types with schemata that can be edited through the web.)
        """
        if field == 'title':
            return '{0}/{1}'.format(
                self.context.absolute_url(),
                urllib.quote(item.__name__)
            )

# Create a form wrapper so the form gets layout.
TypesListingPage = layout.wrap_form(
    TypesListing, __wrapper_class=TypesEditFormWrapper,
    label=_(u'Dexterity content types'))


@implementer(ITypeSchemaContext)
class TypeSchemaContext(SchemaContext):

    fti = None
    schemaName = u''
    schemaEditorView = 'fields'

    def browserDefault(self, request):
        return self, ('@@overview',)

    @property
    def additionalSchemata(self):
        return getAdditionalSchemata(portal_type=self.fti.getId())
Ejemplo n.º 59
0
# -*- coding: utf-8 -*-
from z3c.form.interfaces import IEditForm, IAddForm
from zope import schema
from zope.interface import alsoProvides
from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
from plone.app.dexterity import MessageFactory as _
from plone.autoform.interfaces import IFormFieldProvider
from plone.autoform import directives as form
from plone.supermodel import model


options = SimpleVocabulary([
    SimpleTerm(value=True, title=_(u'Yes')),
    SimpleTerm(value=False, title=_(u'No')),
])


class IAllowDiscussion(model.Schema):

    model.fieldset(
        'settings',
        label=_(u"Settings"),
        fields=['allow_discussion'],
    )

    allow_discussion = schema.Choice(
        title=_(u'Allow discussion'),
        description=_(u'Allow discussion for this content object.'),
        vocabulary=options,
        required=False,
        default=None,