function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Using Profile Name in Apex

I am looking to execute some script (to add a user to a Chatter Group) when a user record is updated to any one of 10 profiles.


        if (u.Profile.Name.startsWith('BTLB') ){
            CollaborationGroupMember NewMember = new CollaborationGroupMember(MemberId = u.Id, CollaborationGroupId = '00ds0000001U9Ot');

 This compile ok, however when i try to edit the user record I get:

Apex trigger NewUserEntries caused an unexpected exception, contact your administrator: NewUserEntries: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.NewUserEntries: line 57, column 13

Line 57 is the if statement.


Is what i am trying to do possible?

I know i use profileId or a SOQL but don't really want to list the 10 possible ID and keep them updated whenever a new profiles is added.

Any help much appreciate.d

Ritesh AswaneyRitesh Aswaney

It would seem like the User reference u or the Profile might be Null ?

I would check 

if(u != null && u.Profile != null && u.Profile.Name.startswith('BTLB'))


I'm assuming that "u" was copied from What is probably happening is that the objects in are not fully populated. You will need to load the objects from the database directly to get the profile name field to be populated. Like this:


SELECT Id, Profile.Name FROM User WHERE Id IN : trigger.newMap.keySet()



Thanks guys, was posting only the section to simplify it but seems to have added consuion.

u. is from the trigger and suspect that the SOQL call is required.

Thanks for you input