i need an apex trigger code if there is no child record for parent object Opportunity and the child object Service(Custom Object) it needs to create child record and the parent child relationship is masterdetial
for(Opportunity objOppt : [Select Id,(Select Id From Contacts__r) from Opportunity where Id IN :setOpptId]) { if(objOppt.Contacts__r.size() > 0) { //nothing } else { Contact objc = new Contact(LastName='Test', Oppt__c= objOppt.id); lstContactsTobeInserted.add(objc);
} }
insert lstContactsTobeInserted; }
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
thank naga but i need a trigger code to cross check whether the child record is existing for the existing parent record if the child is not existing needs to create child otherwise no
for(Opportunity objOppt : [Select Id,(Select Id From Contacts__r) from Opportunity where Id IN :setOpptId]) { if(objOppt.Contacts__r.size() > 0) { //nothing } else { Contact objc = new Contact(LastName='Test', Oppt__c= objOppt.id); lstContactsTobeInserted.add(objc);
} }
insert lstContactsTobeInserted; }
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
please refer the below code for same req:
I haev an opportunity and conatct is child of oppotyunity..I am checking if there is any child then do anything else insert one..
for(Opportunity objOppt : Trigger.New)
{
setOpptId.add(objOppt.Id);
}
for(Opportunity objOppt : [Select Id,(Select Id From Contacts__r) from Opportunity where Id IN :setOpptId])
{
if(objOppt.Contacts__r.size() > 0)
{
//nothing
}
else
{
Contact objc = new Contact(LastName='Test', Oppt__c= objOppt.id);
lstContactsTobeInserted.add(objc);
}
}
insert lstContactsTobeInserted;
}
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
Thanks,
Sandeep
Salesforce Certified Developer
All Answers
Please see a sample code which creates a child record.Please let me know if this helps.
please refer the below code for same req:
I haev an opportunity and conatct is child of oppotyunity..I am checking if there is any child then do anything else insert one..
for(Opportunity objOppt : Trigger.New)
{
setOpptId.add(objOppt.Id);
}
for(Opportunity objOppt : [Select Id,(Select Id From Contacts__r) from Opportunity where Id IN :setOpptId])
{
if(objOppt.Contacts__r.size() > 0)
{
//nothing
}
else
{
Contact objc = new Contact(LastName='Test', Oppt__c= objOppt.id);
lstContactsTobeInserted.add(objc);
}
}
insert lstContactsTobeInserted;
}
P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
Thanks,
Sandeep
Salesforce Certified Developer