Trapdoor In The Sun

Alan Shanahan, Technician & Consultant


Leave a comment

Force.com: Visualforce; slightly better field declarations

Soft coded = good. Hard coded = bad. That’s difficult to argue against and I doubt there’s much dissent in any programming community.

Define it once, use it many times; this is part of the reusability principle that applies to code segments and text literals. When you define an input field in a Visualforce page, more often than not it is based on a field that exists somewhere in the database. It makes a whole lot of sense to take as many attributes from the original field definition as possible, so below are some examples of how you might do that.

(1) When defining a field on a page, prefix it with its label. Use this syntax:
$ObjectType.ObjectName__c.Fields.FieldName__c.Label
…where ObjectName__c and FieldName__c should be replaced as appropriate.

(2) Use the field’s own help text by referring to the InlineHelpText attribute, as shown below in this syntax:
$ObjectType.ObjectName__c.Fields.FieldName__c.InlineHelpText
…where ObjectName__c and FieldName__c should be replaced as appropriate.

(3) Limit the field length in HTML during data entry by using this syntax:
$ObjectType.ObjectName__c.Fields.FieldName__c.Length
…where ObjectName__c and FieldName__c should be replaced as appropriate.

<apex:pageBlock id="searchPageBlock">

	<apex:pageBlockSection columns="2"
	 id="searchPageBlockSection" title="Global Search" collapsible="false">

		<apex:pageBlockSectionItem id="searchAirport"
		 helpText="{!$ObjectType.Airport__c.Fields.Airport_Name__c.InlineHelpText}">

			<apex:outputLabel
			 value="{!$ObjectType.Airport__c.Fields.Airport_Name__c.Label}" />
			<apex:inputText
			 value="{!wrkAirportName}"
			 tabIndex="2"
			 id="inpAirportName"
			 maxlength="{!$ObjectType.Airport__c.Fields.Airport_Name__c.Length}"
			 onkeypress="return noenter(event);" />

		</apex:pageBlockSectionItem>
	</apex:pageBlockSection>
</apex:pageBlock>

The above code works well for text input fields. If you need information on numeric or other input field types check out the $ObjectType schema information page.

Advertisements


4 Comments

Force.com: Visualforce programming, position cursor at first input field

When building a custom Visualforce page with input fields, one common requirement is to place the cursor at the first input field on the page. You would think this would be a simple matter and Salesforce itself manages the task quite well. But when the platform’s default behaviour kicks in and overrides your page’s behaviour, it doesn’t always work smoothly. Or if you want to position on an input field that is not a text entry field it doesn’t always slide into place. Or perhaps you wish to show a dialog box where you wish to conditionally position the cursor to a Confirm or Cancel button depending on prior processing.

In this piece, I’m offering a foolproof way to enable your page to behave exactly as you want it to, in an easy, maintainable way. Here is the step by step way to do this.

First, download a copy of the JQuery library from jquery.com. The minimised (compressed) version is just fine.

Now, upload it to your Salesforce org as a Static Resource.

In your Visualforce page, add this line somewhere after the apex:page tag:

<apex:includeScript value="{!$Resource.JQueryJS}" />

…making sure to replace the JQueryJS text with the name you specified during the Static Resource upload step.

The code below assumes that the page is aware of a “mode” or action passed to it, perhaps as a querystring parameter and parsed separately into a variable called wrkAction.


...

	<script language="JavaScript">

	//----------------------------
	// JQuery initialisation
	//----------------------------
	j$=jQuery.noConflict();
	j$(document).ready(function() {
		initialisePage();
	});

	//-------------------------
	function initialisePage() {
	//-------------------------
		positionCursorToFirstField();
	}
	//-------------------------------------
	function positionCursorToFirstField() {
	//-------------------------------------
		if ('new' == '{!wrkAction}' || 'edit' == '{!wrkAction}' || 'copy' == '{!wrkAction}') {
			j$("[id*=':btnConfirm']").focus();
		}
		if ('del' == '{!wrkAction}') {
			j$("[id*=':btnCancel']").focus();
		}
	}
	</script>

The page buttons might be defined later in your page code, as follows:

	<apex:pageBlockButtons id="pbButtons" location="bottom">
		<apex:commandButton id="btnCancel"  value="Cancel"  immediate="true" onclick="return checkCancel();"  />
		<apex:commandButton id="btnConfirm" value="Confirm" immediate="true" onclick="return checkConfirm();" />
	</apex:pageBlockButtons>

Given that any page element will probably exist in the hierarchy of page elements, the Visualforce page is rendered with the implicit force.com naming applied i.e. the full “pathname” to the element is implied in the name, with colons separating each branch in the tree. For example, an HTML id such as j_id0:j_id1:j_id192:j_id193:j_id196:j_id230:j_id231:j_id232:4:j_id236 would not be unusual.

The above code brings a “best practice” tip to mind – always use page-unique ID values for input fields, buttons and all other page components. Specifying the ID tag also ensures that the force.com implicit naming conventions are not applied.

The JQuery code in the positionCursorToFirstField javaScript method above provides a major advantage: you are now effectively freed from having to worry about the naming hierarchy. The JQuery selector finds the field ending with a colon character followed by the specified unique fieldname. This also means you can move it around on the page and within the page element hierarchy (DOM) and not have to worry about this code failing or needing to be modified.

