+ Start a Discussion
JaredPHJaredPH 

Help! Simple apex trigger for code-dummie

I have a lookup custom field "referrer" on the lead object. When a lead refers someone, we enter a new lead and enter the referrer lead into the lookup field of the new lead. (So, lead-to-lead lookup relationship). We have another custom lead field that is a date-time, called "discount". When a lead has 4 new lead records that list the lead in the "referrer" lookup field, I want to insert the current date and time into the discount field.

 

I'm useless with code. Do we need a number field and add 1 with each lead or is there a way to just do a lookup to see if there are 4 each time a new lead is entered? Is this a simple trigger that anyone would be able to help me out with?

 

Thanks in advance.

lovetolearnlovetolearn

Hi Jared, 

 

Lets assume that your first lookup fields is called "lookup_field1" and your second lookup field is called "lookup_field2" and so on and so forth. Here is the trigger: 

 

trigger testTrigger on Lead (before insert, before update) {
	for(Lead l: trigger.new){
		if(l.lookup_field1 != null && l.lookup_field2 != null && l.lookup_field3 != null && l.lookup_field4 != null ){
			datetime d = datetime.now();
			Discount = d;
		}
	}
}

 

Try it out let me know if it works. 

 

Thanks,

JaredPHJaredPH

Sorry I didn't do a great job describing. There is only one lookup field. When any lead has 4 leads in its related list for that lookup field, then I want to update the date-time field.

 

Example: Lead1 refers Lead2, Lead3, Lead4, Lead5. Leads 2-5 all get entered and have Lead1 in the lookup field. Since there are 4, I want the date-time field on Lead1 record to update to current date/time.

 

 

Alex.AcostaAlex.Acosta

Here's some sudo code I quickly wrote up on notepad.... You'll have to double check your variable names, but I'm pretty sure this will accomplish what you need.

trigger exampleTriggerTrigger on Lead (after insert, after update) {
	Set<Id> leadIds = new Set<Id>();
        // get all lookup lead ids
	for(Lead l: trigger.new){
		leadIds.add(l.Referrer__c);
	}
	
	// NOTE: I do not know your relationship variable name for nested queries here
	List<Lead> requeriedLeads = [SELECT Id,( SELECT Id FROM ReferrerLeads__r ) FROM Lead WHERE Id IN: leadIds];
	List<Lead> updateLeads = new List<Lead>();
	for(Lead l :requeriedLeads){
		if(null == lead.discount__c && null != l.ReferrerLeads__r && l.ReferrerLeads__r.size() >= 4){
			Lead lead = trigger.newMap.get(l.Id);
			lead.discount__c = system.now();
			updateLeads.add(lead);
		}
	}
	
	if(updateLeads.size() > 0)
		update updateLeads;
}

 

lovetolearnlovetolearn

Alex.Acosta wrote:

Here's some sudo code I quickly wrote up on notepad.... You'll have to double check your variable names, but I'm pretty sure this will accomplish what you need.

trigger exampleTriggerTrigger on Lead (before insert, before update) {
	Set<Id> leadIds = new Set<Id>();
        // get all lookup lead ids
	for(Lead l: trigger.new){
		leadIds.add(l.Referrer__c);
	}
	
	// NOTE: I do not know your relationship variable name for nested queries here
	List<Lead> requeriedLeads = [SELECT Id,( SELECT Id FROM ReferrerLeads__r ) FROM Lead WHERE Id IN: leadIds];
	List<Lead> updateLeads = new List<Lead>();
	for(Lead l :requeriedLeads){
		if(null != l.Referrer__r && l.size() >= 4){
			Lead lead = trigger.newMap.get(l.Id);
			lead.discount__c = system.now();
			updateLeads.add(lead);
		}
	}
	
	if(updateLeads.size() > 0)
		update updateLeads;
}

 


Hi mate, 

 

I think this will hit a DML error as DML operations are implicitly stated on before update and before insert. I think after insert and after update might work better in this istance. 

lovetolearnlovetolearn

JaredPH wrote:

Sorry I didn't do a great job describing. There is only one lookup field. When any lead has 4 leads in its related list for that lookup field, then I want to update the date-time field.

 

