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)
{
accountIds.add(contactVar.AccountId);
}
list<Contact> contactList=[select id,name from Contact where AccountId in :accountIds];
for(Contact conVar:trigger.new)
{
if(contactList.size()>=1)
conVar.addError('Only one child is allowed ');
}
}
If it solves your problem, please let me know. Best Regards, Dayakar
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.
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
If it solves your problem, please let me know.
Best Regards,
Dayakar
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.
https://developer.salesforce.com/forums/?id=906F0000000AfsKIAS
Hope this helps you!
Best Regards,
Jyothsna