Monday, 25 October 2010

Apex Triggers

So this weekend, following the Giants punching their trip to the World Series (Fear the Beard), I officially registered for Dreamforce 2010. I advise that everyone who will be attending this year to create their Chatter profile and sign-up for sessions using the Agenda Builder as soon as possible. Also any recommendations would be appreciated since it will be my first time attending any type of cloud computing event.

Ok so let’s jump into Apex triggers. If you recall from my previous post, we will use Apex Code to create these triggers and complete our scheduled payments. Apex Triggers operate like most standard database triggers, you define the trigger name for when the trigger fires and write code to act on the event. This can be before or after insert, update, or delete.

For our application we will be writing two triggers. The first trigger will create scheduled payment objects for an invoice when the invoice is created, and the second trigger will update the invoice's status when the status of a scheduled payment changes. Begin by opening the Scheduled Invoice object definition by clicking ‘Setup’, then ‘Build’, and finally ‘Objects’. At the bottom of the page you will find the ‘Triggers’ section, at which point you will select ‘New’. This will bring up the Apex Code editor, which you will see in the following screen shot:



For our first Trigger we need to replace the blank template by copying the following code and pasting it into the editor:


// After a new entry is insert into the Scheduled Invoice custom object table
// this trigger will fire and create all the scheduled payment objects for
// that invoice.
trigger ScheduledInvoice_After_Insert on Scheduled_Invoice__c
    ( after insert ) 
{
    // Apex Code's maximum batch size for updates, inserts
    // and deletes. The final key word indicates a constant.
    final Integer MAX_BATCH_SIZE = 200; 
    List<Scheduled_Payment__c> newPayments;
    Date endDate;
    Boolean isMonthly = false;
    Integer daysInPeriod = 0;
    Integer numberOfPeriods = 0;
    Double paymentPerPeriod = 0;
    Date dueDate;
    
    newPayments = new List<Scheduled_Payment__c>();
  
    // Loop through the new invoices and create scheduled payments
    // for each one depending on their settings.
    // The trigger object has two properties containing lists of updated
    // objects, new and old. For insert triggers, only the new property
    // has values.
    // The for loop below is similar to a foreach loop in C#. The C#
    // equivalent would be foreach ( Object var in varArray )
    for ( Scheduled_Invoice__c invoice : trigger.new )
    {
        // Convert the Duration in Months to an actual number of
        // periods. If the schedule type is monthly, then the number
        // of periods is equal to the duration in months, otherwise
        // you need to calculate it.
        if ( invoice.Schedule_Type__c == 'Monthly' )
        {
            numberOfPeriods = invoice.Duration_in_Months__c.intValue();
            isMonthly = true;
        }
        else
        {
            Integer numberOfDays;
  
            // For weekly and bi-weekly, calculate the end date first.
            endDate = invoice.Effective_Date__c.addMonths( 
                invoice.Duration_in_Months__c.intValue() );
            // Next, get the number of days.
            numberOfDays = invoice.Effective_Date__c.daysBetween(
                endDate );
            // Setup the number of days in the period for weekly and
            // bi-weekly payments.
            if ( invoice.Schedule_Type__c == 'Weekly' )
                daysInPeriod = 7;
            else
                daysInPeriod = 14;
            // Divide the number of days by the number of days in the
            // period to get the number of periods.
            numberOfPeriods = Math.floor( numberOfDays / 
                daysInPeriod ).intValue();
        }            
  
        // Calculate the payment per period.
        paymentPerPeriod = invoice.Total_Amount_Due__c / 
            numberOfPeriods;
        
        // Generate a new scheduled payment object for each
        // period of the invoice.
        for ( Integer x = 0; x < numberOfPeriods; x++ )
        {
            // Calcualte the due date for this period.
            if ( isMonthly )
            {
                dueDate = invoice.Effective_Date__c.addMonths( x + 1 );
            }
            else
            {
                dueDate = invoice.Effective_Date__c.addDays( 
                    daysInPeriod * ( x + 1 ) );
            }
            
            // Create the new scheduled payment object and add it
            // to the list of new payment objects to be inserted.
            // For SObjects (Salesforce Objects) you can specify the
            // property values in the constructor by using the syntax
            // <Property Name> = <value>.
            newPayments.add( new Scheduled_Payment__c(
                Invoice__c = invoice.Id, Status__c = 'Pending',
                Due_Date__c = dueDate,
                Amount_Due__c = paymentPerPeriod ) );
  
            // If you've hit the maximum batch size, insert the new
            // data and clear the list.
            if ( newPayments.size() == MAX_BATCH_SIZE )
            {
                Database.insert( newPayments );
                newPayments.clear();
            }
        }
    }
  
    // If you still have data you need to insert, insert it now.
    if ( newPayments.size() > 0 )
    {
        Database.insert( newPayments );
  }
}

