Useful things I’ve learned about Plone this week: Archetypes for the lazy

This is the first in a forthcoming planned series of posts about useful things I’ve learned about Zope, Plone and Python. Hopefully, if I write them down I’ll be less likely to forget them and if I do, they’ll be easier to find rather than having to pick apart my code a few months down the line.

I’m kicking off with something I learned about creating new content types in Archetypes. The easiest way to do this is to subclass an existing type (e.g. Page, the basic out of the box ATContentType for a web page). With an ATContentType you get access to tools that let your content type integrate nicely into Plone. I’m all for saving time and effort in this area as I don’t believe in making unnecessary work for myself.

But, say your new content type doesn’t need a field which is required in the ATContentType you’re subclassing? When I was creating a new content type, subclassed from an ATDocument I realised after a while that I didn’t need the default “text” field — pretty much the whole point of an ATDocument — the field which holds the body content! My content type was reasonably complex but most of it was populated from dropdown lists, textareas and input boxes. Luckily, there is a way you can suppress these required fields.

After defining your schema, in the new class for your content type, override the parts of the base schema you no longer require:

schema = ATDocument.schema.copy() + Schema((

   StringField('myNewField',
      widget = StringWidget(label = 'My new string widget'),
   ),

))

class myContentType(ATDocument):
   schema = schema
   schema['text'].required = 0
   schema['text'].widget.visible = {"edit" : "invisible", "view" : "invisible"}
...

In our content type class we define schema as the schema we created earlier, and then we can turn some of the “out of the box” fields off. We set the text field’s mandatory status to off and then stop the editing widget for this appearing in edit mode. We also turn it off in view mode for good measure.

I accept this is probably a lazy way to create a new content type, but it works. Obviously you can use it with any field you wish to hide.

Tags: plone, web development.

Archives