Log in |
Adding ZClass Instances ProgrammaticallyIntroductionSo, you've got these shiny new ZClasses. They do just what you want, and you've added a bunch through the Zope management interface. Now, you need to make a method for adding new instances within DTML or Python code. (If you want to remove ZClass instances, you might want to check out removeZClasses ) Adding ZClass Instances via DTMLThe following ideas were taken from KM|Net News. My method for doing this involves a change to the ZClass constructor method (the one that is automatically created and ends with "_add"). The automatically generated "_add" method has a section at the end for redirecting the user to the proper space in the management interface. This is not desirable when you are adding an instance via code, so I've added a NoRedir flag. Here is what the last part of the "_add" method for the ZClass should look like: <dtml-if NoRedir> <dtml-else> <!--#if DestinationURL--> <!--#call "RESPONSE.redirect( DestinationURL+'/manage_workspace')"--> <!--#else--> <!--#call "RESPONSE.redirect( URL2+'/manage_workspace')"--> <!--#/if--> </dtml-if> Before adding the ZClass instance via DTML, you'll need to set up the REQUEST variable with any properties that you want the new instance to have. Be sure you set the ID of the new object up, like so: <dtml-call "REQUEST.set('id', 'newObId')"> Now, you just need to add the instance via DTML. The exact call you use will depend on where you're calling from. The simplest case is if you are adding a ZClass within a container ZClass. This case is simple, because the ZClass constructor and ZClass itself are within the namespace of the object you are adding the new instance to. All you need to do is add the following line to the DTML Method to add your instance: <dtml-call "YourZClass_add(_.None, _, NoRedir=1)"> The first two parameters (.None, ) are used to pass the current namespace into the function. You can read more about _ in the DTML Guide. If you are trying to add a ZClass instance from elsewhere in the ZODB, it's just a couple of lines more that are necessary: <dtml-with "manage_addProduct['YourProduct']"> <dtml-call "YourZClass_add(_.None, _, NoRedir=1)"> </dtml-with> Adding ZClass Instances via PythonThe following code was taken from a message by Brian Lloyd on the Zope list. I added the Control_Panel.Products.MyProduct part so that this external method will work from anywhere in the ZODB: def addAMyZClass(self, id, REQUEST=None): """ """ # Get the actual destination object, using the this() # method, to be sure we get it in the right context.. self=self.this() # Create the new instance newob=self.Control_Panel.Products.MyProduct.MyZClass(id) newob._setId(id) # Set properties based on the contents of the Add form newob.propertysheets.Basic.manage_changeProperties(REQUEST) # Add a new Folder to the new instance newob.manage_addFolder('foobar') # Add the new instance to the target object self._setObject(id, newob) return 'OK!' |