Daniel Hernández
Daniel Hernández

Reputation: 1317

How to execute actions after creating content types?

I'm trying to execute some arbitrary code after a Dexterity content type is created. For example the content type could represent a horse.

import logging
logger = logging.getLogger("Plone")

class IHorse(form.Schema):

    def __init__(self, context):
        logger.info('Creating horse')
        super(self).init(self, context)

I want to get the logger message "Creating horse" printed in the console when running the app in foreground. But the horse is created and I don't get messages for it. I guess that content type objects are created by the __init__, but maybe I'm in a mistake.

Upvotes: 6

Views: 216

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121306

You hooked into the __init__ for the schema of your content type. The schema is used as the basis for the fields populating your content, but it's not the content type class itself.

If you want to hook into content type creation, you register event subscribers instead:

from zope.app.container.interfaces import IObjectAddedEvent

@grok.subscribe(IHorse, IObjectAddedEvent)
def logHorseCreated(horse, event):
    logger.info('Created a horse')

If you really have to customize the content item initialization in an __init__ method, you'd have to create your own custom content class instead.

from plone.dexterity.content import Item

class Horse(Item):
    def __init__(self, id=None):
        super(Horse, self).__init__(id)

Upvotes: 7

Related Questions