• DaGunster
  • NEWBIE
  • 0 Points
  • Member since 2008

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 13
    Questions
  • 13
    Replies
I have a trigger that works perfect in development. It's been done for about 1 week now.

I cannot get it deployed because I cannot build the test.

Hey, I've asked for help from this forum and no help - that worked
I've poured over every scrap of documentation.

I found an example and went back to it.
This time, I'm going to make a package out of your example
So here goes ...
This is all from your documentation.
First - the Trigger
Second - the Class.
Your documentation says this is what you need.
I made a trigger and compiled it - ok.
I made the class and compiled it - ok.
Went to make a package so I can get this into  P R O D U C T I ON   -   and FAILURE !!!!!!!!!!!!!!

From your PDF - The_World's_First_On-Demand_Programming_Language


The Trigger:

trigger blockDuplicates_tgr on Lead bulk(before insert, before update) {
/*
* begin by building a map which stores the (unique) list of leads
* being inserted/updated, using email address as the key.
*/
Map<String, Lead> leadMap = new Map<String, Lead>();
for (Lead lead : System.Trigger.new) {
if (lead.Email != null) { // skip null emails
/* for inserts OR
* updates where the email address is changing
* check to see if the email is a duplicate of another in
* this batch, if unique, add this lead to the leadMap
*/
if ( System.Trigger.isInsert ||
(System.Trigger.isUpdate &&
lead.Email != System.Trigger.oldMap.get(lead.Id).Email)) {

if (leadMap.containsKey(lead.Email)) {
lead.Email.addError('Another new lead has the same email address.');
} else {
leadMap.put(lead.Email, lead);
}
}
}
}

/* Using the lead map, make a single database query,
* find all the leads in the database that have the same email address as
* any of the leads being inserted/updated.
*/
for (Lead lead : [select Email from Lead where Email IN :leadMap.KeySet()]) {
Lead newLead = leadMap.get(lead.Email);
newLead.Email.addError('A lead with this email address already exists.');
}
}


 Now : The Test Class.

public class testBlockDuplicatesLeadTrigger {

static testMethod void testDuplicateTrigger(){

Lead[] l1 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
insert l1; // add a known lead

Lead[] l2 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
// try to add a matching lead
try { insert l2; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}

// test duplicates in the same batch
Lead[] l3 =new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' ),
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
try { insert l3; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Another new lead has the same email'),
e.getMessage());

}

// test update also
Lead[] lup = new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
insert lup;
Lead marge = [ select id,Email from lead where Email = 'marge@fox.tv' limit 1];
system.assert(marge!=null);
marge.Email = 'homer@fox.tv';

try { update marge; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('irst error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}
}


}

  AGAIN : the above compiled.
CREATE PACKAGE

With the two items above saving correctly, let's create a package.
Create a new unmanaged package and add the two items above.
Click 'upload'.

 oops

- - - Here is what it says

There are problems that prevent this package from being uploaded.

  
Item TypeNameProblem
Apex ClassLink: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, blockDuplicates: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.blockDuplicates: line 14, column 32
Class.testBlockDuplicatesLeadTrigger.testDuplicateTrigger: line 6, column 9




    HELLO - HOUSTON - WE HAVE A PROBLEM.  Your own example doesn't work !!!!!!!!!!!!!!!!!!!!!!

    I have spent the last 3-4 weekends on SalesForce. I've been working on this thing overtime about 3 nights a week.
    Without getting our trigger up into production - I WILL report to my management that Salesforce is a FAILURE.

    We are a LARGE account. My suggestion to executive level is
    (1) You write the test for free, or
    (2) You allow the trigger to work without a test, or
    (3) We cancel the Purchase order and look at other CRM products.

    We have called our account executive who put us in touch with a 'specialist'.

   The specialist said that you don't even use tests anymore !

    Something is going to give here.

    Can you at LEAST make your example work so that I have SOMETHING to go by.

