This is a trigger used in one of the Trailhead challenges. It is on the Contact object. It occurs before insert or update operations. It displays an error message if the contacts last name is invalid name. I don’t know what this means, when would it ever be INVALIDNAME? Is this some kind of system message?

trigger RestrictContactByName on Contact (before insert, before update) {
	
	//check contacts prior to insert or update for invalid data
	For (Contact c : Trigger.New) {
		if(c.LastName == 'INVALIDNAME') {	//invalidname is invalid
			c.AddError('The Last Name "'+c.LastName+'" is not allowed for DML');
		}
	}
}

This test class tests the above trigger. It creates a list of contacts where one of them has INVALID NAME as the last name.

Then there is a method where it uses ‘try’ and ‘catch’. I’ve seen this before but I’ve never really studied what it is. Apparently it tries to insert the list of contacts, which would cause the trigger to fire. And then it catches exceptions meaning any items of the list which don’t work?

@isTest
private class TestRestrictContactByName {

    static testMethod void  metodoTest() 
    {

        List listContact= new List();
        Contact c1 = new Contact(FirstName='Francesco', LastName='Riggio' , email='Test@test.com');
        Contact c2 = new Contact(FirstName='Francesco1', LastName = 'INVALIDNAME',email='Test@test.com');
        listContact.add(c1);
        listContact.add(c2);
        
        Test.startTest();
            try
            {
                insert listContact;
            }
            catch(Exception ee)
            {
            }   
        Test.stopTest();    
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s