Search code examples
pythontrac

Trac plugin - set field value using ticket id at ticket creation


Premise: my tickets have a custom field recipe that should contain a link to a wiki page named after the ticket id. For example Ticket #1 should have the recipe set to [wiki:TicketRecipe_1], Ticket #1234 should have [wiki:TicketRecipe_1234] and so forth.

Since I want that link to be automatically populated at ticket creation/modify I built a very simple plugin, based on the ITicketManipulator entry point.

from trac.core import Component, implements
from trac.ticket.api import ITicketManipulator


class WikiLinkPopulator(Component):
    implements(ITicketManipulator)

    def prepare_ticket(self, req, ticket, fields, actions):
        pass

    def validate_ticket(self, req, ticket):

        wikilink = "[wiki:TicketRecipe_%s]" % (ticket.id)
        if ticket['recipe_link'] != wikilink:
            ticket['recipe_link'] = wikilink

        return []

This works when I modify an existing ticket, but when I create a new one the result is [wiki:TicketRecipe_None]. Maybe it's because the ticket id/number is still unknown when the entry point is called?

Is there a way to have the value also set at ticket creation?


Solution

  • You could implement ITicketChangeListener. The following plugin should work with Trac 1.0+:

    from trac.core import Component, implements
    from trac.ticket.api import ITicketChangeListener
    
    class WikiLinkPopulator(Component):
        implements(ITicketChangeListener)
    
        def ticket_created(self, ticket):
            wikilink = "[wiki:TicketRecipe_%s]" % (ticket.id)
            self.env.db_transaction("""
                UPDATE ticket_custom SET value=%s WHERE name=%s AND ticket=%s
                """, (wikilink, 'recipe_link', ticket.id))
    
        def ticket_changed(self, ticket, comment, author, old_values):
            pass
    
        def ticket_deleted(self, ticket):
            pass
    
        def ticket_comment_modified(self, ticket, cdate, author, comment, old_comment):
            pass
    
        def ticket_change_deleted(self, ticket, cdate, changes):
            pass
    
        def prepare_ticket(self, req, ticket, fields, actions):
            pass