    Time and Date: Saturday, April 19, 2008 at 4:30pm
  
WITHOUT A DEPLOYMENT OF THE ALREADY SUCCESSFULLY DEVELOPED TRIGGER - THIS DEPLOYMENT OF SALESFORCE IS A FAILURE.

Will you at least get your example to work?  What are we going to do.

Monday, I go to my managment and raise big alarms and declare a failure.
I have a trigger that works perfect in development. It's been done for about 1 week now.

I cannot get it deployed because I cannot build the test.

Hey, I've asked for help from this forum and no help - that worked
I've poured over every scrap of documentation.

I found an example and went back to it.
This time, I'm going to make a package out of your example
So here goes ...
This is all from your documentation.
First - the Trigger
Second - the Class.
Your documentation says this is what you need.
I made a trigger and compiled it - ok.
I made the class and compiled it - ok.
Went to make a package so I can get this into  P R O D U C T I ON   -   and FAILURE !!!!!!!!!!!!!!

From your PDF - The_World's_First_On-Demand_Programming_Language


The Trigger:

trigger blockDuplicates_tgr on Lead bulk(before insert, before update) {
/*
* begin by building a map which stores the (unique) list of leads
* being inserted/updated, using email address as the key.
*/
Map<String, Lead> leadMap = new Map<String, Lead>();
for (Lead lead : System.Trigger.new) {
if (lead.Email != null) { // skip null emails
/* for inserts OR
* updates where the email address is changing
* check to see if the email is a duplicate of another in
* this batch, if unique, add this lead to the leadMap
*/
if ( System.Trigger.isInsert ||
(System.Trigger.isUpdate &&
lead.Email != System.Trigger.oldMap.get(lead.Id).Email)) {

if (leadMap.containsKey(lead.Email)) {
lead.Email.addError('Another new lead has the same email address.');
} else {
leadMap.put(lead.Email, lead);
}
}
}
}

/* Using the lead map, make a single database query,
* find all the leads in the database that have the same email address as
* any of the leads being inserted/updated.
*/
for (Lead lead : [select Email from Lead where Email IN :leadMap.KeySet()]) {
Lead newLead = leadMap.get(lead.Email);
newLead.Email.addError('A lead with this email address already exists.');
}
}


 Now : The Test Class.

public class testBlockDuplicatesLeadTrigger {

static testMethod void testDuplicateTrigger(){

Lead[] l1 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
insert l1; // add a known lead

Lead[] l2 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
// try to add a matching lead
try { insert l2; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}

// test duplicates in the same batch
Lead[] l3 =new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' ),
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
try { insert l3; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Another new lead has the same email'),
e.getMessage());

}

// test update also
Lead[] lup = new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
insert lup;
Lead marge = [ select id,Email from lead where Email = 'marge@fox.tv' limit 1];
system.assert(marge!=null);
marge.Email = 'homer@fox.tv';

try { update marge; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('irst error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}
}


}

  AGAIN : the above compiled.
CREATE PACKAGE

With the two items above saving correctly, let's create a package.
Create a new unmanaged package and add the two items above.
Click 'upload'.

 oops

- - - Here is what it says

There are problems that prevent this package from being uploaded.

  
Item TypeNameProblem
Apex ClasstestBlockDuplicatesLeadTrigger.testDuplicateTrigger()System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, blockDuplicates: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.blockDuplicates: line 14, column 32
Class.testBlockDuplicatesLeadTrigger.testDuplicateTrigger: line 6, column 9




    HELLO - HOUSTON - WE HAVE A PROBLEM.  Your own example doesn't work !!!!!!!!!!!!!!!!!!!!!!

    I have spent the last 3-4 weekends on SalesForce. I've been working on this thing overtime about 3 nights a week.
    Without getting our trigger up into production - I WILL report to my management that Salesforce is a FAILURE.

    We are a LARGE account. My suggestion to executive level is
    (1) You write the test for free, or
    (2) You allow the trigger to work without a test, or
    (3) We cancel the Purchase order and look at other CRM products.

    We have called our account executive who put us in touch with a 'specialist'.

   The specialist said that you don't even use tests anymore !

    Something is going to give here.

    Can you at LEAST make your example work so that I have SOMETHING to go by.

