Per Erik Strandberg /cv /kurser /blog

If you have not seen another tutorial on title less content types you might want to check this one out from plone.org by Jens W. Klein [1].

My goal with this tutorial is to create a content type that is a little different compared to your average content type. In short I want it to contain a file field and that the title should be generated as a function of the name of the file and some other values.

Schema

The schema looks like this:

schema = BaseSchema.copy() + Schema((
    FileField('File', required = 1,),

   StringField(name='Maturity', required=1,
        vocabulary=['Alpha (a)', 'Beta (b)', 'Stable (s)'],
        widget=SelectionWidget(label='Release Maturity',),
    ),

    IntegerField('Version', required = 1, ),
))

# the title can not be edited
schema['title'].required = 0
schema['title'].widget.visible = {'edit':'invisible', 'view': 'invisible'}

As you can see I have three fields in it, one for a file, one for the maturity of the file (if it is an alpha release and so on) and one for the version. The really interesting part is what follows after the schema definition: Here we hide the title and make it not required.

Class definition

A condensed version of the class definition is as follows:

class MyTitleLess(BaseContent):
    """An Archetype for MyTitleLess application"""

    schema = schema
    _at_rename_after_creation = True

    def setVersion(self, value):
        """When we set the version update title."""
        self.Schema()['Version'].set(self, value)

        filename = self.getField('File').get(self).filename

        # [...]

        new_title = "%s-%s%s%s" % (filestart, maturity, version, fileend)
        self.setTitle(new_title)

The thing to note is that there is a function called setVersion. This is a function generated by the some instance of the underlying framework (probably archetypes) and that sets the Version. The interesting dirty trick is to use it to actually not only set the version:

   self.Schema()['Version'].set(self, value)

but to also set the title:

    new_title = "%s-%s%s%s" % (filestart, maturity, version, fileend)
    self.setTitle(new_title)

My initial goal was to force the user to only have one item in the Plone site per unique combination of (filename, filematurity, fileversion) in each folder. But it turns out that I did not need that since the Id is incremented if a the user uploads the same thing twice.

Effects

If I now add two items in the same folder with the same filename, maturity and releasenumber I get something like on the below screenshot. It is allowed and the titles are indeed the same but the id of the second one is changed (the id is the part that makes the url I guess).
http://www.pererikstrandberg.se/blog/plone/mytitleless.png

Download

Download this little product here: [2]


Belongs in Kategori Programmering
See also Plone Cms