In the below example Notification will be sent to the Account owner when the file is attached to their Account records.
Notification Type in Setup:
Sample Code:
trigger ContentDocumentLinkTrigger on ContentDocumentLink ( after insert ) {
Set < Id > setAccIds = new Set < Id >();
Map < Id, Id > mapAccIdContDocId = new Map < Id, Id >();
for ( ContentDocumentLink objCDL : trigger.new ) {
String strEntityId = objCDL.LinkedEntityId;
if ( String.isNotBlank( objCDL.LinkedEntityId ) && strEntityId.left( 3 ) == '001' ) {
setAccIds.add( objCDL.LinkedEntityId );
mapAccIdContDocId.put( objCDL.LinkedEntityId, objCDL.ContentDocumentId );
}
}
if ( setAccIds.size() > 0 ) {
CustomNotificationType notificationType = [SELECT Id FROM CustomNotificationType WHERE DeveloperName = 'Desktop'];
Messaging.CustomNotification notification = new Messaging.CustomNotification();
Set < String > recipientsIds = new Set < String >();
notification.setTitle( 'File Attached to your Account' );
notification.setNotificationTypeId( notificationType.Id );
for ( Account objAcc : [ SELECT Id, OwnerId FROM Account WHERE Id IN: setAccIds ] ) {
notification.setBody( 'File Id is ' + mapAccIdContDocId.get( objAcc.Id ) );
notification.setTargetId( objAcc.Id );
recipientsIds.add( objAcc.OwnerId );
notification.send( recipientsIds );
}
}
}
Output:
send() is not bulkified. So, remember 150 DML Governor limit.
https://trailblazer.salesforce.com/ideaView?id=0874V0000010y6zQAA