+ Start a Discussion
santhosh konathala 8santhosh konathala 8 

How can we achieve only one child to one parent using a trigger

Hi sonthosh,

Here I am taking an example of account and contact as a parent and child.
and below is the trigger code to stop inserting more than one child to a parent
trigger OnlyOnechild on Contact (before insert) {
    public set<id> accountIds=new set<id>();
    for(Contact contactVar:trigger.new)
    list<Contact> contactList=[select id,name from Contact where AccountId in :accountIds];
    for(Contact conVar:trigger.new)
        	conVar.addError('Only one child is allowed ');


If it solves your problem, please let me know.
Best Regards,
JyothsnaJyothsna (Salesforce Developers) 
Hi Santhosh,

You can achecive this functionality by using one-to-one relationship.

Let's consider the scenario that we would like to establish a One-to-One relationship between Accounts and Contacts.

Step 1:

create a master-detail relationship and than on master create a roll-up summary field of child with count. then you write validation on rule rollup summary field to check for >1 .
 so it will give you error if it has more than one record for same master detail relation values.

Step 2:

i. Create a lookup field on the child
ii. Create a unique field on the child, and hide this field from all page layouts
iii. Write a workflow, for any change of the lookup field, to copy that value from the lookup field into the unique field

Done!! you have established a one to one relationship between Account and Contacts...

When you try to add a second contact to the Account, the "unique" constraint would be violated and an error would be thrown.

Please check the below link for related posts.

Hope this helps you!
Best Regards,