Salesforce Archives - Justin Silver https://www.justinsilver.com/tag/salesforce/ Technology, Travel, and Pictures Sun, 01 Mar 2020 00:09:41 +0000 en-US hourly 1 https://wordpress.org/?v=6.0.1 https://www.justinsilver.com/wp-content/uploads/2013/06/cropped-apple-touch-icon-160x160.png Salesforce Archives - Justin Silver https://www.justinsilver.com/tag/salesforce/ 32 32 Salesforce sObject Id Validation in Apex https://www.justinsilver.com/technology/salesforce/salesforce-sobject-id-validation-apex/?utm_source=rss&utm_medium=rss&utm_campaign=salesforce-sobject-id-validation-apex https://www.justinsilver.com/technology/salesforce/salesforce-sobject-id-validation-apex/#comments Thu, 10 Dec 2015 20:50:22 +0000 http://justinsilver.com/?p=3989 Salesforce sObject Id‘s are specially formatted strings used to uniquely identify sObjects. If you want to test the validity of an sObject Id in Apex, you can go the simple route of checking the...

The post Salesforce sObject Id Validation in Apex appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

Salesforce sObject Id‘s are specially formatted strings used to uniquely identify sObjects. If you want to test the validity of an sObject Id in Apex, you can go the simple route of checking the length, the slightly more complex route of writing a regular expression, or even go as far as to implement the logic parsing of ID values. An easier way to get accurate testing of validity is to create an instance of the sObject you want to test against, then try to assign your sObject Id to it, and catch any Exceptions. This will validate both the format, as well as the type of the sObject Id.

The Util Code

public abstract class MyUtilClass {
    /**
     * Test a String to see if it is a valid SFDC  ID
     * @param  sfdcId The ID to test.
     * @param  t      The Type of the sObject to compare against
     * @return        Returns true if the ID is valid, false if it is not.
     */
    public static Boolean isValidSalesforceId( String sfdcId, System.Type t ){
        try {

            if ( Pattern.compile( '[a-zA-Z0-9]{15}|[a-zA-Z0-9]{18}' ).matcher( sfdcId ).matches() ){
                // Try to assign it to an Id before checking the type
                Id id = theId;

                // Use the Type to construct an instance of this sObject
                sObject sObj = (sObject) t.newInstance();
     
                // Set the ID of the new object to the value to test
                sObj.Id = id;

                // If the tests passed, it's valid
                return true;
            }
        } catch ( Exception e ){
            // StringException, TypeException
        }

        // ID is not valid
        return false;
    }
}

You can then test the validity of the sObject Id by passing it into the util method along with the System.Type of the sObject you want to compare against. The type can be accessed using sObject.class.

Call From Apex

// maybe a valid Account.Id, maybe not?
String theId = '001xxxxxxxxxxxx'; 

if ( MyUtilClass.isValidSalesforceID( theId, Account.class ) ){
    // do something if it is valid
}

The post Salesforce sObject Id Validation in Apex appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/salesforce/salesforce-sobject-id-validation-apex/feed/ 3
Install WSDL2Apex on OS X El Capitan https://www.justinsilver.com/technology/osx/install-wsdl2apex-on-os-x-el-capitan/?utm_source=rss&utm_medium=rss&utm_campaign=install-wsdl2apex-on-os-x-el-capitan https://www.justinsilver.com/technology/osx/install-wsdl2apex-on-os-x-el-capitan/#comments Tue, 24 Nov 2015 21:09:19 +0000 http://justinsilver.com/?p=3979 The WSDL2Apex generates the Apex classes necessary to implement a SOAP callout from the Force.com platform using the WSDL for the service you are trying to implement. In 2014 it was split out of...

The post Install WSDL2Apex on OS X El Capitan appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

The WSDL2Apex generates the Apex classes necessary to implement a SOAP callout from the Force.com platform using the WSDL for the service you are trying to implement. In 2014 it was split out of the Force.com IDE codebase and was made open source , available on it’s own as an open source project.

