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
sfdcianpsfdcianp 

limiting the promotions to three

i have promotion object as an related list in the campaign object.

i need to enter only 3 promotions for that campaign , if at all i am entering another promotion it chould throw an error

please suggest the way to do this...

thanks in advance
sfdcinap

Syed ishaqSyed ishaq
Trigger on promotion will help u in this regard.Here is the sample trigger hope it helps :
trigger createPromotion on Promotion(before insert){

for(Promotion p:Trigger.new){

// get all the promotions for a campaign

Integer pCount = [select id from promotion where campaignid =: p.campaignid].count();

if(pCount==3){
p.addError('Only 3 promotions can be added to the campaign');
}



}

}
Syed ishaqSyed ishaq
My bad i gave you the wrong syntax for the soql query . It is like this
Integer pCount = [select count() from promotion where campaignid=:p.campaignid];
swatKatswatKat

Syed ishaq , yes you can use a trigger. But the trigger has to be bulkified and you should never write a query in a for loop. You might cross the governor limits.

Can go through this link : http://wiki.developerforce.com/page/Apex_Code_Best_Practices

Syed ishaqSyed ishaq
yes you are right , i was trying to give the developer the approach rather than the spoon fed solution.
swatKatswatKat

The bulkified code can be desgined something like this. This is when you try to insert promotion records in bulk .

 

trigger createPromotion on Promotion(before insert){
        
    //set to contain all the campaign Ids
    Set<Id> setParentCampaignIds=new Set<Id>(); 
    for(Promotion p:trigger.New){
        //add the campaign Id 
        setParentCampaignIds.add(p.CampaignId);
    }
    //query all the campaigns and related promotions 
    Map<Id,Campaign> mapCampIdToCamp=[Select Id,(Select Id from Promotions__r) where Id in:setParentCampaignIds];
    for(Promotion p:trigger.New){
        // pick the parent campaign from the map
        Campaign c=mapCampIdToCamp.get(p.CampaignId);
        // check if the parent campaign already has 3 promotions
        if(c.Promotions__r.size()==3){
            //add error
            p.addError('Your Error Message');
        }      
    }
}