You need to sign in to do that
Don't have an account?
ANAMIKA MONDAL 8
update the parent object
Hi All,
I am having a parent objcet Tree and its child object is Fruit. I need to update the Tree's status to Grown when all the fruits' status of the Tree is changed to Eatable.
Please help me with the trigger logic, or any releted example would help.
I am having a parent objcet Tree and its child object is Fruit. I need to update the Tree's status to Grown when all the fruits' status of the Tree is changed to Eatable.
Please help me with the trigger logic, or any releted example would help.
To Update the parent Object with Child Objects.please refer the below link for reference.
- https://salesforce.stackexchange.com/questions/67433/update-parent-object-with-child-objects
- https://salesforce.stackexchange.com/questions/150308/how-to-update-parent-field-using-trigger
Hope it will be helpful.Please mark it as best answer if the information is informative.so that question is removed from an unanswered question and appear as a proper solution.
Thanks
Rahul Kumar
First you have to write the trigger on the child (Fruit).
The events would be after insert, after update.
Well, the process goes like this.
1) When the child record is inserted/updated the trigger will get invoked.
2) Then you will implement a SOQL query through which you would get all chidrens of the Parent (Tree).
3) You will check whether all childrens status and you will update parent's status when every child's status matches your criteria.If any of child's status does ot match the criteria, the parents status will not get updated.
Example code:
Trigger Status_Changer on Fruit__c(after insert, after update){
if(Trigger.isafter && (Trigger.isInsert || Trigger.isUpdate)) {
//--------Calling the class-------------
StatusChanger.statusChangerMethod(Trigger.new);
}
//----------Class to be invoked------------------
Public class StatusChanger {
Set<Id> parentId = new Set<Id>();
Map<Id,List<Friut__c>> parentMap = new Map<Id,List<Fruit__c>>();
Integer s = 0;
Intgeger validator = 0;
static void statusChangerMethod(childValue) {
for(Fruit__c fruit : childValue) {
parentId.add(fruit.parent__c);--------//I am considering the lookup name of parent---------------
}
Tree__c tree = [select id, childRelationsgipName from Tree__c where id =: parentId];
if(parentMap.isEmpty()){
parentMap.put(tree.Id, new List<Fruit__c>(){tree.childRelationsgipName});
}
List<Fruit__c> fVal = new List<Fruit__c>();
fVal = parentMap.get(tree.Id);
validator = fVal.Size();
for(Fruit__c fruit : childValue) {
for(Id parentVal : parentMap.get(fruit.parent__c)){
for(Child__c childVal : parentVal) {
if(childVal.status == 'Eatable') {
s ++;
}
else {
s--;
}
}
}
}
if(s == validator ) {
Tree__c parentValue = new Tree__c (Id = tree.Id);
parentValue.status = 'Grown';
update parentValue;
}
}
}
static void statusChangerMethod(List<Fruit__c> childValue)