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
Shyam Sundar 84Shyam Sundar 84 

Help me on Apex Trigger

how to assign parent role ID based on hierarchy when ever the record created on contact. (i.e) The owner ID should be the superior level role 
Mehul TyagiMehul Tyagi
I  am not sure if i understand your problem correctly.
Firstly if you want make owner field editable or changing owner filed then you need permission to do it.
One way to do this is to configure the user's profile to "Transfer Records"

To fetch the Parent User Id you can use SOQL Query-

Id currentUserId= UserInfo.getUserId();
List<User> roleId=[SELECT RoleId FROM User WHERE Id=currentUserId];
List<UserRole> parentRoleList=[SELECT ParentRoleId FROM UserRole WHERE Id=roleId[0].RoleId];
List<User> parentUserId=[SELECT Id FROM User WHERE RoleId=parentRoleList[0].ParentRoleId];
Id parentId=parentUserId[0].Id

You can now assign parentId to ownerId of your contact record .
Shyam Sundar 84Shyam Sundar 84
hi mehul,

actually i ll explain my scenario once again...

An external agent acting as an user from commmunity cloud.  agent creating a lead from community cloud once the record save the owner id should gets assigned to the superior user as per hierarchy.

sill agent is not given roles.. call center agent and sales manager are assigned to roles... 

SM is the superior person the call center agent
 
Shyam Sundar 84Shyam Sundar 84
Need a full  trigger with syntax.. i dont know to create one @Mehul Tyagi
Shyam Sundar 84Shyam Sundar 84
trigger assignuser on Contact (before insert) {
 
  Id currentUserId= UserInfo.getUserId();
  List<User> roleId=[SELECT RoleId FROM User WHERE Id=currentUserId];
  List<UserRole> parentRoleList=[SELECT ParentRoleId FROM UserRole WHERE Id=roleId[0].RoleId];
  List<User> parentUserId=[SELECT Id FROM User WHERE RoleId=parentRoleList[0].ParentRoleId];
  Id parentId=parentUserId[0].Id
  
for(Contact c:Trigger.new){
 
if(c.OwnerId == null)
{
 
  c.OwnerId= parentId;
  }
  }
  }


check this is this correct?