    Time and Date: Saturday, April 19, 2008 at 4:30pm
  
WITHOUT A DEPLOYMENT OF THE ALREADY SUCCESSFULLY DEVELOPED TRIGGER - THIS DEPLOYMENT OF SALESFORCE IS A FAILURE.

Will you at least get your example to work?  What are we going to do.

Monday, I go to my managment and raise big alarms and declare a failure.




It was okay to write Apex in a trigger. Yes, the manual says it's 'better' to write the code in a class.
But this is my first Apex.
 
So ... how do I put a test onto a trigger?
 
 
Pardon me please. I am just totally perplexed about the testing. It's required , but hardly explained.  Here is my code.
 
What and how should the test be done so I can get this deployed today !
 
trigger MakeRouteEvents on Account (before insert, before update)
{
// Create routes for FAR's based on choices in Accounts.
// DECLARATIONS: OLD VALUES IN RECORD vs NEW VALUES IN RECORD.
Account[] oldRecords; // GET THE OLD VALUES
Account[] newRecords; // GET THE NEW VALUES
// DECLARATIONS: CONVERSIONS FROM THE FORM TO DATATYPES NEEDED BY EVENT.
Date VisitStartDate; // From Form: Date from date picker
String strVisitStartDate; // Visit Start Date - just date portion - converted to a string.
DateTime finalVisitStartDate; // This is the one written to the field 'RecurrenceStartDateTime'
String strVisitTime; // The time of day from the VISIT TIME picklist
String strDuration; // Duration of visit from Picklist
Integer intDuration; // Duration of site visit in minutes - converted to Integer
String strFrequency; // How often should the visit occur - form Picklist
Integer intFrequency; // How often should the visit occur - converted to integer.
String strVisitDayOfWeek; // Visit day of week, from Picklist.
Integer intVisitDayOfWeek; // Visit day of week, Mon, Tues: converted to Integer
//DateTime timeOfVisit; // converted to time for the Event table.
// DECLARATIONS: OTHER VARIABLES NEEDED BY EVENT
String strAccountId; // From Screen. Get The Account Id
String strUserId; // From API.
String strUserTimeZone; // From User Table. NEEDED BY EVENT.
Event[] existingEvents; // From User Table GET EXISTING ROUTE EVENTS FOR ACCOUNT SO WE CAN DELETE THEM.
// =================================================================
// START PROCESSING
// =================================================================
// GET THE OLD RECORD VALUES AND THE NEW RECORD VALUES
oldRecords = Trigger.old; // old trigger has old record values
newRecords= Trigger.new; // new trigger has new record values
Boolean WorkToDo; // Flag indicates if we have work to do, yes or no.
// DO WE HAVE ANYTHING TO DO?
WorkToDo = FALSE;
if (oldRecords[0].Visit_Start_Date__c != newRecords[0].Visit_Start_Date__c){WorkToDo = TRUE;}
else if (oldRecords[0].Visit_Day_of_Wk__c != newRecords[0].Visit_Day_of_Wk__c){WorkToDo = TRUE;}
else if (oldRecords[0].Visit_Time__c != newRecords[0].Visit_Time__c){WorkToDo = TRUE;}
else if (oldRecords[0].Visit_Wk__c != newRecords[0].Visit_Wk__c){WorkToDo = TRUE;}
else if (oldRecords[0].Visit_Wk_Freq__c != newRecords[0].Visit_Wk_Freq__c){WorkToDo = TRUE;}

// WHAT WOULD CAUSE US TO NOT WANT TO WORK?
if (newRecords[0].Visit_Start_Date__c == null) {WorkToDo = FALSE;}
System.debug('Work To do ' + WorkToDo);
if (WorkTodo)
{
// SCRAPE THE FORM AND SET VARIABLE VALUES
strAccountId = newRecords[0].Id; // Account
VisitStartDate = newRecords[0].Visit_Start_Date__c; // Visit Starting Date
strVisitTime = newRecords[0].Visit_Time__c;
strFrequency = newRecords[0].Visit_Wk_Freq__c; // Frequency
strDuration = newRecords[0].Visit_Duration__c; // Duration of Visit
strVisitDayOfWeek = newRecords[0].Visit_Day_of_Wk__c;
//CONVERT VISIT DAY OF WEEK TO RECURRENCE DAY OF WEEK MASK
System.debug('Day Of Week ' + strVisitDayOfWeek);
if (strVisitDayOfWeek == 'Sunday') {intVisitDayOfWeek = 1;}
else if (strVisitDayOfWeek == 'Monday') {intVisitDayOfWeek = 2;}
else if (strVisitDayOfWeek == 'Tuesday') {intVisitDayOfWeek = 4;}
else if (strVisitDayOfWeek == 'Wednesday') {intVisitDayOfWeek = 8;}
else if (strVisitDayOfWeek == 'Thursday') {intVisitDayOfWeek = 16;}
else if (strVisitDayOfWeek == 'Friday') {intVisitDayOfWeek = 32;}
else if (strVisitDayOfWeek == 'Saturday') {intVisitDayOfWeek = 64;}
// CONVERT DURATION OF VISIT FROM STRING TO INTEGER
if (strDuration == '15 Minutes') {intDuration = 15;}
else if (strDuration == '30 Minutes') {intDuration = 30;}
else if (strDuration == '45 Minutes') {intDuration = 45;}
else if (strDuration == '60 Minutes') {intDuration = 60;}
// CONVERT THE RECURRENCE INTERVAL FROM STRING TO INTEGER.
System.debug('strFrequency ' + strFrequency);
if (strFrequency == 'Weekly') {intFrequency = 1;}
else if (strFrequency == 'Two Weeks') {intFrequency = 2;}
else if (strFrequency == 'Three Weeks') {intFrequency = 3;}
else if (strFrequency == 'Four Weeks') {intFrequency = 4;}
else if (strFrequency == 'Six Weeks') {intFrequency = 6;}
else if (strFrequency == 'Eight Weeks') {intFrequency = 8;}
// CONVERT TIME OF DAY FROM STRING TO DATE
if (strVisitTime == '7:00 AM') {strVisitTime = '07:00';}
else if (strVisitTime == '7:30 AM') {strVisitTime = '07:30:00';}
else if (strVisitTime == '8:00 AM') {strVisitTime = '08:00:00';}
else if (strVisitTime == '8:30 AM') {strVisitTime = '08:30:00';}
else if (strVisitTime == '9:00 AM') {strVisitTime = '09:00:00';}
else if (strVisitTime == '9:30 AM') {strVisitTime = '09:30:00';}
else if (strVisitTime == '10:00 AM') {strVisitTime = '10:00:00';}
else if (strVisitTime == '10:30 AM') {strVisitTime = '10:30:00';}
else if (strVisitTime == '11:00 AM') {strVisitTime = '11:00:00';}
else if (strVisitTime == '11:30 AM') {strVisitTime = '11:30:00';}
else if (strVisitTime == '12 NOON') {strVisitTime = '12:00:00';}
else if (strVisitTime == '12:30 PM') {strVisitTime = '12:30:00';}
else if (strVisitTime == '1:00 PM') {strVisitTime = '13:00:00';}
else if (strVisitTime == '1:30 PM') {strVisitTime = '13:30:00';}
else if (strVisitTime == '2:00 PM') {strVisitTime = '14:00:00';}
else if (strVisitTime == '2:30 PM') {strVisitTime = '14:30:00';}
else if (strVisitTime == '3:00 PM') {strVisitTime = '15:00:00';}
else if (strVisitTime == '3:30 PM') {strVisitTime = '15:30:00';}
else if (strVisitTime == '4:00 PM') {strVisitTime = '16:00:00';}
else if (strVisitTime == '4:30 PM') {strVisitTime = '16:30:00';}
else if (strVisitTime == '5:00 PM') {strVisitTime = '17:00:00';}
else if (strVisitTime == '5:30 PM') {strVisitTime = '17:30:00';}
else if (strVisitTime == '6:00 PM') {strVisitTime = '18:00:00';}
// GET THE USER TIMEZONE
strUserId = UserInfo.getUserId(); // First, get the User ID
//System.debug('User Id is ' + strUserId);
strUserTimeZone = [SELECT TimeZoneSidKey from User where Id = :strUserId][0].TimeZoneSidKey;
//System.debug('Time Zone is ' + strUserTimeZone);
// ASSEMBLE DATES
System.debug('Now ' + System.Now());
System.debug('First Event Date is ' + VisitStartDate);
//System.debug(' Visit Start Date ' + newRecords[0].Visit_Start_Date__c);
strVisitStartDate = String.valueOf(VisitStartDate).substring(0,10); // get date portion, not time portion
System.debug('strVisitTime ' + strVisitTime);
strVisitStartDate = strVisitStartDate + ' ' + strVisitTime;
system.debug('strVisitStartDate ' + strvisitStartDate);
finalVisitStartDate = DateTime.valueOf(strVisitStartDate);
//strVisitStartDate = String.valueOf(VisitStartDate); // get date portion, not time portion
// EVERYTHING IS SET SO DROP EXISTING EVENTS AND CREATE NEW SCHEDULE OF EVENTS
existingEvents = [select Id, AccountId, isRecurrence from Event where AccountId = :strAccountId and isRecurrence = TRUE];
delete existingEvents;
Event newEvent = new Event
(
WhatId = strAccountId,
Subject = 'Route',
Location = 'On-Site',
Description = 'Scheduled Route Site Visit',
ShowAs = 'Busy',
IsReminderSet = FALSE,
IsRecurrence = TRUE,
DurationInMinutes = intDuration,
ActivityDate = date.today(),
ActivityDateTime = System.now(),
RecurrenceDayOfWeekMask = intVisitDayOfWeek,
RecurrenceInterval = intFrequency,
RecurrenceType = 'RecursWeekly',
//RecurrenceStartDateTime = strVisitStartDate,
RecurrenceStartDateTime = finalVisitStartDate,
RecurrenceEndDateOnly = Date.valueOf('2009-03-30'),
RecurrenceTimeZoneSidKey = strUserTimeZone
//ActivityDateTime = '9pm'
);
insert newEvent;

}

}
Is there any example of this... any demonstration of what the tests are to accomplish?
 
My app is done. Ready to go. Deployable.
 
There are a few paragraphs in the developer guide ...
 
I've got my code in a trigger.
 
I open a recordset (trigger)
 
I write a few records to the recordset (trigger).
 
What am I supposed to test?
 
 
Don't need anything big - maybe a message box?

I see where S-controls do visuals - but I'm doing all this back-end.
Apparently, internally, some calculations are made based on the values of this field.

I am not seeing where these values are.

Instead of my going through all the permutations - can you show me where these values are published, I'm not seeing it.

thanks.
I'm programmatically building events for our sales staff.

I'm getting records to write but have a few questions I'll be posing.

In the front end - the user would enter something like  - 9am -  and Salesforce swallows it.

Is the function that converts the - 9am - into a date available in code?

Any suggestion on converting such a time?
Get an error on this ...

newEvent.AccountId = '0017000000NB5vCAAT';

I need to write new events with Apex. I'll need to set the AccountId to which the event is related.

I get an error : Error: Compile Error: Field is not writeable: AccountId at line 51 column 5

What can I do to write an AccountId to the AccountId field in Event?
Here is the trigger...

Scroll down to ...// TRY DELETING CONTACTS
This works.
The next two lines try to delete Events.
These fail.
The account # came from Apex Explorer and I know is correct.
don't worry about all the 'weird' lines in this - it's just a copy and paste from the code window in SF.

***
*** I need to be able to delete events and recurring events given an Account ID. ***
***

trigger MakeRouteEvents on Account (before insert, before update)
{

// Trigger events
// before insert, before update, before delete, after insert
// after update, after delete, after undelete

// Trigger Context Variables
// isExecuting, isInsert, isUpdate, isUpdate, isDelete, isBefore
// isAfter, isUndelete, new, newMap, old, oldMap, size

Integer i;
Account[] oldRecords;
Account[] newRecords;
Lead newLead; // testing
Lead[] deleteLeads;
Event[] existingEvents;
String strAccountId;
Contact[] existingContacts;

if (Trigger.isInsert)
System.debug('An Insert Trigger');
else
System.debug('Not Insert Trigger');


strAccountId = '0017000000NB5vCAAT';

// this block works
//newLead = new Lead(lastname = 'FryZZ', company='FryZZ And Sons');
//insert newLead;

// this block works also
//deleteLeads = [select id, name from lead where company= 'Jackson Controls'];
//try
// {delete deleteLeads;}
//catch (DmlException e)
// {
// Process exception here
// }

// TRY DELETING CONTACTS
existingContacts = [select Id, AccountId from Contact where AccountId = '0017000000NB5vCAAT'];
delete existingContacts;

//existingEvents = [select Id, AccountId from Event where AccountId = :strAccountId];
existingEvents = [select Id, AccountId from Event where AccountId = '0017000000NB5vCAAT'];
delete existingEvents;





i=5;
//sqlContact = "select lastname from contact where accountid in";
//resultContact = [ :Trigger.new];

//CustomerRouting.DropCustomerRouteEvents();


oldRecords = Trigger.old;
newRecords= Trigger.new;

System.debug(oldRecords[0].Number_of_Units__c);
System.debug(newRecords[0].Number_of_Units__c);

}
I am not seeing where Profiles can be imported.  Is there a way?
Good Day.
 
I did an extract of the 'Accounts' utulizing Apex Data Loader.
 
Then I went to the SalesForceFieldsReference.PDF
 
The fields do not match up.
 
Where can I get an accurate reference of the fields to import and export?
 
Thanks.
I have a trigger that works perfect in development. It's been done for about 1 week now.

I cannot get it deployed because I cannot build the test.

Hey, I've asked for help from this forum and no help - that worked
I've poured over every scrap of documentation.

I found an example and went back to it.
This time, I'm going to make a package out of your example
So here goes ...
This is all from your documentation.
First - the Trigger
Second - the Class.
Your documentation says this is what you need.
I made a trigger and compiled it - ok.
I made the class and compiled it - ok.
Went to make a package so I can get this into  P R O D U C T I ON   -   and FAILURE !!!!!!!!!!!!!!

From your PDF - The_World's_First_On-Demand_Programming_Language


The Trigger:

trigger blockDuplicates_tgr on Lead bulk(before insert, before update) {
/*
* begin by building a map which stores the (unique) list of leads
* being inserted/updated, using email address as the key.
*/
Map<String, Lead> leadMap = new Map<String, Lead>();
for (Lead lead : System.Trigger.new) {
if (lead.Email != null) { // skip null emails
/* for inserts OR
* updates where the email address is changing
* check to see if the email is a duplicate of another in
* this batch, if unique, add this lead to the leadMap
*/
if ( System.Trigger.isInsert ||
(System.Trigger.isUpdate &&
lead.Email != System.Trigger.oldMap.get(lead.Id).Email)) {

if (leadMap.containsKey(lead.Email)) {
lead.Email.addError('Another new lead has the same email address.');
} else {
leadMap.put(lead.Email, lead);
}
}
}
}

/* Using the lead map, make a single database query,
* find all the leads in the database that have the same email address as
* any of the leads being inserted/updated.
*/
for (Lead lead : [select Email from Lead where Email IN :leadMap.KeySet()]) {
Lead newLead = leadMap.get(lead.Email);
newLead.Email.addError('A lead with this email address already exists.');
}
}


