Monday, September 16, 2013

One to One relationship in Salesforce

Well, Salesforce offers  one to many relationship  and recently Many to Many relationship has 
also been possible using the concept of a Junction object...

But, is there a One to One relationship in Salesforce. Well, it is not available out of the Box.
But is definitely achievable using simple workflow rules...

Scenario:

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

Step 1:

Create a custom field on the Contact object. Make the field unique.
This field would be used to hold the ID of the associated Account.

Step 2:

Create a Workflow rule on Contact. Update the custom field with the value of the associated Account ID.

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.....

Thursday, August 1, 2013

Example for Difference between Trigger.new and Trigger.newMap in apex

trigger BeforeInsertTrigger on Account (before insert)
{ set<id> sid = new set<id>(); for(Account A :trigger.new) { 1.sid.add(A.Id);//No error but A.Id contains Null value. 2.system.debug('sid :'+sid);//output Null  
//This line of code i.e,( line number 3) would raise Null Pointer 
Exception becasue trigger.newMap dont work for before trigger 
while Sid will Contain all Ids of records. //If you are using after insert this trigger.newMap would return you the Objects Values in Acc.
3.Account Acc = trigger.newMap.get(A.Id); 4.system.debug('Acc :'+Acc); } }
Note : If you are setting event after insert then this will not raise error it will let you have all data with all Ids in Acc.
Account Acc = trigger.newMap.get(A.Id);
Now you have All record field value in Acc object.


KeyPoints

Trigger.new
 Returns a list of the new versions of the sObject records. Note that this sObject list is only available in   insert and update triggers, and the records can only be modified in before 
triggers.
Trigger.NewMap
A map of IDs to the new versions of the sObject records.Note that this map is only
available in before update, after insert, and after update triggers.
Note :   Trigger.newMap dont work for before insert while Trigger.New works fine for holding all Ids of records while inserting.According to the docs, Trigger.new returns a list, which are ordered, and Trigger.newMap returns a map - which are unordered. The docs specifically state you should not rely on the ordering of a map's elements.What to use depends on what you're doing - if you have an ID of an object you need to do something with, using the map makes more sense as you can use newMap.get(). Otherwise you'd have to loop over all the elements in Trigger.new and look for a matching ID. Similarly, if you have multiple loops over each item the trigger is operating on, the list returned by Trigger.new may be the better bet