Teach Me Salesforce

A community approach to learning salesforce.com

Posts Tagged ‘Apex

Trailhead Review: Quick Start: Apex Coding for Admins

leave a comment »

Review of Quick Start: Apex Coding for Admins

This Project won’t teach you a lot of Apex concepts, but is good practice creating Apex Classes and Triggers in the Setup UI and using Workbench with Anonymous Apex to execute the code. The Steps themselves don’t try to teach you Apex and just involve cutting and pasting code then executing the code, however the comments are thorough, one for each line. The comments use formal terminology to describe each line’s action, so they are a good lesson in speaking “Developer”.

Overall, the instructions could add more detailed conceptual descriptions to help Admins grasp what they are doing, perhaps even comparing the actions to what they might already know from declarative development (e.g. the BankAcct class is similar to a Custom Object with number and text fields, plus a Workflow Field Update that adds numbers).

Step 1 is just about setting up the metadata for this project.

Step 2 is just copying and pasting to create two Apex Classes.

Step 3 is just another copy and paste into Workbench to verify that the previous classes behave as expected.

Step 4 introduces Lists and replaces the code fromStep 2 to include a List.

So far, not many concepts have been discussed in the Trailhead itself, but the comments in the code are thorough and should be read carefully to get the most out of this module.

Step 5 introduces For Loops (although without really explaining what they’re for) and updates an Apex class to include a For Loop.

Step 6 introduces DML, specifically the database insert method to add Contacts.

Step 7 introduces SOQL and updates an Apex class to include a SOQL query.

Step 8 adds a Trigger and tests it by creating a custom object record to verify that the Contact insert from Step 6 works.

 

Advertisements

Written by Always Thinkin

December 9, 2018 at 4:49 pm

Posted in Apex, Beginner

Tagged with

Unit Tests: Not Just for Dev – Idea 1

leave a comment »

Unit tests offer much more than just the means to get 75%+ code coverage, and they can be used to protect more than just Apex. Read the intro to this series in Idea 0.

Our first example is the simplest: protecting fields that you don’t want deleted. A use case for this is External Integrations that rely on Salesforce fields. If someone tries to delete the fields, you want to ensure that they are alerted to the impact. By including the fields Current Generators and SIC Code in the example Unit Test below, an attempt to delete the fields will throw an error referencing the unit test.

@isTest
private class UnitTest1 {
    static testMethod void protectFields(){

    /*Create a new Lead, populating any Fields you need to protect
    * In this case, we want to ensure Current Generators and SIC Code cannot be deleted
    * or the field type changed by including them in this Apex Unit Test
    */
    Lead l = new Lead(Company = 'Test Lead',
                      LastName = 'Lead Last Name',
                      CurrentGenerators__c = 'Generator X',
                      SICCode__c = '1234-ABC');
    insert l;
    }
}

Let’s describe what’s happening here.

We start off with the all-important @isTest flag. This tells Salesforce that the Apex Class contains only test Methods. That means nothing you do in the Class will be saved to the server, and will not delete or change anything on the server. It also means you cannot use most records that exist on the server, so you have to create your own test records.

@isTest means that Salesforce will recognize it as a test Class, and when you Run All Tests, it will know to run this test too.

Next is the Class Name, UnitTest1 and its access modifier is set to “private”. Access modifiers are irrelevant for Unit Tests, private is the default.

The actual test Method here is protectFields(). Your test exists between the curly braces {}. Here you must create your test records and perform any actions you want tested. The critical item here is “testMethod” which ensures that Salesforce recognizes the method as performing tests. Without this, Salesforce will not report a test failure regardless of the outcome.

In this case we are creating a Lead. We are using standard Apex code to create a Lead, to populate fields on that Lead, and finally to use DML to insert the Lead. Required fields and Validation Rules will get enforced when you create the Lead, so be sure to include any fields affected by them.

Once this Unit Test is saved to the server, any attempt to delete the field or change its data type will be blocked with a reference to this Unit Test.

For this limited scenario, that’s all we need!

Written by Always Thinkin

August 3, 2014 at 3:53 pm

Posted in Apex, Code Sample, Intermediate

Tagged with ,

Unit Tests: Not Just for Dev – Idea 0

leave a comment »

This post is kicking off a series of posts about how Salesforce Admins & Developers can use Unit Tests for more than just testing Apex. The target audience is Admins who haven’t written Unit Tests. The ideas for Unit Tests here are intended to be easily copied and modified by anyone with System Admin access, a Sandbox or Developer Edition Org and a need to add a little more protection to their hard-won successes in building their org.

Unit Tests are designed to test Apex Triggers and Classes. They are required for deploying them to Production, but more important they are an essential tool to ensure that your logic, both Apex and declarative, does what it’s supposed to do, and nothing more or less.

But how else can they be useful?

