Question

I'm writing a content type like the this with Dexterity:

class IArticle(form.Schema):

    title = schema.TextLine(
        title=_(u"Name"),
    )

    code = schema.TextLine(
        title=_(u"Code"),
    )

If some user creates a new article setting "foo" as title and "bar" as code, the title will be "foo" and the article URL will be ".../foo". How can I get that the content URL be ".../bar"?

Was it helpful?

Solution

What you want to do is influence the name chooser, and you can do that with a custom behavior for your interface.

Subclassing the INameForTitle interface is the easiest:

from plone.app.content.interfaces import INameFromTitle
from zope import interface, component

from ..types.interfaces import IArticle


class INameFromCode(INameFromTitle):
    pass

class ArticleCodeAsTitle(object):
    component.adapts(IArticle)
    interface.implements(INameFromCode)

    def __init__(self, context):
        self.context = context

    @property
    def title(self):
        return self.context.code

The default name chooser tries to adapt the new-to-be-added object to the INameForTitle interface, then if that succeeds, will use the .title attribute to build a new name for the object. By implementing a subclass of that interface as an adapter for your IArticle objects, you get to substitute the title for your .code field instead, thus making sure that that is used for new names instead.

Register this as:

<configure
    xmlns="http://namespaces.zope.org/zope"
    xmlns:plone="http://namespaces.plone.org/plone"
    i18n_domain="your.i18n.domain"
    >

<plone:behavior
    title="ArticleCode"
    description="Use .code as the title when choosing a new object name"
    provides=".articlecode.INameFromCode"
    factory=".articlecode.ArticleCodeAsTitle"
    for="..types.interfaces.IArticle"
    />

</configure>

and add this behavior to your Article type definition instead of the INameFromTitle behavior.

OTHER TIPS

Create a custom behavior to set the object id to the code attribute value:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top