You need to sign in to do that
Don't have an account?

Record Sharing Through Apex Trigger
Hi All ,
I have an issue . Let me explain the problem.
I am sharing A custom object Record through before trigger . And the Object is OWD Private.
I am changing record owner as System Administrator who ever insert the record .
User u = [select Id from User where Profile.Name='System Administrator' Limit 1];
for(Project__c p : trigger.new){
p.ownerId = U.Id;
}
Now let say any of the user insert the Project__c records trigger will change the owner.
Once owner is change as System Admin. This user can not share this recod with other users because OWD is private.
The User who insert this record do not have privelage to share the record.
Now suggest me how to share these records in sigle trigger script.
Actually you are incorrect here.
Regardless of if the owner was changed or not, the trigger still runs in system context and without sharing. A class also operates without sharing by default.
You had something else going on that was not related to the sharing of the record through apex.
All Answers
You could use Apex sharing rules to give permission to access records to additional users/groups.
Take a look at the article below -
http://astreait.com/wordpress/?p=26
You should first investigate if the use of sharing rules would work in your situation. They are the prefered way to go and are eaiser to maintain. you can share to roles and / or groups as well as include people below those roles.
But, if that does not work, here is a basic example of adding a record to the object share. Make sure you set up Apex Sharing Reasons on the object to clarify whay someone has rights.
Hi Starz26 ,
Thanks for reply,
I have read your post but the problem is not which you trying to explain.
Once I change the record owner setting to System Admin. Then the user in which context the script is runnig lost the permission to share the record. So what I did ,
I create a class without sharing and migrate the whole trigger code in that class.
In this way I was handle to share the records.
Over all I was expecting that Once update the Record Owner then below this statement all script should run in context on System Admin because now only System Admin Can share that record.
Actually you are incorrect here.
Regardless of if the owner was changed or not, the trigger still runs in system context and without sharing. A class also operates without sharing by default.
You had something else going on that was not related to the sharing of the record through apex.
Thanks
Regards
Jeniffer (http://www.greatbasinindustrial.com/products/air-pollution-control/)
We can achieve it without writing apex code