function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DJ 367DJ 367 

Attachment mandatory on Task

Hello All,
Can someone plese help me writting a trigger so that whenever I save a task record it must insist me to add an attachment on task.

Thanks and regards,
Dj367

 
Best Answer chosen by DJ 367
GhanshyamChoudhariGhanshyamChoudhari
for(Task t : [SELECT Id,
        (SELECT Id FROM Attachments LIMIT 1)
        FROM Task
        WHERE Id IN : trigger.new]){
		if(t.Attachments.size()==0){
		t.addError('Attachment mandatory on Task');

		}
    }

 

All Answers

Raj VakatiRaj Vakati
https://salesforce.stackexchange.com/questions/27047/attachtment-required-to-create-a-task
Raj VakatiRaj Vakati
https://help.salesforce.com/articleView?id=000006460&type=1
DJ 367DJ 367
Hi Raj,

I tried this code 
trigger DocumentAttached on Task (before update) {
    // "after insert" won't work for sure. 
    // It's pretty much guaranteed to have 0 attachments there 
    // (well, unless you have other triggers but let's not go down that rabbit hole)
    // also - in "after" triggers you can't modify the original record directly, 
    // "before" is better for what you're trying to do

    for(Task t : [SELECT Id,
        (SELECT Id FROM Attachments LIMIT 1)
        FROM Task
        WHERE Id IN : trigger.new]){

        trigger.newMap(t.Id).Questionnaire_attached__c = !t.Attachments.isEmpty();
        // looks like black magic but should work ;)
    }
}

but I am not sure Questionnaire_attached__c  what this field is all about due to this I am getting error.​
GhanshyamChoudhariGhanshyamChoudhari
for(Task t : [SELECT Id,
        (SELECT Id FROM Attachments LIMIT 1)
        FROM Task
        WHERE Id IN : trigger.new]){
		if(t.Attachments.size()==0){
		t.addError('Attachment mandatory on Task');

		}
    }

 
This was selected as the best answer