Once again the final step is to simply click ‘Save’.  Normally this code would be placed in a completely separate Apex Code class editor, but in order to be concise we will include it directly into the trigger. We will go over Apex Code classes when we learn about VisualForce next week. It will make more sense in that context.

In the next post we will create the second Trigger and test both of them when they are in place.

Thursday, 21 October 2010

Page and Search Layouts

The fact that I was able to write this post last night following what was one of the most exciting baseball games I have ever witnessed is a testament to my infatuation with developing, training, and Salesforce. San Francisco has been absolutely crazy during every game and it’s so much fun to be part. But work needs to be done, serious money needs to be made, and new skills need to be learned.

So let’s begin….after we have saved our validation rules we can begin creating Page and Search Layouts. To do so we need to return to the Scheduled Payment object definition; which is done by clicking the ‘Back to Scheduled Invoice’ link. Scroll down to the ‘Page Layouts’ section and click the ‘Edit’ link next to ‘Scheduled Invoice Layout’.

The great thing about the Page Layout editor is that it allows you to easily alter the object's presentation by dragging and dropping fields within sections. Developers can also customize the by adding and removing sections and fields to fit the needs of the client or business. For our Scheduled Payment object just go ahead and arrange the field layout to what fits your particular needs. Preview what the final screen will look like and then click ‘Save’ if everything is up to your criterion.

Directly below the Page Layout section you will find the Search Layout section. The standard function of this is to control how your invoices are listed in search results, and ultimately the Scheduled Invoice Tab. We are going to add the following fields to the ‘Selected Field’ list by clicking ‘Edit’ next to ‘Search Results’:
  • Owner Alias
  • Primary Customer Contact
  • Status
  • Amount Past Due
  • Amount Pending
Save and add the same fields to the ‘Scheduled Invoices Tab’ search layout:
  • Owner Alias
  • Primary Customer Contact
  • Status
  • Amount Past Due
  • Amount Pending
Congratulations! As it stands you have created a fully functional application that has a usable interface. Select ‘Scheduled Payment Manager’ from the application drop-down list and click the Scheduled Invoices tab. To create a new scheduled invoice, simply click ‘New’, input the required values, and hit ‘Save’.

Our new invoice is finally here! Unfortunately the scheduled payments need to be created. This used to be quite a mundane task since this had to be developed manually. But with Apex Triggers, which are written in Salesforce’s Java-like scripting language Apex Code, this procedure has become much simpler. We will jump into Apex Triggers in our next post.

Monday, 18 October 2010

Validation Rules

I hope everyone had a great weekend. I had a little too much fun with my “Wife” on Saturday at a music festival and didn’t get as much design work done as I would have liked this weekend. That being said, it didn’t prevent me from writing this post regarding validation rules. This is a brief step in overall object development but very important for insuring the use of correct values and data.

Validation rules are great additions to your objects due to the fact they go beyond the simple required/not required field selections. These rules are formula based and prevent the end users from saving an object if the formula elevates to true. Your custom error message will be displayed below the field in question when the validation rule actual prevents the saving of data. We need to add two validation rules to our Scheduled Invoice object.

