Ads

Thursday 16 May 2013

How to create One to One relationship in Salesforce?

In Salesforce, we have One to Many relationship and Many to Many relationship.

To achieve One to One relationship in Salesforce, kindly follow the below steps

Objects: Interest, Employee.
Relationship: Interest is Master and Employee is Detail. 

1. Create a Roll up Summary field on Interest object to find the number of employees(Count).


2. Create a trigger in Employee object to check whether Number Of Employees is equal to one. If it is one, then throw an error, else allow the user to create.

Trigger:

trigger oneToOne on Employee__c (before insert, before update)
{
    for(Employee__c e : trigger.New)
    {
        String empId = e.Interest__c;
        Interest__c i = [SELECT Number_of_employees__c FROM Interest__c WHERE Id =: empId];
        Decimal empStrength = i.Number_Of_Employees__c;
        if(empStrength == 1)
        {
            e.addError('Already an employee has been associated with this interest');
        }
    }
}


Output:

No comments:

Post a Comment