 Now : The Test Class.

public class testBlockDuplicatesLeadTrigger {

static testMethod void testDuplicateTrigger(){

Lead[] l1 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
insert l1; // add a known lead

Lead[] l2 =new Lead[]{
new Lead( Email='homer@fox.tv', LastName='Simpson', Company='fox' )
};
// try to add a matching lead
try { insert l2; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}

// test duplicates in the same batch
Lead[] l3 =new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' ),
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
try { insert l3; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Another new lead has the same email'),
e.getMessage());

}

// test update also
Lead[] lup = new Lead[]{
new Lead( Email='marge@fox.tv', LastName='Simpson', Company='fox' )
};
insert lup;
Lead marge = [ select id,Email from lead where Email = 'marge@fox.tv' limit 1];
system.assert(marge!=null);
marge.Email = 'homer@fox.tv';

try { update marge; } catch ( System.DmlException e) {
system.assert(e.getMessage().contains('irst error: FIELD_CUSTOM_VALIDATION_EXCEPTION, A lead with this email address already exists'),
e.getMessage());
}
}


}

  AGAIN : the above compiled.
CREATE PACKAGE

With the two items above saving correctly, let's create a package.
Create a new unmanaged package and add the two items above.
Click 'upload'.

 oops

- - - Here is what it says

There are problems that prevent this package from being uploaded.

  
Item TypeNameProblem
Apex ClasstestBlockDuplicatesLeadTrigger.testDuplicateTrigger()System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, blockDuplicates: execution of BeforeInsert

caused by: System.NullPointerException: Attempt to de-reference a null object

Trigger.blockDuplicates: line 14, column 32
Class.testBlockDuplicatesLeadTrigger.testDuplicateTrigger: line 6, column 9