The first rule will prevent creation of invoices with a ‘Total Amount’ less than one, and the second rule prevents users from changing terms after the invoice has been established. To complete this we need to start at the Custom Object Definition Screen. Begin by scrolling down to the ‘Validation Rules’ section and clicking ‘Next’. Set the ‘Rule Name’ to the following:

"Disallow_Amounts_Less_Than_One"

Once set, check the ‘Active’ box. Set the ‘Error Message’ to the following:

The Total Amount Due must be greater than 1

Following this step change the error location to the ‘Total Amount Due’ field.

The developer has two options when defining the validation formula. You can either type the formula by hand or utilize the buttons around the formula editor. Our particular validation rule is only going to check to see if the ‘Total Amount Due’ is less than one. To reference the ‘Total Amount Due’ field, you can either type in the API name of the field or use the "Insert Field" button to select the field.

These rules, once established, prevent what could be potentially damaging fiscal errors for our Scheduled Invoice object. Next post we will begin using the page layout editor in order to drag and drop fields within sections. Please try to contain your excitement until then.

Thursday, 14 October 2010

Adding Roll-Up Summary Fields

What time is it?!? Game time hoooo!!

Ok so I was being facetious, it’s not game time, it’s time to add our roll-up summary fields to our custom application (You are probably thinking to yourself that might be the worst intro to a Blog post ever...and I’m inclined to agree).

We will be adding three specific fields. These three fields will calculate their values based on data in the child object. To design a roll- up summary field you need to create a new field and choose “Roll-Up Summary” as the field type. Below you will find a screen shot this particular page looks like:



To complete the process the following data will need to be inputted:

    Field Type: Roll-Up Summary
    Field Label: Amount Paid
    Field Name: Amount_Paid
    Summarized Object: Scheduled Payments
    Roll-Up Type: SUM
    Field to Aggregate: Amount Due

The final step involved in creating the roll-up summary fields is to determine filter criteria. This step is only necessary if you want to recapitulate your scheduled payments into three separate fields (which is what we are doing). These fields are ‘Amount Paid’, ‘Amount Pending’, and ‘Amount Past Due’. We start this by opening the “Filter Criteria” section and selecting “Only records meeting certain criteria should be included in the calculation” and lastly adding “Status equals Paid”. To avoid typos for these particular picklists, we use the lookup button next to the value field to select the correct picklist value we want to filter by. Finally we hit ‘Next’ and proceed through the rest of the field wizard as we have previously done.

Input the following data to create our other two fields:

    Field Type: Roll-Up Summary
    Field Label: Amount Past Due
    Field Name: Amount_Past_Due
    Summarized Object: Scheduled Payments
    Roll-Up Type: SUM
    Field to Aggregate: Amount Due
    Filter Criteria: Status equals Past Due

    Field Type: Roll-Up Summary
    Field Label: Amount Pending
    Field Name: Amount_Pending
    Summarized Object: Scheduled Payments
    Roll-Up Type: SUM
    Field to Aggregate: Amount Due
    Filter Criteria: Status equals Pending

Now that these fields are complete our objects are ready for some validation rules. This will be demonstrated in the next post because it really is game time now. The San Francisco Giants have two games to win in Philadelphia this weekend so I will be very distracted. To all my readers that are fans of the Phillies I’m sorry…but not that sorry.

Monday, 11 October 2010

Adding Custom Fields

I know all you aspiring SFDC Developers have been waiting patiently for my next post and I’m sorry for the delay. Fleet week was going on in San Francisco so of course I had to partake in the festivities. But I’m back and ready to start teaching again.

Now that we have designed our application, we need to begin adding custom fields and define the parent/child relationship. To start this simply scroll down to the ‘Custom Fields & Relationships’ and open a new custom field wizard. Select ‘Master-Detail Relationship’ and click ‘Next’. Change ‘Related To’ to ‘Scheduled Invoice’, and click ‘Next’. Set the ‘Field Label’ to ‘Invoice’, and press ‘Tab’, this will instantly set the field name to ‘Invoice’ as well. Finally click ‘Next’ to finish. Below you will see a screen shot of what the custom field wizard page looks like:


