Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Friday, October 31, 2014

Simple Lightning-to-Lead tutorial for the Salesforce1 Platform

If you're brand new to Lightning on the Salesforce1 Platform, and you're having a bit of trouble following the cool but relatively complex Expenses sample app from the Lightning Components Developer's Guide, maybe this Lightning-to-Lead tutorial will work better for you.

The goal is simple: Create a one-page app that basically does what Web-to-Lead does, which is to create a new Lead record. Nothing glorious, but it's just complicated enough to go over some core concepts. When you're done, you'll end up with a simple page with a few fields and a lone button.


Sound simple? Give it a try and let me know what you think!

Wednesday, August 20, 2014

Close recurring tasks using Apex

At least one developer had reported encountering an error when trying to automate updates to Task records using Apex: System.UnexpectedException: Apex Task trigger cannot handle batch operations on recurring tasks. This error occurs even in simple scenarios, such as simply closing any open tasks on a close opportunity.

While I agree with what I imagine to be general consensus that this error seems crazy, luckily there appears to be a workaround: Update a custom flag using Apex, and then use workflow rules to handle the dirty work of updating restricted standard field(s).

While I've only tested this approach on the scenario below, I think it will be applicable to solving other similar problems with updating Task records using Apex.

Sample solution to close recurring tasks using Apex


The anonymous Apex code below illustrates the solution.


And there's nothing special about the checkbox field, the workflow rule or the field update. The idea is that when the checkbox is checked, the workflow rule fires and performs the field update.


Wednesday, June 18, 2014

Rails directories for Heroku Connect

Heroku Connect is a new add-on offering that simplifies data synchronization between Heroku apps and Salesforce. At its core, Heroku Connect periodically syncs selected objects and fields between Salesforce and Heroku. While the demo Rails app provided by Heroku gives a solid recommendation for extending ActiveRecord::Base to create an analog for models in the Heroku Connect database, some gaps still existed in terms of how to best set up your Rails app and define your classes.

After some experimentation, I decided on the following setup for my app:

  • Heroku Connect model paths: app/models/heroku_connect/schema_name/table_name.rb
  • HerokuConnectRecord::Base
  • Autoload lib modules and classes

I'll explain the setup in more detail below, but quick question: How would you set up your Rails app directories for Heroku Connect?

Heroku Connect model paths


All models in your Rails app by default go in the app/models/ directory. Rails knows to autoload models stored in the models/ directory, and as a result it seemed to reason that Heroku Connect models should go in the same directory. But a namespace is needed to prevent conflicts between regular Rails models and Heroku Connect models. And moreover, what if you have multiple Heroku Connect databases in play?

My implementation addresses this by first moving Heroku Connect models into its own namespace a la the heroku_connect/ directory. Next, different Heroku Connect databases can be split by the schema name or some other unique identifier for each database.

Examples of Heroku Connect model class paths, assuming the schema name "salesforce"
sObject NameClass NameModel Path
Car__cHerokuConnect::Salesforce::Car__capp/models/heroku_connect/salesforce/car__c.rb
OpportunityLineItemHerokuConnect::Salesforce::OpportunityLineItemapp/models/heroku_connect/salesforce/opportunity_line_item.rb
AssessmentPeriod__cHerokuConnect::Salesforce::AssessmentPeriod__capp/models/heroku_connect/salesforce/assessment_period__c.rb

Note: For custom object models, the double-underscores can be written as-is in the name of the .rb file. To be more technical, use the String.underscore method in irb to derive the expected name of the model's .rb file. For example, JointVenture__c would become "joint_venture__c.rb", and Lazy_Boy__c would become "lazy_boy__c.rb".

HerokuConnectRecord::Base


Heroku recommends extending ActiveRecord::Base to create a base for all Heroku Connect models. I thought that instead of calling my base class SalesforceBase, I would call it HerokuConnectRecord::Base to be mimic the naming convention for ActiveRecord::Base. While there's no direct need for this to get going, I figured I would adopt this convention in case I need to extend other Active__ modules or classes down the road for Heroku Connect.

All that's needed to set up this class is the following code, placed within lib/heroku_connect_record/base.rb:

module HerokuConnectRecord
  class Base < ActiveRecord::Base
    self.abstract_class = true
    establish_connection ENV['DATABASE_URL']
  end
end

All Heroku Connect module classes would then extend this class, as in:

