Quantcast
Channel: Salesforce Online Training
Viewing all articles
Browse latest Browse all 84

How to Notify When Attachment Added to Custom Object?

$
0
0

Question

You want to send an email notification whenever an attachment is uploaded to a custom object in Salesforce. Attachments in Salesforce are now represented as ContentDocument records, and their relationship to other records is managed through ContentDocumentLink objects.

The challenge lies in correctly identifying when an attachment is associated with your custom object because the LinkedEntityId field in the ContentDocumentLink object does not always directly reference the custom object.

Behavior of ContentDocumentLink

When a file is uploaded to a record, Salesforce creates two ContentDocumentLink records:

  1. One for the user who uploaded the file. This link references the user object in the LinkedEntityId field.
  2. One for the record to which the file was uploaded. This link references the target record (e.g., your custom object) in the LinkedEntityId field.

Because both records are created, your trigger will fire twice. Therefore, you need to filter out the irrelevant record (the one referencing the user) and process only the link related to your custom object.

The Solution

You can achieve this using a trigger on the ContentDocumentLink object. The goal is to check the type of record referenced by the LinkedEntityId field and process only those that match your custom object. Below is the detailed code and explanation:

Trigger Code Example

trigger ContentAttachmentTrigger on ContentDocumentLink (after insert) {
    // Sets to store relevant IDs
    Set<Id> customObjectIds = new Set<Id>();
    Set<Id> contentDocumentIds = new Set<Id>();

    // Iterate over new ContentDocumentLink records
    for (ContentDocumentLink cdl : Trigger.new) {
        // Check the type of record being linked (LinkedEntityId)
        Schema.sObjectType objectType = cdl.LinkedEntityId.getSObjectType();

        // Process only links related to the custom object
        if (objectType == Custom_Object__c.sObjectType) {
            customObjectIds.add(cdl.LinkedEntityId);  // ID of the custom object
            contentDocumentIds.add(cdl.ContentDocumentId);  // ID of the file
        }
    }

    // If relevant links are found, process them
    if (!customObjectIds.isEmpty()) {
        // Fetch additional details for the email (if required)
        List<Custom_Object__c> customObjects = [
            SELECT Id, Name, Owner.Email
            FROM Custom_Object__c
            WHERE Id IN :customObjectIds
        ];

        List<ContentDocument> attachedFiles = [
            SELECT Id, Title, FileType
            FROM ContentDocument
            WHERE Id IN :contentDocumentIds
        ];

        // Send email notifications
        for (Custom_Object__c obj : customObjects) {
            // Construct and send an email (example using Messaging.SingleEmailMessage)
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            email.setToAddresses(new String[] {obj.Owner.Email});
            email.setSubject('New Attachment Added');
            email.setPlainTextBody('A new file has been attached to the record: ' + obj.Name);
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
    }
}

Explanation of Code

  1. Trigger on ContentDocumentLink:
    The trigger fires after a file is uploaded to a record. It processes the ContentDocumentLink object, which represents the relationship between a file and the record it is attached to.
  2. Identify Relevant Records:
    Use the LinkedEntityId.getSObjectType() method to determine the type of record linked. Only process records where the linked entity is your custom object.
  3. Collect IDs for Processing:
    Store the LinkedEntityId (custom object) and ContentDocumentId (file) in sets to fetch additional details for the email notification.
  4. Query Related Records:
    Fetch details of the custom object and the uploaded file to include relevant information in the email notification.
  5. Send Email Notifications:
    Use Messaging.SingleEmailMessage to construct and send an email to the record owner (or any other recipients). Customize the email content to suit your requirements.

Why Not Trigger on the Custom Object?

Placing a trigger directly on the custom object will not work in this scenario. Attaching a file does not trigger any change in the custom object itself, so the trigger will not fire. This is why the ContentDocumentLink object is the correct place to implement your logic.

Alternative Solutions

Salesforce Flow
Use a Flow triggered on the ContentDocumentLink object. Filter the records to include only those where LinkedEntityId is of type Custom_Object__c. You can then send an email notification using the Send Email action in Flow.

Apex Batch Processing
If the volume of uploads is large, you can use an Apex Batch process to periodically scan for new ContentDocumentLink records and send notifications. This approach can help manage governor limits in high-volume environments.

Platform Event or Pub/Sub Model
Publish a platform event when a file is attached, and have a subscriber handle the email notification. This is a more advanced design pattern and is suitable for complex integrations.

Considerations

  1. Governor Limits: Ensure that your trigger logic handles bulk operations effectively. Avoid querying or performing DML operations inside loops. Use collections like sets and lists to minimize resource usage.
  2. Security: Verify that users have the necessary permissions to access ContentDocumentLink and related records, as missing permissions can cause runtime errors.
  3. Testing: Write comprehensive test cases to cover various scenarios, such as files being uploaded to other objects, bulk uploads, and edge cases.

Summing Up

To notify when an attachment is added to a custom object in Salesforce, use a trigger on the ContentDocumentLink object. This object manages relationships between files and records. When a file is uploaded, two ContentDocumentLink records are created—one for the user and one for the target record.

The trigger filters records using LinkedEntityId.getSObjectType() to process only links related to the custom object. After identifying relevant records, query details about the custom object and the attached file. Use Messaging.SingleEmailMessage to send notifications to appropriate recipients, such as the record owner.

Alternative solutions include Salesforce Flow, batch processing for high volumes, or a platform event-based approach. Ensure proper handling of governor limits, security, and testing to implement this effectively.

Job-Oriented Salesforce Course: Enroll for Free Demo

Our Salesforce Course is designed to equip you with a solid foundation and advanced skills needed to thrive in the Salesforce ecosystem. Covering key areas such as Salesforce Admin, Developer, and AI modules, our course offers a perfect blend of theoretical knowledge and hands-on experience. With a focus on real-time project scenarios, you’ll gain practical expertise that directly applies to the challenges faced by businesses today. Our expert instructors guide you through each step, ensuring you’re well-prepared for both certification and real-world implementation.

In addition to technical proficiency, our Salesforce training in Pune provides personalized mentorship and tailored interview preparation to help you excel in the competitive job market. You’ll receive access to detailed class notes, practical assignments, and one-on-one support throughout the program. By the end of the training, you’ll be equipped not only with the skills to succeed in Salesforce roles but also with the confidence and insights needed to advance your career. Join us and take the first step toward mastering Salesforce and unlocking new career opportunities!

The post How to Notify When Attachment Added to Custom Object? appeared first on Salesforce Online Training.


Viewing all articles
Browse latest Browse all 84

Trending Articles