After the aforementioned steps have been completed, the page layout editor screen will appear. This is a simple drag & drop GUI editor that SFDC developers use to define the presentation of the Scheduled Invoice object. Basically page layouts create the characterization of how a specific custom object is displayed. You can have multiple page layouts characterize for a specific object. This gives different views of that object based on either user’s profile or the object data. The object data is also known as the Record Type. We will leave the page layout in default for now and click ‘Next’.

Another screen we are going to leave in the default setting for now is the Custom Related List. The screen only appears in the custom field wizard when adding a Master-Detail Relationship field or a Look-up field. The main purpose of this screen is to define a ‘Related List Label’, which is used when displaying the list of Scheduled Payments on the Scheduled Invoice screen. Again we will leave this is the “Scheduled Payments” default and move to the final step; which is giving the Master-Detail relationship a name that you can reference from the Salesforce API or Apex Code. Type “Scheduled_Payments” for the ‘Child Relationship Name’ in the ‘Edit’ link next to the Invoice field of the ‘Custom Fields & Relationships’ section. It is important you set a name for this relationship or the system will use designate an 18-character alphanumeric internal identifier.

Repeat this process and input the following data to add three more fields:

    Field Type: Date
    Field Label: Due Date
    Field Name: Due_Date
    Required: Checked

    Field Type: Currency
    Field Label: Amount Due
    Field Name: Amount_Due
    Length: 16
    Decimal Places: 2
    Required: Checked

    Field Type: Picklist
    Field Label: Status
    Field Name: Status
    Values:
        Pending
        Paid
        Past Due
    Use first value as default value: Checked

At this point you need to add custom fields to our Scheduled Invoice object. In the ‘Build’ menu under the ‘Objects’ option, you simply need to select or ‘Scheduled Invoice’ app from the list of custom objects.

Repeat this process and input the following data to add six necessary fields:

    Field Type: Date
    Field Label: Effective Date
    Field Name: Effective_Date
    Required: Checked

    Field Type: Number
    Field Label: Duration in Months
    Field Name: Duration_in_Months
    Length: 3
    Decimal Places: 0
    Required: Checked

    Field Type: Currency
    Field Label: Total Amount Due
    Field Name: Total_Amount_Due
    Length: 16
    Decimal Places: 2
    Required: Checked

    Field Type: Email
    Field Label: Primary Customer Contact
    Field Name: Primary_Customer_Contact
    Required: Checked

    Field Type: Picklist
    Field Label: Schedule Type
    Field Name: Schedule_Type
    Values:
        Monthly
        Bi-Weekly
        Weekly
    Use first value as default value: Checked

    Field Type: Picklist
    Field Label: Status
    Field Name: Status
    Values:
        Current
        Past Due
       Paid in Full
    Use first value as default value: Checked

We are going to stop here but next post we will begin adding more required fields.

Tuesday, 5 October 2010

Creating Custom Applications


Get stoked….we are finally going to create a custom application. Not the most exciting or unique thing about learning how to become a Salesforce developer but again very necessary. Creating Apps is great due to the fact they are simple and involve almost no code.

I previously mentioned that we would be creating a basic invoice-payment management system. This is an application a large number of business’s use to invoice for a specific amount that is be paid over a designated period of time. On the Custom Apps page, click "New." Type in "Scheduled Payment Manager" for the Label and what you think is best for the description. The label is the name of your application and will show up in the drop-down list in the upper-right corner of the screen. Click "Next" and you'll be prompted to choose an image for your application. The image you choose will show up in the upper-left corner of the screen. Click "Next" to continue.

You will pass by the ‘Custom Tabs’ options at this point since we have yet to create these tabs yet. We will get to that soon in this post. At this point you need to decide which end users will be granted access to the application. Personally I think you should show it to everyone who uses the platform, but I like to show off. After you hit “Save” you should see "Scheduled Payment Manager" in the list of custom applications.