module HerokuConnect
  module Salesforce
    class Car__c < HerokuConnectRecord::Base
      self.table_name = "salesforce.car__c"
    end
  end
end

Autoload lib modules and classes


Finally, to autoload HerokuConnectRecord::Base (and potentially future custom classes for Heroku Connect), I adopted ifyouseewendy's recommendation to add the following line to config/application.rb:

config.autoload_paths += %W(#{config.root}/lib)

Friday, December 20, 2013

Testing Apex @future Methods in Salesforce

To write functional Apex unit tests for methods having the future annotation, all you need to do is use Test.startTest() and Test.stopTest(). The general structure of your testMethod will look like the following.

Whether it's scheduled Apex or @future Apex, calling Test.stopTest() will cause those methods to run in sequence in your test method. Test.stopTest() then allows you to validate the results of @future Apex using normal means.

Friday, October 4, 2013

Force.com #Tested, Standard Pattern for Apex Unit Tests

The first step to writing an Apex unit test is... just to lay down the framework. The boring stuff, really. Declare the class, add the isTest annotation, declare a testMethod-qualified method, etc. And to make boring matters worse, in practice Apex unit testing is pretty important to get right.

The reason is simple: In addition to deploying your own customizations, Salesforce will upgrade your org 3 times a year with 100+ new features per release. Whether you like it or not. Assuming CRM is fairly important to your organization, who's going to run tests for your org every time a new release happens, to make sure the business can continue to operate?

  • Code coverage and test methods are intended to make sure that customizations work correctly, release after release, with minimal human effort
  • Good tests help to make sure your code works not only for one-off record edits but also for batch inserts, updates and deletes
  • With good intent, Salesforce requires you to have at least 75% code coverage to deploy new code. So, if you have to write tests anyway, let's just do it right the first time. Build the tests to add value as regression tests, instead of just time drains.


Understanding the significance of these tests, a new developer may find writing good tests to be quite daunting, second-guessing himself and worrying about whether he followed best practices. Then, in frustration, he could decide to just "screw it" and hack something out to achieve the minimum amount of code coverage required to just push a risky feature into production. Bad outcome.

To help a developer avoid this sub-optimal decision, he can adopt a standard test class structure that is easily adapted for all Apex unit tests. Below is one such self-documenting template for Apex unit tests, using a contrived example of trying to roll-up all activities related to a particular contact record.


There are lots of comments and little code in the above block, which is intentional to leave material for the rest of this series. :-) Subsequent posts will dive into each step above in more detail, walking through sample implementations by building out this example trigger test class.

But regardless of whether you're testing triggers, controllers, extensions, Schedulables or anything else in Apex, the general steps above should remain the same for your test methods. This way, Apex unit tests transform from time-and-materials liabilities in a Salesforce org to valuable assets that shine every time anyone goes to release a new feature.

Wednesday, September 25, 2013

Force.com #Tested, Way Beyond Code Coverage

Force.com gives developers a quick and easy way to not only deploy business automation but also to set up unit tests for acceptance testing and regression testing. The value of such testing cannot be underestimated, especially in large orgs with multiple admins, developers and outsourced partners.

While the ideals are good, there are many challenges preventing an organization from reaching these goals. Managers may not fully understand the benefits of unit testing, and as a result have little or no buy-in for the practice. Without buy-in from managers, there is no enforcement of consistent methodologies for internal and external developers. Frustrated developers who don't have management support, training or knowledge on unit tests only see the code coverage portion of unit testing and feel that the practice is a big pain with little gain.

But actually, proper and disciplined use of unit tests on Force.com allows a company to:
  • More reliably implement new features by explicitly testing for expected functionality using Apex
  • Simplify regression testing by allowing the system to automatically perform acceptance tests that were used when deploying previous features to production
  • More confidently allow developers to simultaneously tackle multiple work streams for different features, knowing that both each other's functionality and previous functionality will be validated together before new features goes live
  • Define functional specifications for external parties through unit tests, in addition to written requirements

This blog mini-series aims to address the challenges above by sequentially tackling the following topics, with new posts every 3 business days:
  1. Standard pattern for Apex unit tests
  2. Common database of test data for all Apex unit tests
  3. Using System.assert() and related methods to verify expected conditions for the test
  4. Using Test.startTest(), Test.stopTest() and other Test methods
  5. Using System.assert() and related methods for validating test results
  6. Apex unit tests for workflow rules, validation rules and system configurations
  7. How this standard pattern affects code coverage