Wednesday, November 19, 2008

Using Plone's Title-to-id conversion in a script using an External Method

I tried to plug into Plone's title-to-id conversion machinery in a script which creates new objects. Unfortunately, due to restricted python, doing certain imports is not allowed. I fixed it using an external method. I placed the module "" my product's Extensions directory:

from zope.component import queryUtility
from plone.i18n.normalizer.interfaces import IIDNormalizer

def convertTitleToId(title):
"""Plug into plone's id-from-title machinery.
title = title.decode('utf-8')
newid = queryUtility(IIDNormalizer).normalize(title)
return newid

To my, i added a new method:

def installExternalMethod(portal, out, module, method, project, id=None):
Install external method
if not id:
id = method
print >> out, "Installing external method %s for %s" % (id, project)
if not id in portal.objectIds():
em = ExternalMethod(
title='%s(%s)' % (id, method),
module='%s.%s' % (project, module) ,
portal._setObject(id, em)

and i added
installExternalMethod(site, out, 'MyProductExternalMethods', 'convertTitleToId', PROJECTNAME)
to the postInstall method.

I might also have created a browser view which has this method, but i was not sure how to call that from a script, and curious if external methods still work in Plone 3. They do. I can now convert a title to an id in my script by doing
id = context.convertTitleToId(title)

2 comments: said...

Thanx for that snippet. It is exactly what I've been looking for.

Anonymous said...

You don't need to write an external method, if you are writing a simple python script TTW just use:

from Products.CMFPlone.utils import normalizeString