    HELLO - HOUSTON - WE HAVE A PROBLEM.  Your own example doesn't work !!!!!!!!!!!!!!!!!!!!!!

    I have spent the last 3-4 weekends on SalesForce. I've been working on this thing overtime about 3 nights a week.
    Without getting our trigger up into production - I WILL report to my management that Salesforce is a FAILURE.

    We are a LARGE account. My suggestion to executive level is
    (1) You write the test for free, or
    (2) You allow the trigger to work without a test, or
    (3) We cancel the Purchase order and look at other CRM products.

    We have called our account executive who put us in touch with a 'specialist'.

   The specialist said that you don't even use tests anymore !

    Something is going to give here.

    Can you at LEAST make your example work so that I have SOMETHING to go by.

    Time and Date: Saturday, April 19, 2008 at 4:30pm
  
WITHOUT A DEPLOYMENT OF THE ALREADY SUCCESSFULLY DEVELOPED TRIGGER - THIS DEPLOYMENT OF SALESFORCE IS A FAILURE.

Will you at least get your example to work?  What are we going to do.

Monday, I go to my managment and raise big alarms and declare a failure.




Hello.

I have had nothing but trouble deploying/updating/activating triggers in EE (no problem in DE).  I check the forums and found many people saying the same thing.  However I assume than most people are able to deploy/run triggers in EE without a problem?  Please respond if you're able to reliably work with Apex in EE.

Thanks
Chris


