0

I am working on a scenario of creating generic apex method of creating share records by using the recordId of an Object. I have a method which accepts recordId, userId, levelOfAccess and sharingReason and trying to create a sharing record after determining the sObjectType.

public static Boolean shareRecord(Id recordId, String userId, String levelOfAccess, String sharingReason)
{
    Boolean result = false;
    SObjectType sObjectType;
    String objName;
    if( recordId != null )
    {
        sObjectType = recordId.getSObjectType();
        objName = sObjectType.getDescribe().getName();
        if(!sObjectType.getDescribe().isCustom())
        {
            System.debug('Standard object'+objName);
            String shareObj = objName+share;
            shareObj so = new shareObj();//This line is not working!!
            so.ParentId = recordId;
            so.UserOrGroupId = userId;
            so.objectNameAccessLevel = levelOfAccess;
            so.RowCause = sharingReason;
            insert shareObj;
        }
        else
        {
            System.debug('Custom object'+objName);
            //Insert share record for custom object
        }
    }       
    return result;      
}

I am trying to figure out how to construct the share record variable dynamically and trying to insert it. Any help is appreciated.

Thanks.

1
  • P.S. one problem you'll run into is that AccountShare is specially unique, because it defines additional shares besides just the Account (and you can't not specify those levels). You may need to create versions that have different parameters or come up with some sort of solution using a Map or other collection type. – sfdcfox Jul 20 '20 at 4:37
1

You can't use a String as a type name directly. Instead, you must dynamically resolve the type using Type.forName(), and then create a new instance with newInstance():

sObject so = (sObject)Type.forName(shareObj).newInstance();

Note that since you will not have a concrete sObject instance, you'll have to use the put() method to populate fields.

The Type class is helpful reference documentation.

You have several other syntax errors in this code. The literal string share is not quoted correctly, and you do insert shareObj instead of insert so.

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.