Author Archives: Biswajeet

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

Salesforce Generic Sharing Record Using sObject

Sample Code:

//Create sharing object for the custom object Student
Schema.SObjectType stdShareType = Schema.getGlobalDescribe().get('Student__Share');
SObject stdShare = stdShareType.newSObject();
stdShare.put('ParentId', 'a0E0I00000fFSUBUA4'); //Set the ID of record being shared
stdShare.put('UserOrGroupId', UserInfo.getUserId()); //Set the ID of User or Group or Territory being granted access
stdShare.put('AccessLevel', 'Read'); //Set the Account access level
stdShare.put('RowCause', 'Student__c'); //Set the Row Cause reason
Database.SaveResult sr = Database.Insert(stdShare,false);

Salesforce Sharing Record Using Apex

For Custom Object:

//Create sharing object for the custom object Student
Student__Share studentShare  = new Student__Share();
studentShare.ParentId = recordId; //Set the ID of record being shared
studentShare.UserOrGroupId = userOrGroupId; //Set the ID of User or Group or Territory being granted access
studentShare.AccessLevel = 'Edit'; //Set the access level
Database.SaveResult sr = Database.Insert(studentShare,false);

For Standard Object:

//Create sharing object for the Standard object Account
AccountShare accshare = new AccountShare();
accshare.AccountId = accountId; //Set the Account ID of record being shared
accshare.UserOrGroupId = userOrGroupId; //Set the ID of User or Group or Territory being granted access
accshare.AccountAccessLevel = 'Edit'; //Set the Account access level
accshare.ContactAccessLevel = 'Edit'; //Set the Contact access level
accshare.OpportunityAccessLevel = 'Edit'; //Set the Opportunity access level
Database.SaveResult sr = Database.Insert(accshare,false);

Get All Objects and Its Fields in Salesforce Org

We can use Schema.getGlobalDescribe() to get all properties of sObject and its fields.

Apex Class:

public class SampleController {
    Public string selectedObj {get;set;}
    public String selectedField {get; set;}
    Public List<Selectoption> getObjList(){
        List<Schema.SObjectType> objList = Schema.getGlobalDescribe().Values();     
        List<SelectOption> objNames = new List<SelectOption>();
        objNames.add(new SelectOption('','-- Select --'));
        for(Schema.SObjectType obj : objList)
            objNames.add(new SelectOption(obj.getDescribe().getName(),obj.getDescribe().getLabel()));
        return objNames;
    public List<SelectOption> getObjectFields() {
        List<SelectOption> fieldNames = new List<SelectOption>();
        fieldNames.add(new SelectOption('','-- Select --'));
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
            Schema.SObjectType ObjSchema = schemaMap.get(selectedObj);
            Map<String, Schema.SObjectField> fieldMap = ObjSchema.getDescribe().fields.getMap();
            for (String fieldName: fieldMap.keySet()) 
                fieldNames.add(new SelectOption(fieldName, fieldMap.get(fieldName).getDescribe().getLabel()));
        return fieldNames;

Visualforce Page:

<apex:page controller="SampleController">
            <apex:pageBlockSection columns="2">
                <apex:pageBlockSectionItem >
                    <apex:outputlabel value="Object Names :"/> 
                    <apex:actionRegion >      
                        <apex:selectList value="{!selectedObj}" size="1">
                            <apex:selectOptions value="{!ObjList}"/>
                            <apex:actionSupport event="onchange" rerender="objFields"/>
                <apex:pageBlockSectionItem >
                    <apex:outputlabel value="Field Names :"/>   
                    <apex:outputPanel id="objFields">   
                        <apex:actionRegion >  
                            <apex:selectList value="{!selectedField}" size="1">
                                <apex:selectOptions value="{!ObjectFields}"/>


Test Class For Future Method

Future Method:

public class AccountHelper {
	public static void UpdateAccounts(List<Id> accountIds){
		//Get those records based on the IDs
		List<Account> accList = [SELECT Name FROM Account WHERE Id IN : accountIds];
		//Process records

Test Class:

public class TestAccountHelper {
    private static User CreateUser(){
        String orgId = UserInfo.getOrganizationId();
        String standardUserProfileId = [SELECT Id From Profile WHERE Name = 'Standard User'].Id;
        User u = new User(
            FirstName = 'Test',
            LastName = 'User',
            Alias = 'TestUser', 
            profileId = standardUserProfileId ,
            Email = orgId + '',
            Username = orgId + '',
            EmailEncodingKey = 'ISO-8859-1',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',  
            TimeZoneSidKey = 'America/Los_Angeles'
        insert u;
        return u;
    private static Account CreateAccount(){
        Account acc = new Account( Name = 'Test Account', 
                                  Type = 'Technology Partner', 
                                  Industry = 'Technology',
                                  Phone = '9898989898'
        insert acc;
        return acc;
    private static testMethod void testUpdateAccounts(){
        User u = CreateUser();
        System.runAs(u) {
            Account acc = CreateAccount();
            List<Id> accountIds = new List<Id>();
        //Verify account is inserted
        List<Account> accList = [SELECT Id From Account WHERE Name = 'Test Account'];
        System.assertEquals(1, accList.size());