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
❤Code❤Code 

restrict more than one child record in parent record

Hi All,

I have an object X__c. it is having a lookup field to itself XC__c. My requirement is , an user can insert only one child record. Simplifying one parent id should be used to one child record. If that parentid is used again or twice trigger should throw an error.

Regards
PratikPratik (Salesforce Developers) 
Hi ,

Try out the Unique field. You can capture the obejct record id in a field and set that field as Unique so it will not have the same value for 2 records and in turn 2 records with the same parent id will not be created.

You can refer to:
https://help.salesforce.com/HTViewHelpDoc?id=custom_field_attributes.htm&language=en_US (search for Uniqule)

Hope this will help!

Thanks,
Pratik
❤Code❤Code
Thanks Pratik,

Ca we have a trigger for this as we need to display custom error msg. Kindly let me know.
PratikPratik (Salesforce Developers) 
Hi ,

If you are goin for Unique field property, then you will be shown the existing record for the same value but not the custom error message. 

You can write a trigger as well to compare value. Here is the sample code (this code is basically identify the duplicate lead based on email same you can replicate for the parent id)
 
trigger duplead on lead(before insert,before update) {
List<contact> conlist =new list<contact>();
    for(lead l:trigger.new) {
    
    If(l.email!=null) 
    
   conlist = [select id from contact where email=:l.email];
    If (conlist.size()>0)
    l.adderror('Lead email duplicate with contact : ');      // custom error message
    
    
    }
        

}

Thanks,
Pratik

P.S. If this answers you question, please mark it as "Best Answer" so it will help other community members too.
ra811.3921220580267847E12ra811.3921220580267847E12
Hi,

trigger contactDemo on Contact( before insert,before update)
{
set<ID> ids= new set<ID>();
for(Contact c:trigger.new)
{
if(c.accountID!=null)
ids.add(c.accountID);

}


List<contact> cts1=[select id,name from contact where accountid in :ids];
System.debug('contacts are ======>'+cts1);
if((Trigger.isInsert &&cts1.size()>0)||(Trigger.isUpdate &&cts1.size()>1))
{
trigger.new[0].addError('duplicate');
}





}
Vishal NegandhiVishal Negandhi
If it's not about duplicacy and you just want to stick to one child per parent, then even a validation rule will do. 
For example, 
If for an Account, you only want one opportunity to be created. 
You can create a rollup field on Account to count number of Opportunities.
Now write a validation rule such that it throws an error if this rollup count is greater than 0.