Rolling your own rename after creation
In another tip we saw the built in AT flag for automatically renaming an object based on its title. When this flag is set, AT calls a method in BaseObject.py called _renameAfterCreation(), which does all of the hard work, including checking for duplicate ids, checking to see if the current id was generated by AT, committing a portal_factory subtransaction (discussed in another tip), and so on.
This is fine most of the time, but sometimes it isn't exactly what you want. For example, what if you want to generate the id from a combination of fields and not from the title alone (or at all)? Wouldn't it be nice to reuse the existing code?
Unfortunately _renameAfterCreation() assumes you want to use the title field for the id, and gets the title value by calling the method Title(). This might lead you to think of overriding the Title() method, but that isn't really what you want to do. Rather, you can play a trick on AT to make it do what you want.
The trick is to temporarily set the title to your generated value, call _renameAfterCreation(), then restore the title. Here's an example where the user can enter a long title and a short title. This code is called from the post-create script (discussed in another tip):
title = self.getField('title').get(self).strip()
shortTitle = self.getField('shortTitle').get(self).strip()
# If a short title was given, temporarily set the title
# to that so _renameAfterCreation() will work.
if shortTitle:
self.getField('title').set(self, shortTitle)
success = self._renameAfterCreation()
if success and shortTitle:
# The id was successfully changed,
# put the original title back
self.getField('title').set(self, title)
# We changed an indexed field, reindex
self.reindexObject()
