I need to automatically create a customer portal (CP) user whenever a CP admin (ie, CP user with delegated external user admin rights) creates a contact in the CP.

The CP admin logs into the portal via a Force.com Site, so I've assumed the Site class instance will figure out this Site-CP association. But when I use the Site.createPortalUser() in my trigger, it throws this

System.TypeException: You are already logged in.

I use the Site class as I need to use the returned userId for other things, therefore I am unable to use @future method.

Any ideas? Here's short version of the trigger in question:

trigger CreateCPUser on Contact (before insert) {
    if (UserInfo.getUserType() == 'CustomerSuccess' || UserInfo.getUserType() == 'PowerCustomerSuccess') {
        for (Contact contact : Trigger.new) {
            // Instantiate a new user.
            User newuser = PortalUserUtility.createCPUser(contact);

            // Throws the error.
            String newuserId = Site.createPortalUser(newuser, contact.AccountId, null, true);

            // Need to use the returned User Id.            
            contact.Customer_Portal_User__c = newuser.Id; 

EDIT I understand the ability to add a user can be made available in the customer portal via the "Manage External User" button but unfortunately, the button is unwanted.


You can only call Site.createPortalUser from a site context. If you're in a trigger, you no longer have the site context.

If you're interested in creating customer portal users from contacts, check out the blog Provisioning Customer Portal Users with Apex

| improve this answer | |
  • This solution works great for creating users and without the use of Site class. However, the use of @future here prevents me from retrieving the ID of the user. – jmrjulian Aug 9 '13 at 20:56
  • what do you need the new user id for? Can your future method do what you need to do with the user id after it's created? The reason it doesn't return is that the user isn't created right away. – Ryan Guest Aug 9 '13 at 21:01
  • I need to populate the lookup field on the contact with the portal user. See last statement in the sample trigger above. – jmrjulian Aug 9 '13 at 21:07
  • @jmrjulian You can requery the userId in future method and populate and update the contact . – Mohith Shrivastava Aug 9 '13 at 22:40
  • The future method will fail as you can't mix DML operations on user and contact. – jmrjulian Aug 12 '13 at 20:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.