  • April 15, 2008
  • Like
  • 0
 
Hi everyone. I'm still very new at writing triggers. I've had a few succesful ones. We have one trigger that is firing on a custom object and updates two fields pulled via SoQL from its related object. The code below works well but only updates 1 record when using the dataloader.
 
 
Code:
trigger Product_Contact_Roles_Phone_Email on Product_Contact_Role__c (before insert, before update) {
 
 //Set Contact_Email__c  to Email
 //Set Contact_Phone__c to Phone 
 
  //This should set a variable to an identifier 
 String ContactID = Trigger.new[0].Contact__c;
 
    
 Contact p = [SELECT Phone FROM Contact WHERE contact.id = :ContactID limit 1]; 
 Contact e = [SELECT Email FROM Contact WHERE contact.id = :ContactID limit 1]; 
  //For the Item that's update the field Phone__C value is set to the varible defined above
  
  Trigger.new[0].Contact_Phone__C = p.Phone;
  Trigger.new[0].Contact_Email__C = e.Email;
So I updated the code to loop through the Trigger.new. This works, but once I get more than 10 records being updated I reach the limit. I think I can use a map to grab all the Phone and E-mails from the related contact IDs of items in Trigger.new and then use a for to loop through all Ids from Trigger.new to update from the Map. But 1. I'm not sure if this would work and 2. if it would not quite sure how to build it. Here's the trigger that's breaking the limit:
Code:
for (Integer i = 0; i < Trigger.new.size(); i++) { 
 Contact p = [SELECT Phone FROM Contact WHERE contact.id = :ContactID limit 1]; 
 Contact E = [SELECT Email FROM Contact WHERE contact.id = :ContactID limit 1]; 
 Trigger.new[i].Contact_Phone__C = p.Phone;
 Trigger.new[i].Contact_Email__C = e.Email; 
}

 Help Suggestions greatly appreciative. If anyone has a good resources that gives me examples of similar triggers that would be fantastic learning tool for me. Thank you!

 
Apparently, internally, some calculations are made based on the values of this field.

I am not seeing where these values are.

Instead of my going through all the permutations - can you show me where these values are published, I'm not seeing it.

thanks.
Here is the trigger...

Scroll down to ...// TRY DELETING CONTACTS
This works.
The next two lines try to delete Events.
These fail.
The account # came from Apex Explorer and I know is correct.
don't worry about all the 'weird' lines in this - it's just a copy and paste from the code window in SF.

***
*** I need to be able to delete events and recurring events given an Account ID. ***
***

trigger MakeRouteEvents on Account (before insert, before update)
{

// Trigger events
// before insert, before update, before delete, after insert
// after update, after delete, after undelete

// Trigger Context Variables
// isExecuting, isInsert, isUpdate, isUpdate, isDelete, isBefore
// isAfter, isUndelete, new, newMap, old, oldMap, size

Integer i;
Account[] oldRecords;
Account[] newRecords;
Lead newLead; // testing
Lead[] deleteLeads;
Event[] existingEvents;
String strAccountId;
Contact[] existingContacts;

if (Trigger.isInsert)
System.debug('An Insert Trigger');
else
System.debug('Not Insert Trigger');


strAccountId = '0017000000NB5vCAAT';

// this block works
//newLead = new Lead(lastname = 'FryZZ', company='FryZZ And Sons');
//insert newLead;

// this block works also
//deleteLeads = [select id, name from lead where company= 'Jackson Controls'];
//try
// {delete deleteLeads;}
//catch (DmlException e)
// {
// Process exception here
// }

// TRY DELETING CONTACTS
existingContacts = [select Id, AccountId from Contact where AccountId = '0017000000NB5vCAAT'];
delete existingContacts;

//existingEvents = [select Id, AccountId from Event where AccountId = :strAccountId];
existingEvents = [select Id, AccountId from Event where AccountId = '0017000000NB5vCAAT'];
delete existingEvents;





i=5;
//sqlContact = "select lastname from contact where accountid in";
//resultContact = [ :Trigger.new];

//CustomerRouting.DropCustomerRouteEvents();


oldRecords = Trigger.old;
newRecords= Trigger.new;

System.debug(oldRecords[0].Number_of_Units__c);
System.debug(newRecords[0].Number_of_Units__c);

}
I have one after trigger and one before trigger on a custom object.
 
 whin I checked in system log I found that the triggers are executing in the following sequence
First when I Edit a record , before trigger(in which I compare a value from this object to a value in other object and throw an error) is executing and then after trigger(in which I have update statement of other custom object)
and then its going back to before trigger(but the fields which I'm updating are not commited to database) and throwing error message.
 
is this the sequence or am I missing something.
Any pointers are appreciated...
  • April 03, 2008
  • Like
  • 0
I'm at a loss how i can get code coverage with this trigger:
 
trigger forcemeetingEventtrigger on Event(before insert) {

  Event[] evt= Trigger.new;

   Forcemeeting.addforcemeeting(evt);

}
 
Can somebody suggest something at this point that would be useful?  I've read all the docs and examples on unit testing.
Good Day.
 
I did an extract of the 'Accounts' utulizing Apex Data Loader.
 
Then I went to the SalesForceFieldsReference.PDF
 
The fields do not match up.
 
Where can I get an accurate reference of the fields to import and export?
 
Thanks.
I'd like to be able to query for events that are either one-time events or are "parent" recurring events (where IsRecurrence = true), which is to say I don't want to have all of the individual events created by a single recurring events returned. Is there a way to do this?

I almost suspect the IsRecurrence field wound up meaning the opposite of what it should have. If there were two fields: IsRecurring (true for the event that defines the series) and IsRecurrence (true for the events created by the series), it would be easy to perform the query I'm looking for.

Or am I just confused?

Thanks,
charlie
  • May 11, 2006
  • Like
  • 0