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
V AnandV Anand 

Trigger for update

I created a trigger for attachment .IF attachment is created on contact object  then create a document.  Document is created  easily. but when I updated attachment then these updates are not reflects to documents .


How do I perform updation.  insert trigger code is...

trigger doccon on attachment (after insert, after update) {
 folder f=[select id,name,type from folder where name='children' and type='document' limit 1];
 list<contact> con=[select id from contact]; 
     document doc= new document();
      for(attachment attach:[select name,body,parentid from attachment         where and parentid in :con]){
        insert doc;
    if(trigger.isUpdate){ me to update document.




Whoa there..


List<Contact> con = [select id from Contact];  will fetch every Contact in the database!


If you want to test that an Attachment was added to a Contact, you need to examine the value of attach.parentId. If the first three characters are '003', then it is a Contact. (Each Sobject has a unique 1st three characters in its ID field; SFDC out of the box SObjects 'id prefix' can be easily inspected by looking at any URL.  That said, best practice would be to use the Schema.Describe methods as those extend to custom objects and future proof you

V AnandV Anand

Thank you for  your suggestion. I definitely follow your suggestion..  could you please help me to do updation.


Ooh -- when the attachment is updated, you want to update the corresponding Document that was inserted when the attachment was originally inserted.


To do this, when the original Document is inserted, you will need to associate the Attachment Id to the Document Id; then this association can be used to locate the document for updating when the attachment is updated


Unfortunately, neither Attachment or Document SObject may have custom fields added. This leaves you only one good choice I can think of:


1> Create a new SObject AttachmentToDocument with two custom fields

* AttachmentId

* DocumentId


insert this Sobject in your trigger when you have inserted the Document

Query this object in your trigger when an attachment is updated in order to locate the corresponding Document


You of course, need to ensure your trigger is bulkified and that you don't do any SOQL calls inside of loops, nor do DML calls inside of loops.  Bulkification is discussed in detail in many places, notably and the excellent book Advanced Apex Programming by Dan Appleman



V AnandV Anand

Thank you crop I will try this............