There’s just one more piece of code needed to ensure the force.com standard processing doesn’t happen i.e. that the platform itself doesn’t try to be too clever and preempt what you’re trying to do. This code masks the effect of the standard “first input field positioning” processing:

	<script language="JavaScript">

	//--------------------------------------------------------------------------------------------------------------
	// This empty function overrides the SFDC standard function, and enables us to control initial field positioning
	//--------------------------------------------------------------------------------------------------------------
	function setFocusOnLoad() {
	}

	</script>


Leave a comment

The Transition To Force.com Developer

This is aimed at Java and C# developers who want to move into cloud computing and create demand for their skills.

One thing I regard as vital is to constantly keep an eye on your career progression. My aim is to make myself just that little bit more employable every year. It’s tough to combine this with a busy work schedule, but just because it’s tough doesn’t mean it’s not worthwhile.

The last year has seen huge growth and even bigger projections for the future of Cloud Computing. The trends are all upward, there’s no doubt. Gartner’s recent report states that the areas of “social, mobile, big data and cloud” will experience growth as they are championed by new IT leaders. Forrester predicts patterns of growth that are also encouraging. Most pundits and industry commentators agree and many of the big players are positioning themselves along these lines.

Along with explosive sales in mobile and tablet devices, it’s clear that mobile applications (particularly those that are cloud-based) will feature strongly in a global IT context for some time to come.

Add social media to the mix and it’s clear that Salesforce.com (with its Force.com platform) has its bases well and truly covered. They’ve got Chatter; Facebook and Twitter integration is covered; Touch is their technology stack for mobile; mobile apps proliferate.

And at their heart SFDC are “Cloud”. They are pioneers in the arena, that’s an undisputed fact.

Getting down to nuts and bolts, if you’re a developer with Java or C# skills, there’s a definite path you can take to sharpen your skills to become a certified Force.com developer. If you have designs on such a career path, my advice would be to follow these lists:

Application & Configuration Skills:

  • Get yourself trained up on the (Sales Force Automation) SFA application and, optionally, get yourself a certification
  • Understand what Account, Contact, Opportunity, Pricebook, Product, Case, Lead are, and what they do
  • Understand how to use Reports & Dashboards
  • Preferably, attend at least one of the Salesforce Administrator courses
  • Learn how to configure custom objects, custom fields, page layouts, field sets, formula fields, validation rules, custom buttons & links
  • Learn about Security, Roles & Profiles, field-level security
  • Get acquainted with Workflow and Approvals, what they are, what they can do
  • Learn how to import data with the Data Import Wizard

Technical & Coding Skills:

  • Sign up for a free SFDC Developer org
  • Learn about coding on the Force.com platform: Apex Triggers & Classes, VisualForce, Components, Custom Settings, Custom Labels, Resources
  • Understand what Force.com Governor Limits are, how to apply them
  • Learn what SFDC API usage limits are and understand how they may affect any application you design
  • Learn the new coding paradigms for bulk processing (a large topic but here’s a useful starter blog post)
  • Understand Lists, Maps, Sets and when to use them to handle batches of data
  • Understand Test Classes & methods
  • Learn about Apex Batch and Scheduled jobs
  • Learn how to use the SFDC SOAP and REST APIs and Workflow Outbound Messaging options
  • Learn how to extend the API with your own custom web services
  • Understand how to process inbound emails in Apex
  • Use Eclipse and the Force.com plugin to maintain Apex & Visualforce code and to examine the database schema
  • Learn how to debug code and troubleshoot using the various tools on the Force.com platform
  • Understand all the places (or “hooks”) where you can plug into the SFDC application to customise it
  • Gain at least a cursory understanding of SControls (deprecated functionality) in case you need to modernise or maintain old applications
  • Understand how to use the Apex Data Loader
  • To help you on your way with the above, here is a link to all SFDC documentation (pay special attention to the Apex and Visualforce reference docs)

You can also take your existing skills with you, and these will be invaluable:

  • Database and application design skills
  • Data Migration skills
  • Data Integration knowledge
  • Service-Oriented Architecture (SOA) and web service knowledge
  • Industry vertical expertise
  • Test-Driven Development (TDD) strategies
  • Source code version control tools and techniques
  • Multi-developer, multi work-stream development
  • Application testing strategies & methods

You can acquire all the training resources you need with little or no cost, but you can also accelerate your ramp-up time by attending SFDC formal training courses.

Anecdotal evidence would suggest that there are at least some Java developers out there who have a reluctance to extend their knowledge into the Force.com arena, primarily because of the more restricted nature of the environment. However, if you take the plunge, the rewards are there for the taking and you’ll join a growing army of technicians with niche skills.

Don’t be too quick to assume, however, that because you can instantly read Apex code (which a Java or C/Whatever coder can), your transition will be instant – there’s a little more to it than that. Most who took that path with that outlook fell foul of platform differences, a.k.a. the famed Governor Limits. But, learning the How, When and Why of these limits will help get you to the next stage in the transition process.

Acronyms used above:

  • SFDC = SalesForceDotCom
  • API = Application Programming Interface
  • SOA = Service-Oriented Architecture
  • SOAP = Simple Object Access Protocol
  • REST = Representational State Transfer
  • TDD = Test-Driven Development