You need to sign in to do that
Don't have an account?

Question about after insert and before insert
Hi all,
My customer wants me to create a trigger fired on contact object, this trigger will create a relationship object related to this new created contact record and get some field values from contact. After inserting the contact object, I need to blank out three fields of this contact object and the relationship should get this contactId
My problem is, when I set this trigger before insert. The blank out code part works fine, but I cannot get the contactId in the relationship object for this trigger fired before insert.
And then I try to set the trigger after insert, it gives me some error message said that fields is read only, so I cannot get the fields to be blank out successfully.
Is there any way to meet both requirements ie. 1. Realtionship object should obtain the contactId 2. In the contact, field should be blank out.
I have highlight the parts which will cause some problems. Thanks in advance for any answer
trigger ContactRelationshipTrigger on Contact (before insert) {
for(Contact CON : Trigger.New){
//A new Relationships__c record will be created
Relationships__c relation = new Relationships__c();
//Make it related to the Account which name is in the List Owner
Account ac = [SELECT Id, Name FROM Account WHERE Name =: CON.List_Owner__c];
relation.List_Owner__c = ac.Id;
relation.Contact__c = CON.Id;
//Get the values in both List Id and opt-in of the contact record
relation.List_ID__c = CON.List_ID__C;
relation.List_Opt_In__c = CON.List_Opt_In__c;
insert relation;
CON.Relationship__c = relation.Id;
//Blank out the three string field in the Contact
CON.List_Owner__c = '';
CON.List_ID__c = '';
CON.List_Opt_In__c = '';
}
}
I think you'll need two triggers to do this correctly. Here's how it looks:
So, our first trigger creates the new relationships in an "after-insert" manner, which calls the second trigger, which then calls the frst trigger a second time, where we blank out the fields.
You could, of course, make this three triggers, but I rolled it into two for simplicity.
Also note that you can't put your query inside a for loop; you need to do the query outside the loop, and then inside the loop reference the results of the query.
All Answers
I think you'll need two triggers to do this correctly. Here's how it looks:
So, our first trigger creates the new relationships in an "after-insert" manner, which calls the second trigger, which then calls the frst trigger a second time, where we blank out the fields.
You could, of course, make this three triggers, but I rolled it into two for simplicity.
Also note that you can't put your query inside a for loop; you need to do the query outside the loop, and then inside the loop reference the results of the query.
Great!! Thanks a lot