1

I have the following function that creates a share to a custom object:

public static Order_Request__Share generateOrderRequestShare(Id orderRequestID, Id userId, Boolean readOnly){
    System.debug('generateOrderRequestShare');
    Order_Request__Share shareTmp = new Order_Request__Share();
    if (!readOnly){
        shareTmp.AccessLevel = 'Edit';
    } else {
        shareTmp.AccessLevel = 'Read';
    }
    shareTmp.ParentId = orderRequestID;
    shareTmp.RowCause = 'Manual';
    shareTmp.UserOrGroupId = userId; 
    return shareTmp;
}

i want to do the same function, but for the object "SBQQ__Quote__Share", but i don't want to have the exact same function again. like this:

public static Order_Request__Share generateOrderRequestShare(Id orderRequestID, Id userId, Boolean readOnly){
    System.debug('generateOrderRequestShare');
    Order_Request__Share shareTmp = new Order_Request__Share();
    if (!readOnly){
        shareTmp.AccessLevel = 'Edit';
    } else {
        shareTmp.AccessLevel = 'Read';
    }
    shareTmp.ParentId = orderRequestID;
    shareTmp.RowCause = 'Manual';
    shareTmp.UserOrGroupId = userId; 
    return shareTmp;
}

public static SBQQ__Quote__Share generateQuoteShare(Id quoteId, Id userId, Boolean readOnly){
    SBQQ__Quote__Share shareTmp = new SBQQ__Quote__Share();
    if (!readOnly){
        shareTmp.AccessLevel = 'Edit';
    } else {
        shareTmp.AccessLevel = 'Read';
    }
    shareTmp.ParentId = quoteId;
    shareTmp.RowCause = 'Manual';
    shareTmp.UserOrGroupId = userId; 
    return shareTmp;
}

Is there a way i can create a generic function that will return a different object every time?

  • You can do it dynamically with getDescribe apex. Here is a sample code. Replace Account with your object. In the newAccount instance, you just need to do newObject.put('AccessLevel', 'Edit'); Schema.SObjectType objectType = Schema.getGlobalDescribe().get('Order_Request__Share'); SObject newObject = objectType.newSObject(); – Kevan Mar 3 at 16:00
  • 1
    @Kevan Comments really are not intended for answers; it would have been better to just add an answer. – sfdcfox Mar 3 at 16:03
1

Using the generic sObject type and the sobjecType classes, you can accomplish your goals. Here's an example:

public static sObject createShare(sObjectType shareType, Id parentId, Id userOrGroupId, Boolean readOnly) {
  sObject result = shareType.newSobject();
  result.put('AccessLevel', readOnly? 'Read': 'Edit');
  result.put('ParentId', parentId);
  result.put('UserOrGroupId', userOrGroupId);
  result.put('RowCause','Manual');
  return result;
}

Your method would be called slightly differently:

sObject shareRecord = createShare(SBQQ__Quote__Share.SobjectType, record.Id, someUser.Id, true);

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.