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
devfredevfre 

Reg:Apex Trigger

I have to write apex trigger fore before insert operation... how to check the field values and add the field values in that trigger.. and if we are having the field values from two different object..

kiranmutturukiranmutturu

u need to query the reference object and get the values and compare....

devfredevfre

hi i'm new for the trigger.. could you please help me with some example? i want to check the picklist value of field of one object and if it is matching the criteria,then the other object's field's picklist value i should set.

kiranmutturukiranmutturu

sorry i didnt get u...

devfredevfre

i'm having two objects. object 1 is having the picklist field called x__c with values yes ,NO ... object2 is having the picklist field called y__c with values ab,bc,cd,ef.. in my trigger i used to use before insert operation and in that when the value of object1.X__c=NO then automatically the value of object2.y__c=level1.. how to write trigger for this?

LVSLVS

you need to tell us what the relation between object1 and object2 is

devfredevfre

object1 is parent and object 2 is child object

devfredevfre

sorry object2 is parent and object 1 is child

LVSLVS

You'll need to query the corresponding record of object2.

 

//begin trigger

//Getting object2 ids in a set

Set<Id> object2Ids = new Set<Id>();

for(Object1__c rec : trigger.new) {
    object2Ids.add(rec.object2__c);
}

Map<Id, Object2__c> mapOfObject2 = new Map<Id, Object2__c>();
mapOfObject2.addAll([SELECT y__c FROM Object2__c WHERE Id IN :object2Ids]);
List<Object2__c> listOfObject2ToUpdate = new List<Object2__c>();

for(Object1__c rec : trigger.new) {
    Object2__c obj2Rec = mapOfObject2.get(rec.object2__c);
    if(rec.x__c == 'NO') { //or whatever
        obj2Rec.y__c = 'Level1'; // or whatever
        listOfObject2ToUpdate.add(obj2Rec);
    }
}

Database.SaveResult[] results = Database.update(listOfObject2ToUpdate);

for(Database.SaveResult result : results) {
    if(!result.isSuccess()) {
        System.debug('error updating object2 rec. Msg:' + result.getError());
    }
}

 

//end trigger

 

Note: I'm assuming here that you're in the trigger for object1 (the child). Please try to give the details as clearly as possible in a single post.