0

I am trying to write a trigger which will be triggered when an opportunity update event occurs. for that I have written an update event as below.

Opportunity o = [select Discount_Percent__c from Opportunity where Discount_Percent__c=11];
o.Discount_Percent__c=1;
update o;

And I have one custom object called "MyTest" with two field (Name & Approval Status). So I created a trigger as below.

trigger InsertNewRecordTOForTriggerPractice on Opportunity (after update) {    
    for(Opportunity objectOfOpp : trigger.new) {
        if(objectOfOpp.Id=='0067F000002tbN3') {
            MyTest__c mytest = new MyTest__c();
            mytest.Name='Mytestone';
            mytest.Approval_Status__c='Not Approved';
            insert mytest;
        } 
    }  
}

So for example, If i am trying to update an opportunity having record id 0067F000002tbN3, I am trying created new record for object "MyTest" inside Opportunity object with id=0067F000002tbN3.

The above trigger written is working fine, it is creating a MyTest record separately but not inside the Opportunity object. (I mean I want to insert new record into the that opportunity on which update event occurs).

Can anyone help me to solve my problem.

2
  • What do you mean by "inside the opportunity object"? Does you MyTest__c object have a look up field related to an Opportunity object? Does your Opportunity object has a lookup field related to your MyTest__c object? Jun 13, 2017 at 9:38
  • @MartinLezer sorry for not mentioning it mistakenly.. But yes,MyTest_c object have a look up field related to an opportunity object
    – Amit
    Jun 13, 2017 at 9:48

1 Answer 1

0

After referring some documents.I myself found a solution for this problem.

trigger InsertNewMyTestInsideOpp on Opportunity (after update) {  
    for(Opportunity objectOfOpp : trigger.new) {
            MyTest__c mytest = new MyTest__c();
            mytest.Name='Mytestseven';
            mytest.Opportunity__c=objectOfOpp.Id; // This is for lookup field 
            mytest.Approval_Status__c='Not Approved';
            insert mytest;
    }  
}

I think we dont need to check the Opportunity which is being updated/inserted using 'if' condition. Because 'trigger.new' stores the records which are currently in context of trigger, either being inserted or updated.

This solves my problem. Thank You !!!

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .