[SalesForce] Add a Portal/Community User in a Trigger

I'm toying with an idea of auto-activating (or deactivating) contacts for Communities/customer portal after certain criteria have been met on their contact records. It would look something like this (inefficient stub, for demonstration purposes):

  1. Go through Contacts in trigger, pulling list of contacts to activate/deactivate
  2. If there are contacts to activate/deactivate, query for any existing Portal users linked to these contact records. Activate/Deactivate accordingly (via IsActive) field.
  3. For any remaining contacts (who didn't match existing users), create & insert new portal user accounts.

My question is: would this work?

  • I know how to create portal users and manage their permissions in Apex
  • I also know that there are some API restrictions on creating/updating User records in the same transaction where you update other data
  • But I don't know if those limits apply to portal users, or in trigger contexts, or if there are ways to make it work anyway using @future calls or some other technique.

I can definitely explore this, but thought I'd ask here in case anyone has experience with this approach or whether it would work.

Best Answer

If your action is tripped by a DML on Contact, then you're mixing a DML operation of a non-setup object (Contact) with a setup object (User) and therefore you have to kick your trigger action to be handled by an @future method. There are no special limits here (other than apex trigger limits) as it applies to portal or communities context. Some things to consider though as you architect this code:

  • User context is lost in the @future method. That is to say, future methods run in system context. If you want to preserve something about the running user, you will need to pass it in as an argument to your future method.
  • How are you planning handle deactivated users attempting to login again? Ideally, the login page would surface a helpful message about why a user is deactivated, or you would handle reactivation in your registration handler class. Otherwise it could just be confusing for deactivated users attempting to login after a lapse.
Related Topic