This means that you can clone the GitHub project, build the JAR, and then use it to consume a WSDL and generate your Apex classes. There is one caveat for OS X El Capitan (and Yosemite as well) in that the operating system ships with Java 1.8, however WSDL2Apex requires Java 1.7 or earlier. If you try to run the build using a later version of Java, you will get 12-15 test errors (I got 12, other people reported 15).

Results :

Failed tests:   testAsyncFalse(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test 8 doesn't match expected:<...rmationByAirportCode[Response_element {(..)
  testNewClassNames(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): testNewClassNames doesn't match expected:<... }(..)
  testNoOperation(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test noOperation failed expected:<...   public class Echo[Date_element {(..)
  testExchange(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test testExchange failed expected:<...{(..)
  testAmazonGood(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test testAmazonGood failed expected:<... {(..)
  testBigFile(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test testBigFile failed expected:<... {(..)
  testNamespaceDependencies(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test testNamespaceDependencies failed expected:<... {(..)
  testTwoNamespaces(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): testTwoNamespaces a doesn't match, Async class expected:<...mple.com/stockquote.[wsdl', 'exampleComStockquoteWsdl', 'http://example.com/stockquote.xsd', 'exampleComStockquoteXsd]'};(..)
  testSqlMutations(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test sqlMutations failed expected:<...lic class getMutants[CompressedResponse_element {(..)
  testMultipleNamespace(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): Test testMultipleNamespace failed expected:<...   public class Echo[Date_element {(..)
  testLargeFile(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): testLargeFile a doesn't match expected:<...m/spectrum/services/[EOLS_PSAPLookupUS', 'wwwPbComSpectrumServicesEolsPsaplo', 'http://spectrum.pb.com/', 'spectrumPbCom', 'http://www.mapinfo.com/midev/service/geometries/v1', 'wwwMapinfoComMidevServiceGeometries', 'http://www.mapinfo.com/midev/service/units/v1', 'wwwMapinfoComMidevServiceUnitsV1', 'http://www.pb.com/spectrum/services/', 'wwwPbComSpectrumServic]es'};(..)
  testSimple(com.salesforce.ide.wsdl2apex.core.WSDL2ApexTest): testSimple doesn't match expected:<...rmationByAirportCode[Response_element {(..)

Tests run: 47, Failures: 12, Errors: 0, Skipped: 0

[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.230 s
[INFO] Finished at: 2015-11-23T20:30:10-08:00
[INFO] Final Memory: 8M/245M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12.4:test (default-test) on project WSDL2Apex: There are test failures.

Requirements

  • Homebrew
  • git
  • Apache Maven
  • Java 1.6

We’ll use Homebrew to install git (to fetch the project), Apache Maven (to build the project), and Java 1.6 from Apple to meet the version requirements.

Homebrew, Git, and Maven

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew install maven git

Clone WSDL2Apex

mkdir ~/SalesforceDev && cd ~/SalesforceDev
git clone https://github.com/forcedotcom/WSDL2Apex
cd WSDL2Apex

Java 1.6 for OS X

Visit the Apple support site to download and install Java 1.6 for OS X. It will be installed to your /Library/Java/JavaVirtualMachines/1.6.0.jdk/ directory.

Build WSDL2Apex

We need to set the JAVA_HOME directory to point to the 1.6 JDK so that Maven will use it for the build. To do this just set it before the actual mvn execution. If you have Java 1.7 on your machine, feel free to substitute it for 1.6 – just check your JavaVirtualMachines directory to see what’s available.

JAVA_HOME=/Library/Java/JavaVirtualMachines/j1.6.0.jdk/Contents/Home/ \
mvn install package

Bask in the glory that are your newly generated Apex SOAP classes.

The post Install WSDL2Apex on OS X El Capitan appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/osx/install-wsdl2apex-on-os-x-el-capitan/feed/ 4
Hide Edit/Del Links on Salesforce Standard Page https://www.justinsilver.com/technology/salesforce/hide-edit-del-link-on-salesforce-standard-pages/?utm_source=rss&utm_medium=rss&utm_campaign=hide-edit-del-link-on-salesforce-standard-pages https://www.justinsilver.com/technology/salesforce/hide-edit-del-link-on-salesforce-standard-pages/#comments Thu, 13 Nov 2014 00:36:35 +0000 http://justinsilver.com/?p=3831 It is not possible to control the visibility of the Edit/Del action links for a related list. On a VisualForce page you can insert your own CSS or Javascript to control the display, which...

The post Hide Edit/Del Links on Salesforce Standard Page appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

It is not possible to control the visibility of the Edit/Del action links for a related list. On a VisualForce page you can insert your own CSS or Javascript to control the display, which you can also do on a Salesforce standard layout, albeit in a slightly more complicated fashion.

The trick is to use a Custom Link on your Home Page Layout. This Custom Link is defined as an onClick, but will actually load code inline with the use of REQUIRESCRIPT. Inside the REQUIRESCRIPT will be our Javascript payload, Base64 encoded.

Create Javascript Payload

First let’s compile the Javascript we need to control the UI on standard page layouts. In this case we want to hide the Edit/Del links on a related list, so view the page and use your developer tools to look at the DOM. You want to find the ID of the top level element in the related list table, something like “500c0000004BtmN_00sE0000004gkgq_body”. Use the following snippet as an example.

jQuery(document).ready(function($){
	// hide this sidebar module
	$('#sidebarDiv div.linksModule').each(function(){
		var $module = $(this);
		if ( $module.find('.brandPrimaryFgr').text()=='UserInterfaceInjection'){
			$module.hide();
			return false;
		}
	});
	// hide the Edit/Del links
	jQuery('#500c0000004BtmN_00sE0000004gkgq_body .actionColumn').hide();
});

Now we need to convert this to Base64. Any way is fine, but online is pretty easy: https://www.base64encode.org/.

alF1ZXJ5KGRvY3VtZW50KS5yZWFkeShmdW5jdGlvbigkKXsNCgkvLyBoaWRlIHRoaXMgc2lkZWJhciBtb2R1bGUNCgkkKCcjc2lkZWJhckRpdiBkaXYubGlua3NNb2R1bGUnKS5lYWNoKGZ1bmN0aW9uKCl7DQoJCXZhciAkbW9kdWxlID0gJCh0aGlzKTsNCgkJaWYgKCAkbW9kdWxlLmZpbmQoJy5icmFuZFByaW1hcnlGZ3InKS50ZXh0KCk9PSdVc2VySW50ZXJmYWNlSW5qZWN0aW9uJyl7DQoJCQkkbW9kdWxlLmhpZGUoKTsNCgkJCXJldHVybiBmYWxzZTsNCgkJfQ0KCX0pOw0KCS8vIGhpZGUgdGhlIEVkaXQvRGVsIGxpbmtzDQoJalF1ZXJ5KCcjNTAwYzAwMDAwMDRCdG1OXzAwc0UwMDAwMDA0Z2tncV9ib2R5IC5hY3Rpb25Db2x1bW4nKS5oaWRlKCk7DQp9KTs=

Put this text aside, we will need it later when creating the Javascript link.

Create Custom Link

Visit Setup > Home > Customize > Custom Links

  1. Create a new Link
  2. Name: UserInterfaceInjection
  3. Behavior: Execute Javascript
  4. Content Source: onClick Javascript
  5. Body: {!REQUIRESCRIPT('data:application/javascript;base64,BASE64_JS')}, except that you want to replace BASE64_JS with your Base64 encoded Javascript.

Create Home Page Component

Visit Setup > Home > Home Page Components

  1. Create a new Component
  2. Name: UserInterfaceInjection
  3. Type: Links
  4. Choose UserInterfaceInjection Link

Add to Home Page Layout

Visit Setup > Home > Home Page Layouts

  1. Edit your layout to include UserInterfaceInjection

Now when you visit your page the Action column should be hidden from your related list. It’s pretty easy to see how this could be further expanded to add all kinds of custom functionality to standard Page Layouts in Salesforce.

The post Hide Edit/Del Links on Salesforce Standard Page appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/salesforce/hide-edit-del-link-on-salesforce-standard-pages/feed/ 10
Use jQuery + Plugins with Visualforce Pages https://www.justinsilver.com/technology/salesforce/use-jquery-plugins-visualforce-pages/?utm_source=rss&utm_medium=rss&utm_campaign=use-jquery-plugins-visualforce-pages https://www.justinsilver.com/technology/salesforce/use-jquery-plugins-visualforce-pages/#respond Sun, 09 Nov 2014 11:31:25 +0000 http://justinsilver.com/?p=3820 The jQuery library makes it much easier to create cross-browser functionality on any web page, and Salesforce Visualforce pages are no exception. Going one step further and include jQuery plugins in your pages as...

The post Use jQuery + Plugins with Visualforce Pages appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

The jQuery library makes it much easier to create cross-browser functionality on any web page, and Salesforce Visualforce pages are no exception. Going one step further and include jQuery plugins in your pages as well for even more functionality and sparkles. But what do you do when you want to use a more recent version of jQuery, and your plugin is being reported as an undefined function in the console? To the rescue comes jQuery.noConflict(true);.

First you will want to upload both jQuery and your plugin as Static Resources, or from a CDN if you prefer. For our purposes we will assume they are Static Resources called jQuery and jQueryPlugin. As soon as the javascript sources is includes – jQuery first followed by plugins – we need to make a call to noConflict() to free up the $ resources. Using jQuery as an alias is easy and logical.

Next we want to tell our code to run after the DOM of the page has loaded, so we wrap our code inside a function that is called by jQuery.ready(). A neat trick here is to pass jQuery back into the callback function as $, so your code will know the version of jQuery you loaded and it’s attached plugins as the standard $.

<!-- include static resources -->
<apex:includeScript value="{!$Resource.jQuery}" />
<apex:includeScript value="{!$Resource.jQueryPlugin}" />
<script type="text/javascript">
// Alias to jQuery and free $
jQuery = $.noConflict(true);

// Call jQuery.ready(), and alias jQuery back to $ by passing as an argument
jQuery(document).ready(function($){
	// use $.plugin()
	$('#container').plugin();

	// attach events to DOM elements
	$('.button').on('click', function(){
		alert('clicked!');
	});
});
</script>

The post Use jQuery + Plugins with Visualforce Pages appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/salesforce/use-jquery-plugins-visualforce-pages/feed/ 0
Get Week of Month in a Salesforce Formula Field https://www.justinsilver.com/technology/salesforce/get-week-month-salesforce-formula-field/?utm_source=rss&utm_medium=rss&utm_campaign=get-week-month-salesforce-formula-field https://www.justinsilver.com/technology/salesforce/get-week-month-salesforce-formula-field/#comments Thu, 06 Nov 2014 06:05:50 +0000 http://justinsilver.com/?p=3810 If you want to add a custom formula field to a standard or custom Salesforce object you have to get tricky as there is no built in function to return the week of the...

The post Get Week of Month in a Salesforce Formula Field appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

If you want to add a custom formula field to a standard or custom Salesforce object you have to get tricky as there is no built in function to return the week of the month based on a given starting day of the week. For this example we will assume we have an existing Date field called Date__c.

If the week starts on Sunday and the 1st of the month is a Sunday we can just use CEILING(Date__c/7) to figure it out. But what happens when the 1st is on a Monday? The 7th is now in the second week of the month and not the first.

Calculate Offset of the 1st

We can account for this by determining the index of the 1st of the month and then adding that to the DAY(Date__c) value to accurately capture the week of the month. This means that if the first is a Monday, the index will be 1, and thus the CEILING((7th + 1)/7) will give us week 2.

To get the day of the week offset we can start with a known Sunday the 1st – 1900-04-01 for example – and then get the number of days between it and the first of the month of the date we want to get the week of the month of. Once we have the difference in days we can take that value divided by 7 less the remainder to get the day of the week index.

Completed Formula

CEILING(
	(
	DAY( Date__c ) +
	MOD( DATE( YEAR( Date__c ), MONTH( Date__c ), 1 ) - DATE( 1900, 4, 1 ), 7 )
	) / 7
)

The post Get Week of Month in a Salesforce Formula Field appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/salesforce/get-week-month-salesforce-formula-field/feed/ 2
Protected: Salesforce Continuous Integration https://www.justinsilver.com/technology/salesforce/salesforce-continuous-integration/?utm_source=rss&utm_medium=rss&utm_campaign=salesforce-continuous-integration https://www.justinsilver.com/technology/salesforce/salesforce-continuous-integration/#respond Sat, 22 Mar 2014 01:21:38 +0000 http://justin.ag/?p=3081 There is no excerpt because this is a protected post.

The post Protected: Salesforce Continuous Integration appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

This content is password protected. To view it please enter your password below:

The post Protected: Salesforce Continuous Integration appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/salesforce/salesforce-continuous-integration/feed/ 0
Loggly.com Logging with Salesforce.com Apex https://www.justinsilver.com/technology/salesforce/loggly-com-logging-salesforce-com-apex/?utm_source=rss&utm_medium=rss&utm_campaign=loggly-com-logging-salesforce-com-apex https://www.justinsilver.com/technology/salesforce/loggly-com-logging-salesforce-com-apex/#respond Fri, 14 Feb 2014 01:26:21 +0000 http://justin.ag/?p=3173 If you want to send log messages to Loggly.com you will need to implement their HTTP API interface. All that is required to send data to this interface is an HTTP POST to a...

The post Loggly.com Logging with Salesforce.com Apex appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

If you want to send log messages to Loggly.com you will need to implement their HTTP API interface. All that is required to send data to this interface is an HTTP POST to a url containing your API token with the log message in the body. Tags can be applied either in the URL after your token or using the X-LOGGLY-TAG. Setting the Content-Type header is also required with value of text/plain.

Worth noting that you should keep your Apex Limits in mind in regards to number of callouts and possibly implement a different scheme depending on your volume. Don’t forget to add “https://logs-01.loggly.com” to your Salesforce.com>Setup>Security Controls>Remote Site Settings.

Apex Class LogglyService.cls

This class uses the @future (callout=true) annotation to make an HTTP POST to Loggly.com

public abstract class LogglyService {

    // Use a future method to make a callout
    @future (callout=true)
    public static void log(String data, String[] tags) {
        // this should come from config somewhere
    	final String api_key = 'GET YOUR API KEY FROM SOMEWHERE';

        // objects to make the request
        HttpRequest request = new HttpRequest();
        HttpResponse response = new HttpResponse();
        Http http = new Http();

        // setup the request
        request.setEndpoint('https://logs-01.loggly.com/inputs/'+api_key);
        request.setMethod('POST');
        request.setHeader('Content-Type', 'text/plain');

        // add tags in the header
        request.setHeader('X-LOGGLY-TAG', String.join(tags, ','));

        // put the log message in the body
        request.setBody(data);

        try {
            // send the request to Loggly
            response = http.send(request);
        } catch(System.CalloutException e) {
            System.debug('Loggly error: ' + e);
        }

        System.debug(response.toString());
    }
}

Anonymous Apex Logging

Post a sample message to Loggly.com using this anonymous apex.

List<String> tags = new List<String>{'testTag'};
LogglyService.log('Test Log Message', tags);

The post Loggly.com Logging with Salesforce.com Apex appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/salesforce/loggly-com-logging-salesforce-com-apex/feed/ 0