Protection Integrations: Many Salesforce Orgs are now integrated with other applications and rely on the fields in Salesforce to, well, exist. And not to change or get locked down. Unit tests can be used to protect all the fields an integration uses against deletion, against changes to field type or restrictions by Field-level Security or Validation Rules.

Testing Declarative-only Apps: All those Clicks-not-Code components can add up to a complex series of Workflow Rules, Formula Fields and Validation Rules where you’ve got an application that is vulnerable to even slight changes. Unit tests can be used to ensure that a series of related Rules and Fields perform as expected, and that changes don’t disrupt the outcome.

And that application’s complexity can become difficult to test when there are hundreds of combinations of fields and their values. Throw in the ability to mass edit records in Views or Data Loader and you’ve got hours of manual tests to perform. Unit Test can be written to try all the combinations you want to throw at it, for hundreds of records.

The Ideas and Unit Tests in this series are all written using the sample data and metadata from the Developer Edition Orgs. Where necessary, I’ll add some new Workflow Rules, Validation Rules and Fields to come up with viable scenarios. If you don’t already have a Developer Edition org, you can get one (or one hundred) free Orgs at developer.force.com.

Because it’s so handy, we’ll use the Developer Console to write and run the Unit Tests, but you can also use the Force.com IDE for Eclipse, MavensMate or even the declarative interface.

You won’t need to know much Apex. I’ll attempt to explain the parts that are not intuitive, or just advise you to do-as-I-do if the explanation won’t help (or I don’t know either).

So put your pencils down, Testing time is up: Idea 1

Written by Always Thinkin

August 3, 2014 at 3:28 pm

Posted in Apex, Intermediate, Validation, Workflow

Tagged with ,

Trigger to create a new record

with 13 comments

Ask me a year ago, and I never thought I’d be writing triggers, but yet, here I am. I gained a bit of confidence after taking the Salesforce DEV 531 class, and that confidence then flourished with the support of this community. This blog just goes to show how many people out there are willing to help, and I definitely want to return the favor whenever possible. So here goes – the anatomy of my first trigger.

What I was looking to do was to create a new support request record (a custom object) when a new Event record of a specific type was created. Pretty straight-forward, but definitely not doable without a trigger. The final result was this:

trigger createPDtask on Event (after insert) {     
List<Support_Request__c> sr = new List<Support_Request__c>();
    for (Event newEvent: Trigger.New)
         if (newEvent.Type__c == '1. Meeting - Initial'){
                 sr.add (new Support_Request__c(
                     Name = 'New PD',
                     Task_Type__c = 'PD',
                     SFDC_Record_ID__c = newEvent.Id,
                     Rep__c = newEvent.OwnerId,
                     Event_Date__c = newEvent.ActivityDate));   
         }
   insert sr;
 }

Now for the breakdown of what I was trying to do with each step. First, I define what I want the trigger to do & when to do it.

trigger createPDtask on Event (after insert) {

The second line compiles all new records I am going to insert into a list (& therefore takes care of bulkifying my trigger).

List<Support_Request__c> sr = new List<Support_Request__c>();

Then I need to define the criteria around the event record that would cause this trigger to create a new support request.

for (Event newEvent: Trigger.New)
         if (newEvent.Type__c == '1. Meeting - Initial'){

Next, I set the details that get inserted into the new Support Request record. You can see that some are static, while a few are dynamically pulled from the event record.

sr.add (new Support_Request__c(
                     Name = 'New PD',
                     Task_Type__c = 'PD',
                     SFDC_Record_ID__c = newEvent.Id,
                     Rep__c = newEvent.OwnerId,
                     Event_Date__c = newEvent.ActivityDate));

Finally, the list gets inserted.

 }
   insert sr;
 }

As far as triggers goes, it’s pretty simple, but it was a great learning process for me to build on my own. From here, the next step is to write some test coverage, and while I thought I had it in the bag, I’m going to let Kyle share the lesson he gave me in a subsequent post.

Written by Becka

May 16, 2011 at 10:10 am

Posted in Apex, Beginner, Intermediate, Trigger

Tagged with

Call Apex code from a custom button

with 3 comments

Want to be able to call an Apex class from a custom button on a detail page? I see this request show up somewhat frequently, and it is really quite useful. All you need to do is enable your apex class as a webservice, like so.

WebService static integer addNumbers(integer numOne, integer numTwo)
{
    return numOne + numTwo;
}

You can then invoke it via an execute javascript custom button.

{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")}
var myvar = sforce.apex.execute("yourClass","addNumbers", {numOne:4,numTwo:5}");
window.alert(myvar);

Just replace the yourClass with the name of a class with the method you want to invoke.
You can pass arguments to the method by name, using the format you see above.
You can of course also pass in field values by using the field value
notation {!object.fieldName}. Remember to wrap text values in quotes.

Written by kenji776

May 2, 2011 at 1:52 pm

Posted in Apex, Intermediate

Tagged with , ,