Example: Lead1 refers Lead2, Lead3, Lead4, Lead5. Leads 2-5 all get entered and have Lead1 in the lookup field. Since there are 4, I want the date-time field on Lead1 record to update to current date/time.

 

 


Ah okay. I misunderstood you. 

 

Try this:

 

trigger testTrigger on Lead (after insert, after update){
	List<Lead> leadList = new List<Lead>();
	for(Lead l : trigger.new){
		if(l.referrer != null){
			Lead le = [SELECT ID FROM Lead WHERE ID =: l.referrer];
			LIST<Lead> referredList = new List<Lead>([SELECT ID From Lead WHERE referrer =: le.ID]);
			if(referredList.size() = 4){
				le.discount = now();	
			}
		}leadList.add(le);
	}database.update(leadlist);
}

 

Alex.AcostaAlex.Acosta

Thanks, I've made the proper correct's on my original post. Again this was just sudo code i quickly wrote up on the fly, and I had copied the original trigger posted =). Only suggestions I can give to your trigger love is you may hit govenor limits wtih your nested query.

JaredPHJaredPH

Thanks for the help

 

It isn't liking this line:

 

if(referredList.size() = 4){

 

"Error: Expression cannot be assigned at ...."

 

Any ideas?

JaredPHJaredPH

Replaced = with >= and it took it. Looks like it works.

 

Thanks again!

Alex.AcostaAlex.Acosta

it's suppose to be 2 =.... so == is to compare. Just remember nesting queries within a loop can cause issues if you do mass updates. It's not bulk safe.

JaredPHJaredPH

One more thing...I messed with it and couldn't figure it out.

 

What would I add so that it doesn't update the discount field if the discount field already has a date/time in it i.e. is not null? Only run if discount field is null on lead le.

Alex.AcostaAlex.Acosta

on your if statement you add your criteria...

 

if((null == l.discount__c || '' == l.discount__c) && referredList.size() == 4){
JaredPHJaredPH

@Alex--Not bulk safe...does that mean if I try to mass update the referrer lookup field or if I try to mass update anything on leads?

Alex.AcostaAlex.Acosta

Yes, if you try to do mass updates / inserts, depending on the amount of records being modified / created you could hit a govenor limit. I suggest doing it the way I originally posted as it is bulk safe or any amount of record size.

 

http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_gov_limits.htm

JaredPHJaredPH

Thanks for the caution. How do I find the exact name of the lookup relationship?

Alex.AcostaAlex.Acosta

You go to your lookup field and click on the 'Field Label' so you can see the field details... within here you should see something parameter as 'Child Relationship Name'. This is your related field name. Just remember to append '__r' at the end of that name.

JaredPHJaredPH

Thanks again.

 

I put the trigger in and don't get any errors, but when I add 4 referral leads, it doesn't update the field. No errors, just not updating the discount field.

 

Any suggestions? Thanks so much for you time with this.

Alex.AcostaAlex.Acosta
I'll check it out tomorrow. Mind posting the code? Also if you'd like try doing system.debug(objectInstance); You may be able to figure it out before tomorrow when I can take a look at this Sent from my iPhone
JaredPHJaredPH

My bad. Somehow I unchecked the "active" box.

 

But...now that it is active, I am getting this error any time I try to update any lead:

 

Error:Apex trigger referfriend caused an unexpected exception, contact your administrator: referfriend: execution of AfterUpdate caused by: System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Lead.discount__c: Trigger.referfriend: line 10, column 1

 

Any suggestions? I'm not sure what is going on with that...

JaredPHJaredPH

If I take out the bit about having the discount field be null, then it gives me this error only on leads that have 4 referrals:

 

Apex trigger referfriend caused an unexpected exception, contact your administrator: referfriend: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.referfriend: line 12, column 1

Alex.AcostaAlex.Acosta

On line 10, please add your discount field to the query. The original error you posted was describing that the field was not queried for....

 

List<Lead> requeriedLeads = [SELECT Id, Discount__c,( SELECT Id FROM ReferrerLeads__r ) FROM Lead WHERE Id IN: leadIds];