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
HelloSanHelloSan 

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

Best Answer chosen by HelloSan
sandeep sankhlasandeep sankhla
Hi HelloSan,

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

NagaNaga (Salesforce Developers) 
Hi HelloSan,

Please see a sample code which creates a child record.Please let me know if this helps.

User-added image
HelloSanHelloSan
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
sandeep sankhlasandeep sankhla
Hi HelloSan,

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 
This was selected as the best answer