Skip to content

Instantly share code, notes, and snippets.

@mhamzas
Created October 11, 2019 11:11
Show Gist options
  • Save mhamzas/4c48ae37a364d7f406e8b84931821967 to your computer and use it in GitHub Desktop.
Save mhamzas/4c48ae37a364d7f406e8b84931821967 to your computer and use it in GitHub Desktop.
Share file with Parent Record.
/*
*
* Author : M Hamza Siddiqui
* Description : Share file with Parent Record.
* Last Modified : Oct 1,2019
*
*/
trigger ParentFileSharing on ContentDocumentLink (before insert) {
List<ContentDocumentLink> linksToAdd = new List<ContentDocumentLink>();
Map<String,Set<String>> mapofObject = new Map<String,set<String>>();
Map<String,String> mapofAcc = new Map<String,String>();
system.debug(trigger.new.size());
for(ContentDocumentLink cdl:trigger.new){
if(cdl.LinkedEntityId !=null){
system.debug('LinkedId ::'+cdl.LinkedEntityId);
Id myId = cdl.LinkedEntityId;
Schema.SObjectType sobjectType = myId.getSObjectType();
String sobjectName = sobjectType.getDescribe().getName();
if(mapofObject.containsKey(sobjectname)){
Set<string> ids = mapofObject.get(sobjectname);
ids.add(myId);
mapofObject.put((String)sobjectname,ids);
} else {
Set<String> ids = new Set<String>();
ids.add(myId);
mapofObject.put((String)sobjectname,ids);
}
}
}
if(mapofObject != null){
for(String Objname : mapofObject.keySet()){
set<String> ids = new set<string>();
ids.addAll(mapofObject.get(Objname));
if(Objname=='Contact'){
String Query = 'Select Id,AccountId From ' + Objname + ' Where Id In :ids';
system.debug('Query=='+Query);
for(SObject record : Database.query(Query)){
mapofAcc.put((String)record.get('Id'),(String)record.get('AccountId'));
}
}
}
}
for(ContentDocumentLink cdl:trigger.new){
if (mapofAcc != null) {
// Sharing File with Account
linksToAdd.add(new ContentDocumentLink(ContentDocumentId=cdl.ContentDocumentId,
LinkedEntityId=mapofAcc.get(cdl.LinkedEntityId),
ShareType='C')
);
}
}
system.debug('size=='+linksToAdd.size());
// DML Operation
if(linksToAdd.size() != null)
insert linksToAdd;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment