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
Monin SavantMonin Savant 

Before creating attachment check if it doesn't exist

I am creating an attachment, but I want to check if it does not exist with the same name.
a = (Opportunity)standardPageController.getRecord();
 PageReference pdfPage = new PageReference('/apex/myPage');
        Opportunity b =[select Id, Name Invoice_Number__c from Opportunity where Id=:a.id];
        Blob pdfBlob;

Attachment attach = new Attachment(
        parentId = a.Id,
        Name = b.Name +'.pdf', 
        body = pdfBlob); //create the attachment object
        insert attach;

 
Best Answer chosen by Monin Savant
Maharajan CMaharajan C
Hi Monin,

I have added the parendId also in below query to filter the attachment based on Name and under particular opportunity... If you don't need the parentId check then remove the parentId in where condition.

List<Attachment> att = [ SELECT Name,ParentId FROM Attachment where Name =: existAttachname and parentId =: b.Id];

Please try the below code:
a = (Opportunity)standardPageController.getRecord();
 PageReference pdfPage = new PageReference('/apex/myPage');
        Opportunity b =[select Id, Name Invoice_Number__c from Opportunity where Id=:a.id];
        Blob pdfBlob;
        
String existAttachname =  b.Name + '.pdf';
List<Attachment> att = [ SELECT Name,ParentId FROM Attachment where Name =: existAttachname and parentId =: b.Id];

If(att.size() == 0){
    Attachment attach = new Attachment(
            parentId = a.Id,
            Name = b.Name +'.pdf', 
            body = pdfBlob); //create the attachment object
            insert attach;
}  

Thanks,
Maharajan.C