Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create and populate a Plone object in the portal_factory?

Tags:

plone

I need to create an (archetypes) object from a View of a second object (object2 - which is not the parent of the new object). It needs to be prepopulated with data from the Request, and from object2.

The simple solution would seem to be to use "default_method" on the schema fields, and that can work for the data from the Request, but I don't believe I have access to the View from there, and therefore not to object2, either. In any case, one of the fields is a ReferenceField to object2 and I've read that ReferenceField ignores "default_method".

The other option is to create it inside the portal_factory, set its defaults, and then display the Add page, allowing the user to modify the content as required, or to exit without actually creating the object. Perfect, except that, of the multitude of methods available to create an object, (invokeFactory(), _createObjectByType(), _constructInstance() & createObject(), that I know of), only createObject actually leaves the object in the portal_factory - and since it only returns a string (the URL of the object's Add page), won't accept keyword arguments, and doesn't seem to notify any events (certainly not IObjectCreatedEvent), I can't see how to modify that with my data before directing the user to the edit page.

like image 941
Auspex Avatar asked Feb 22 '23 13:02

Auspex


1 Answers

This is the pattern that I recommend when is not possible to use createObject:

_id = self.context.generateUniqueId("Document")
_id = self.context.invokeFactory(type_name=type_name, id=_id)
ob = self.context[_id]
ob.edit(
    description = "text...",
    subject     = ('tag1', 'tag2'),
    title       = "some title...",
)
ob._renameAfterCreation(check_auto_id=True)
_id = ob.getId()
like image 97
Tiberiu Ichim Avatar answered May 16 '23 06:05

Tiberiu Ichim