+ Start a Discussion

Trigger to update contact associated with a user


I have portal users, chatter users and salesforce users.

When a user is created, I want a trigger that will check if the user is a portal user and then update the associated contact to show the contact has a portal account.  The contact object has a checkbox called "Portal_User__c" and I have put together the code below but I'm missing the section that updates the Contact field (shown below with the comment).  Can anyone suggest how I would update the contact?

trigger UpdateContactAsPortalUser on User (after insert, after update){

User uid =[select Contact from User where id=:UserInfo.getUserID()];

for (User newUser:Trigger.new){

if(uid.Contact !== null)

// Steps to set "Portal_User__c" field on Contact object to true

update uid;


Any assistance is appreciated.
Venkat PolisettiVenkat Polisetti
Try this:

trigger UpdateContactAsPortalUser on User (after insert, after update) {
Set<Id> contactIds = new Set<Id>();

for (User u : Trigger.new) {
  if (u.ContactId != null)

if (contactIds.size() > 0) {

  List<Contact> contacts = [select id, Portal_User__c from Contact where Id in :contactIds];

  for (Contact c : contacts) {
   c.Portal_User__c = true;

  update contacts;

Hi Venkat, thanks, that does exactly what I need when I activate the user.

The only thing I have noticed is that when I deactivate the user this locks the deactivate as "Updating records..." and it never finishes.  Could you advise how I'd update the above to clear Portal_User__c if the user is deactivated?

Hi Alanistic,

I am having the same problem!  Basically, we have a custom field that we want to update when the user is activated then update to a different selection when user is deactivated.  I am getting the same problem on the "Deactivate" side of things, just sticks on "Updating Records".

Any help would be appreciated!


Jeremy Stender

Rick HaagRick Haag
I know this is from years ago, but I thought I would respond anyway for users looking at this again.

I removed the "after update" and this resolved the portal user deactivation error (Mixed DML).

On the contact record I created two formula fields (boolean). One checks if there is a related portal user (NOT(ISBLANK(Contact.Portal_User__c). The other checks if the related User is active (Contact.Portal_User__r.IsActive).

The reason to keep the referenced portal user record on the contact after deactivation is to let us run a contact report on deactivated portal user.

Trigger SetUserOnContact on User (after insert) {
    List<Contact> userContacts = new List<Contact>();
    for (User u : trigger.new) {
        if (string.isNotBlank(u.ContactId)) {
            userContacts.add(new Contact(
                Id = u.ContactId,
                Portal_User__c = u.id));
    update userContacts;
Dependency - Custom Field on Contact: Portal User (Contact.Portal_User__c)