Search code examples
salesforceapex-code

Providing notifications to the current user from an Apex trigger in Salesforce


I'm trying to figure out a user friendly way to pass messages to users from my Apex code. I have a trigger which fires after insert/update of a lead, which then filters the list of updates and triggers a @future method which pushes the lead data out to an external web service and updates the converted account with some of the returned values.

I'd like to do the following (where X, Y and Z are any number of leads from 1 to 50)

  • notify the user converting the leads that leads X, Y and Z will be exported (I'll know this during the trigger execution).
  • notify the user whether the export succeeded or failed (which will be known for each of X, Y and Z when the @future method runs).

What is the recommended way to pass this information back to the user? I'd prefer not to use email (as this would trigger one email per record, which is pretty spammy and unpleasant). Is there another way to inject notification messages into a page? I've tried ApexPages.addMessage() but it doesn't seem to do anything for me (no error, but no notice either).


Solution

  • addMessage() works with both Visualforce pages and standard pages when there's a current page active, so using this in the trigger should work fine if the user is firing the action from a button / VF page. Using this won't work from your @future method however because it runs asynchronously in the background.

    Maybe the best solution would be to use a custom message object, which has a list of fields modified, when, and has a lookup to the appropriate user (or uses them as the owner). You could then create a simple VF page and controller which when viewed queries for records in that object related to the current user and provides an option to delete them (you could automatically delete them after pulling them from the DB but you run the risk of the user not actually noticing a message). You can then take this page and use it as part of a dashboard component, so anytime the user is viewing their Home page they could see a list of notifications.

    Finally another option might be making use of Chatter, pumping the messages to the user via that which will then also show up in digest emails etc..