This is a simple App that only requires two objects, Scheduled Invoice and Scheduled Payment. Scheduled Invoice is the parent object with a one-to-many relationship with the Scheduled Payment object. This is referred to as the Master-Detail relationship. Because of this relationship you'll create the Scheduled Invoice object first. Click "Objects" under the "Build" menu on the left side of the screen, and then click "New Custom Object". You will then input the following data to finalize the object:

Label: Scheduled Invoice
Plural Label: Scheduled Invoices
Object Name: Scheduled_Invoice
Record Name: Scheduled Invoice ID
Data Type: Auto Number
Display Format: SP-{00000}
Starting Number: 1
Allow Reports: Checked
Allow Activities: Checked
Add Notes and Attachments: Checked
Launch New Custom Tab Wizard: Checked



After hitting “Save” you are brought to the Custom Tab definition page and the “Add to Profiles” screen. Basically the only things you really need to de here is choose the ‘Tab Style’ and decide who has access to your new tab.

The “Add to Custom Apps” screen is next and allows you to choose which applications your tab is associated with. Deselect all applications except your new custom application ("Scheduled Payment Manager") and click "Save." The platform will instantly redirect your completed custom object.

An important part of this application is adding summary fields to the parent object (Scheduled Invoice). These fields calculate values based on the parent’s child objects, which is what will we create next. The child object in this application is the Scheduled Payment. To do this you simply need to input these values in the "Custom Object Definition Edit" screen:

Label: Scheduled Payment
Plural Label: Scheduled Payments
Object Name: Scheduled_Payment
Record Name: Scheduled Payment ID
Data Type: Auto Number
Display Format: SP-{00000}
Starting Number: 1
Allow Reports: Checked
Allow Activities: Unchecked
Add Notes and Attachments: Unchecked
Launch New Custom Tab Wizard: Unchecked

You won't need a custom tab for this object since it is the ‘child’ of the Scheduled Invoice object, but you will need to add custom fields. However this is a lot of information to digest at this point so we can start there in the next post.

Friday, 1 October 2010

Apex and Visualforce

As I explained in my last post Creating custom SaaS applications for Salesforce used to require the manual development of S-Controls, which are just simply components comprised of HTML and JavaScript. Visualforce is the new standard technology that allows you to create custom user interfaces for your force.com applications. Not only is Visualforce easier to use, it is much more powerful and has the added benefit of promoting good design and component reuse. This is due to the fact it has an uncorrupted separation between the business logic and interface involved in a custom page.  

Apex is the language aimed at creating the extension of existing Salesforce applications. This language operates similar to what you would see with JavaScript. Apex is a revolutionary application since it has complete functionality without the need for local software. The primary reason I enjoy working with Apex is because it allows me to do enhanced customizations. Developers can create new Salesforce application behavior as well as modify existing behavior. I get to use the same programs the original Salesforce development team utilizes to build commercial SaaS products.

Another tool Apex provides to the developer is the creation of triggers. These triggers initiate events when the end user performs specific operations. Apex also creates classes, which house business logic and procedural data-processing commands. The Salesforce developers can expose these classes as web services by adding a few simple keywords. The Apex language also provides is direct access to UI elements, such as buttons and events. It even facilitates the creation of transaction semantics and flow control. Basically it makes a lot of the developing I do a lot easier.

Creating an Application

The application we are going to build in the next couple of posts is a basic invoice-payment management system. This is an application a large number of business’s use to invoice for a specific amount that is be paid over a designated period of time. Once the invoice is created it automatically generates a payment schedule via Apex Code triggers. It will also maintain the payment status (Past Due, Pending, and Paid) using a combination of Salesforce’s built-in workflow engine Apex Code triggers. The invoice screen itself is a Visualforce page that utilizes both Salesforce’s native configurable page layouts and custom layout regions.


When we start designing this application in the next post, we will be working through the main administration page on Salesforce.com. All administration and customization options are listed along the left side of the screen. Click "Build" to expand the tree node, and then click the "Apps" link below it.


Get excited...we are going to start developing an application soon. Boo-yah.