Sunday, 26 February 2012

Salesforce Certified Sales Cloud Consultant


Continuing my quest for certification, I passed the Sales Cloud Consultant exam on 23rd Feb 2012.  After the rigours of the Technical Architect exams, this felt a lot tighter in terms of scope, plus it was nice to actually receive a result at the end, rather than having to wait on tenterhooks for several weeks.

Please don't ask for or post any exam questions/answers, as this is contravenes the test taker agreement that we all sign up to at the beginning of the exam and devalues the certification.

This is a 60 question exam with 105 minutes allowed to complete and a 73% pass mark.  A few tips for the mechanics:

  1. Read the question carefully.  This is one of the wordier exams that I can remember, and if you skim read its easy to misunderstand the scenario.  More than once over the years I've caught myself choosing the option that was 100% wrong and only picking this up during a review of the questions.
  2. Some of the potential answers are flat out wrong, so even if you aren't sure of the correct answer, it may be possible to eliminate the impossible.  And as Sherlock Holmes said, when you eliminate the impossible, whatever remains, however improbable, must be the truth.
  3. I find it useful to note down questions that I'm not sure about with a percentage confidence.  This allows me to work out how I'm doing against the pass mark and not feel bad if I've got a couple of total guesses in there!
Areas that are covered are detailed in the study guide available from http://certification.salesforce.com/. The areas that I paid particular attention to were:
  • Sharing settings - this comes up on every exam.  Its vital to any implementation so its important to understand the detail regardless of whether you are getting certified or not.
  • Person accounts - not only what they add to regular accounts but what they don't, in terms of fields and related lists.
  • Account hierarchy - again, its important to understand what setting up a parent/child relationship adds (hint: not very much!)
  • Territory Management
  • Forecasting.  Simply because there's so many of them now - classic, Winter 12 and customisable.
  • Custom fiscal years - mainly around the impact of enabling this.
  • Multi-currency and advanced currency management - the impact this has on reports, dashboards and forecasting, plus which is appropriate to use for particular scenarios.
  • Opportunities, products, pricebooks and scheduling.
  • Salesforce to Salesforce
In order to revise for this exam, I used the Salesforce help and cheat sheets/FAQs available from the only help. Wherever possible I tried thing out in my developer instance.  Some things can't be tried out as they are feature activations, but there's no substitute for doing it rather than reading about it I find.  I also watched a few of the Salesforce training videos, mainly so that I could take the knowledge check at the end of each section.  Other useful resources were the Salesforce Consultant Resource Center and the question and answer deck at Study Blue.

I can't remember any questions on actual configuration of Salesforce, all those which referred to a specific configuration item were regarding the change in behaviour once the system is configured in that way.  Its important to know what business problems the Sales Cloud is solving, as a number of questions present a scenario and ask what Salesforce functionality would be appropriate.  Some questions have multiple valid answers and you are asked to choose the most appropriate - in these cases you need to be thinking about clicks not code, minimising the impact on the desired process, impact on adoption and keeping data on platform. Metrics and analytics questions cropped up fairly regularly too.  Integration and data migration have been an ever present in the exams and this was no exception.  There were a fair few questions around the Software Development Life Cycle too - more than I remember in the old CON201 exam.

When all is said and done though, there's no substitute for consultancy experience.  If you've actually been through the end to end process of gathering requirements, designing and building a solution, validating it internally and externally, setting up integration paths and migrating data from legacy systems, you'll find this quite a straightforward exam. Just remember to brush up on the aspects of implementation that you haven't carried out for a while.

Sunday, 5 February 2012

Certified Salesforce Technical Architect



This week I received an email from Salesforce Certification informing me that I'd passed the review board and obtained the Salesforce Technical Architect certification.  This post details my experience and hopefully provides some guidance for those that are considering attempting this certification.

Please don't ask for or post any exam questions/answers, as this is contravenes the test taker agreement that we all sign up to at the beginning of the exam and devalues the certification.

I participated in the beta of this exam for the first two stages, so things may have moved on a little.

There are three parts to the certification:

1. Self Assessment

This is a questionnaire in which you rate your experience with various technologies, both on and off Salesforce platform.  Some of the items I rated myself on didn't feature again (e.g. JQuery).  The most important thing here is to be honest about your abilities.  The second and third parts of the exam are tough, so if you claim experience that you don't have, you are likely to be quickly found out.

2. Multiple Choice

After clearing the self-assessment, next up is the multiple choice.  This is 60 questions over 2 hours, which gives a clue as to the level of detail in the questions and answers - the beta had 139 questions over 4 hours, so it could be worse.  Like the cloud consultant exams, many questions had answers that were all correct, but you had to pick the best practice, and there were only a handful of questions where I felt that the answer was obvious if you had worked in that area.

Unfortunately for me, the study guide wasn't released at the time that I took the exam, so I only had the description of the exam to work from when deciding what to revise.  The thing that really surprised me about this exam was how little actual Salesforce knowledge was tested - a lot of the questions were around how Salesforce could integrate with other systems.

3. The Review Board

The next step is the review board. This requires a significant investment - $6,000 - which increases the pressure to pass!  While it sounds like a lot of money, there are 8-9 people involved in the review board for the best part of half a day, so its easy to see how the costs mount up.

Prior to the actual event, you have to produce a case study of a real-life customer implementation that you have architected.  The study guide recommends at last 10 hours, but I'd say I spent easily twice that, mainly because I kept changing my mind about what needed to be in there.

The certification packet you get sent when you book the review board indicates the areas that you need to cover, but only at a very high level so choosing which details to leave in or out takes some thought.

Something to bear in mind for this is that you will have 30 minutes to present it to the review board.  While that sounds like a lot, once you get into your stride and start talking around the points in the presentation it quickly gets eaten up, and the most useful piece of advice I can give you here is to dry run the presentation a few times to check your timings and learn your lines.  I really struggled to keep to 30 minutes, and in my first couple of attempts ended up hurtling through the final 10 slides or so and having to speak at an incredibly fast rate.  I'd suggest that 30 slides is the maximum that you can use if you are intending to have a reasonable amount of information on each.  The next key piece of advice is that if you put something into this presentation, you had better be prepared to drill into it in great detail.

The review board was being run out of San Francisco, but unfortunately I couldn't swing a trip out there so I had to take part remotely via a web session.  Handily enough we do quite a lot of webinars with our customers so this was quite a familiar environment for me.  The review board is made up of subject matter experts and technical architects from Salesforce and the wider community.

The review board is a 4 hour session, broken down into 5 parts:
  1. First you are given a hypothetical scenario with a current architecture landscape and set of business requirements, and you have to architect/design a solution and produce a presentation  in 75 minutes.  At first glance, 75 minutes sounds like a lot of time, but the time flew by.  The   scenario was a lot more complex than I had anticipated and it was quite a struggle to cover everything.
  2. You then have 30 minutes uninterrupted to present your solution to the review board.  If you don't utilise the full 30 minutes this gets added to the next section.  I only used 22 minutes and learned a valuable lesson the hard way!
  3. Next the review board has 30 minutes (plus any time you didn't utilise from the previous section) to question you on your solution in an interview format. This is the toughest part by far - you are already likely to be rattled from trying to produce the solution design in quite a short amount of
    time, and you'll no doubt have started questioning yourself while presenting it.  Once the experts start drilling down into the detail it can become a real test of character.  Apparently there have been candidates that have been very nervous during their presentation and have then been too nervous to answer questions - I'd imagine this applies to candidates who weren't really ready from an experience perspective and had relied on memorising information.

    Its not a hostile or unpleasant environment, but you will be expected to speak to quite a level of detail across a number of technological aspects, and if you don't give enough detail the questions will keep coming!  This 38 minutes seemed to last an awful long time.
  4. After a short break, you then have another uninterrupted 30 minutes to present your case study that you have prepared in advance.  The difficulty here is to lift yourself after the previous session and not to dwell on any mistakes you feel you've made earlier.  This is where the rehearsal can stand you in good stead, as you should know this material like the back of your hand.  Learning from part iii I took 29 minutes and 52 seconds by my stopwatch, thus only giving the board an additional 8 seconds to quiz me!

  5. Finally, another Q and A session on your case study.  This covers a lot of the wider aspects of the Technical Architect role, so you'll need to be prepared to talk about things like the development methodology, testing strategies, project governance, interaction with project stakeholders and the wider business users.  My preparation really paid off here and as far as I recall I was able to answer pretty much all of the questions to quite a level of detail.  This final section flew by and I was quite surprised when the board indicated they had no further questions.
I really had no idea how I'd done at the review board - its quite intense and reactive, so its difficult to judge your own performance.  Another key piece of advice here is to ensure some of your colleagues are waiting to buy you a beer straight afterwards!  
 
I realise I'm making this sound like a really tough experience and that is because it was.  I don't feel I could have been much more prepared but it was still a real challenge, so if you are going in underprepared or lacking experience you really aren't going to find it much fun.  This is as it should be of course - this is the highest level of certification so it shouldn't be easy.
 
After the review board its a wait of up to 4 weeks to hear the results - I received my results in just under 2 weeks and I was rather pleased to pass to say the least.
 
Areas that you need to know are:
  • Integration - the various APIs that Salesforce has and when it is appropriate to use each one
  • Clicks versus code - the pros and cons of each and which is appropriate to use for a given scenario
  • Identity management - the various types of single sign-on that can be utilised with Salesforce, user provisioning and if there are any caveats around sites/portal access
  • Multiple org versus single org - again, pros and cons, which to use for a give scenario and also elements that may push you towards multi org having started out in a single org
  • Large data volumes - techniques for handling large volumes of data from a migration, integration and analytics perspective
  • Mobile and desktop access
  • Agile versus waterfall development methodologies
  • Design patterns
  • Project governance
  • Stakeholder management
  • Testing strategies
  • Deployment strategies
  • Change management
  • Portal options - customer, partner, Force.com sites, Siteforce and Heroku.  Again, the pros and cons, which is the better fit, license restrictions and cost
  • Security and privacy - from a number of perspectives, e.g. technical configuration details, benefits of certifications, physical versus logical, firewalls, DMZs, proxies and reverse proxies
  • Performance and scalability
  • General architecture concepts - a lot of the time Salesforce will be one component in an architecture, so you'll need to know what is a good fit for Salesforce and what needs to be in an external system
Q & A
 
Q. Can you please share links for the preparation of exam specially relating to integration and SSO topics.
A. The best resource for SSO I've found is the Developerforce Consultant Resource Center page at: http://wiki.developerforce.com/page/CRC:SSO (This link is now defunct).
The Developerforce Technical Library is a good starting point. Here are some links to this:
Q. When your results came back to you, did the review board give you any feedback?
A. Yes, you do get feedback.  There are around 12 areas and you get told what you were strong on and what you need to work on.

If you have any questions on this, please post them into the comments section below and I'll add them to this section.  

 

Saturday, 28 January 2012

Record Type Specific Picklist Values

This post is my solution to an issue that seems to have been around for a while - how to get at the picklist values for a particular record type programmatically.  I've been working on a JavaScript chart (using my framework of choice for charting - Dojo) that will show how far through the sales process an opportunity is.

Initially I was using the describe capability for the StageName field, which worked fine for a single record type. However, as soon as I introduced multiple opportunity record types with different sales processes, I hit problems - regardless of the sales process, the full set of picklist values was returned each time, even if I navigated to the field via an opportunity with the appropriate record type.  Some googling and searching on the Developerforce discussion boards seemed to confirm that there isn't a simple way to achieve this.

Clearly the information about which stages are applicable to a record type is available to the Salesforce UI, as the Stage picklist contains the values specific to the record type.  Even better, this is respected when using a Visualforce input field.  Therefore one way of getting at this information for use in a Visualforce controller is to have the page supply it.  Utilizing a technique I've written about before in DML During Initialisation, I created a page that would send the picklist values back to the controller the first time it was loaded, and then display the details thereafter.

The first time that the page is loaded the following outputpanel is rendered:

   <apex:outputPanel rendered="{!loadonce}">
      <apex:form id="frm">
         <apex:actionFunction name="reloadWithStages" action="{!reload}"/>
         <div id="test1" style="width: 100%; height: 150px;"></div> 
         <apex:outputPanel layout="block" id="vals" style="display:none">
            <apex:inputField value="{!Opportunity.StageName}" required="false" id="stages"/>
            <apex:inputText value="{!valsText}" required="false" id="back"/>
         </apex:outputPanel>
      </apex:form>
      <script>
         function reload()
         {
            var ele=document.getElementById('{!$Component.frm.stages}');
            var idx=0;
            var valText='';
            for (idx=0; idx<ele.length; idx++)
            {
               valText+=ele.options[idx].text + ':';
            }
   
            var backele=document.getElementById('{!$Component.frm.back}');
            backele.value=valText;
 
            reloadWithStages();
         }

         window.onload=reload(); 
      </script>
   </apex:outputPanel>
   

This contains a hidden form with an inputfield for the opportunity stage and an input text element that will be used to submit the stage options to the controller. The reload() function is installed as an onload handler, and this extracts the option text, concatenates it into a single string value, populates the input text with this string and then submits the form.
When the page is reloaded, the following outputpanel is rendered - this simply creates a pageblocktable to iterate through the available values:

   <apex:outputPanel rendered="{!NOT(loadonce)}">
      <apex:pageBlock title="Status Values for record type {!Opportunity.RecordType.Name}">
         <apex:pageBlockTable value="{!pickListVals}" var="plVal">
            <apex:column headerValue="Stage">
               <apex:outputText value="{!plVal}"/>
            </apex:column>
         </apex:pageBlockTable>
   </apex:pageBlock>
   </apex:outputPanel>

The controller is shown below - the heavy lifting is done by the reload() method - this parses the string containing the picklist values and stores them in a list property. it also sets the loadonce property to false, to ensure that the page is reloaded once and once only:

public with sharing class RecordTypePickListController 
{
 public List<String> pickListVals {get; set;}
 public String valsText {get; set;}
 public Boolean loadOnce {get; set;}
 private Opportunity opp;
 
 public RecordTypePickListController(ApexPages.StandardController std)
 {
  opp=(Opportunity) std.getRecord();
  loadOnce=true;
 }
 
 public PageReference reload()
 {
  pickListVals=new List<String>();
  Boolean skip=true;
  for (String val : valsText.split(':'))
  {
   if (skip)
   {
    skip=false;
   }
   else
   {
    pickListVals.add(val);
   }
  }

  loadOnce=false;
  
  return null;
 }
}


Here are a couple of screenshots of the page doing its thing for opportunities with two different record types.  The first with just a few of the stages:


and the second with most of them:



For the sake of completeness, the entire page is shown below:

<apex:page standardController="Opportunity" extensions="RecordTypePickListController">

   <apex:outputPanel rendered="{!loadonce}">
      <apex:form id="frm">
         <apex:actionFunction name="reloadWithStages" action="{!reload}"/>
         <div id="test1" style="width: 100%; height: 150px;"></div> 
         <apex:outputPanel layout="block" id="vals" style="display:none">
            <apex:inputField value="{!Opportunity.StageName}" required="false" id="stages"/>
            <apex:inputText value="{!valsText}" required="false" id="back"/>
         </apex:outputPanel>
      </apex:form>
      <script>
         function reload()
         {
            var ele=document.getElementById('{!$Component.frm.stages}');
            var idx=0;
            var valText='';
            for (idx=0; idx<ele.length; idx++)
            {
               valText+=ele.options[idx].text + ':';
            }
   
            var backele=document.getElementById('{!$Component.frm.back}');
            backele.value=valText;
 
            reloadWithStages();
         }

         window.onload=reload(); 
      </script>
   </apex:outputPanel>
   
   <apex:outputPanel rendered="{!NOT(loadonce)}">
      <apex:pageBlock title="Status Values for record type {!Opportunity.RecordType.Name}">
         <apex:pageBlockTable value="{!pickListVals}" var="plVal">
            <apex:column headerValue="Stage">
               <apex:outputText value="{!plVal}"/>
            </apex:column>
         </apex:pageBlockTable>
   </apex:pageBlock>
   </apex:outputPanel>
</apex:page>

And a special thanks to the blogger software error that meant I had to write this post twice! Always save at regular intervals.

Sunday, 11 December 2011

Advanced Developer Certification Q&A

A slight departure this week - I've received a number of questions through different channels regard the Advanced Developer Certification exam.  Rather than answering these point to point I thought I'd create living blog entry that gets updated as new questions come through and spread the knowledge out a bit.  Feel free to post further questions in the comments section - I'll then uplift them into the main post with an answer (if I have one!), so don't be surprised if a comment gets deleted!

I can't go into specifics of the actual exam questions or assignment subject, as this is contravenes the test taker agreement that we all sign up to at the beginning of the exam.  Outside of that I'll do my best to answer.


Q. What not to study for multiple choice exam. There are topics like salesforce mobile, apex chart, visual workflow these are not specified in study guide so can I ignore these topics?
A. I don't remember any questions that were not based on GA features. I did make sure that I was familiar with the information on the beta/pilot features that were available, but mainly from reading the release notes and developers guide.

Q. From start to end, ie appearing for 1st exam to receiving the result whats the total duration it took for you?
A. Just over 6 months, but some of that was waiting. I took the first exam around the middle of May, but then had to wait until September for a chance to sit the assignment. There's around 1 month to complete the assignment, and then a 6-7 week wait for the results.

Q. If somebody fails in programming assignment than he/she has appear again for multiple choice again?
A. I'm not 100% sure, but I believe that you can retake the programming assignment without having to retake the multiple-choice exam. This is based on comments from someone on LinkedIn though, so it would be better to check this with the certification team from Salesforce

Q. The 20 hrs of timeline is actually restricted to 20 hrs by monitoring login time or you can take more time and login to sandbox/production anytime for your assignment?
A. No, it was made clear that 20 hours was the suggested minimum amount of time it would take you to complete the assignment, there was no mention of any upper limit. I recorded around 28 hours, although some of that was researching and building the QA scripts.

Q. Any tips apart from the blog post?
A. The multiple choice exam is a little different from others I've taken - the questions tended to be a lot longer (including code snippets in the main), so there was more to understand and take in. More knowledge of reference material was required (e.g. triggers and order of execution, standard component attributes). Aside from that, the usual tips of ruling out any obviously wrong answers to narrow down the opportunities, making sure that you read the questions and answers properly.

Q. When is the next registration window for the programming assignment?
A. According to Nina Marinova on Linked In, the assignment window opens Dec 21.  Full details at: bit.ly/sXmySO
Update - the registration for the assignment was full in a few hours this time.  All the more reason to ensure you are following salesforce certification on linked in, facebook and twitter.

Saturday, 3 December 2011

Certified Force.com Advanced Developer

As of 3rd December 2011 I'm a Certified Force.com Advanced Developer! This post gives an overview of the exam and a few tips to hopefully assist others.  Please don't ask for or post any exam questions/answers, as this is contravenes the test taker agreement that we all sign up to at the beginning of the exam and devalues the certification.


The first step is to join the Salesforce.com Certified Professionals group on Linked In.  This is where a lot of information around the exams is disseminated (the assignment registration windows, for example) and the Salesforce certification team often comment in the discussions around test taking.

You'll need to know the following documents intimately:
  • Force.com Apex Code Developer's Guide
  • Visualforce Developer's Guide
I also made sure I had a broad understanding of the following - not so much to know them inside out, but when each particular one should be used:
  • Web Service API
  • Metadata API
  • Force.com Migration Too

There are three parts to the exam - multiple choice, programming assignment and essay.

Multiple Choice

This is an online proctored exam lasting up to 2 hours. There are 69 Questions and the pass rate is 73%, which means that you need to get just over 50 of the answers right.  This is different to most of the other exams that I've taken, in that you needed to know reference material in detail (e.g. triggers and orders of execution), plus there was a lot more to take in for the scenarios for most questions.

One thing I found particularly useful was the amount of time that I spend on the Developerforce Discussion boards - being able to quickly comprehend unfamiliar code and spot errors is a definite advantage.

Programming Assignment

After passing the multiple choice, you the have the opportunity to register for the programming assignment. Assignments are available several times a year, but spaces are limited, so my advice would be keep your eyes peeled for the announcement that the window is open and register immediately.  The last window was open for around 6 days and fully subscribed in 48 hours.

Assuming you are successful in registering, you'll receive the assignment requirements.  They are very detailed and give you clear instructions as to what you need to focus on and what you shouldn't waste time on as you'll gain no extra marks.  The assignments have a deadline date, but you don't have to wait until that date to submit it if you are finished in advance.

The recommendation is to spend 20 hours on the assignment. I spent more than this, initially on research to check the approach that I was using was the correct one (in my opinion at least!) and the rest on revisiting my unit tests as other scenarios occurred to me. I find that once I start coding unit tests it's difficult to stop!

I approached this as I would any customer project:
  • Read the specs carefully and understand the requirements
  • Produce a design
  •  Implement the solution and unit tests
  • Write a formal QA plan to cover all of the scenarios mentioned in the specs, plus as many others as I can think of, paying attention to security and scalability.
  • Use the system for some real-world scenarios
Development is carried out in a sandbox and deployed to production.  If the deadline is around one of the three release windows for Salesforce, its best to allow plenty of time for deployment, as this can be fragile once sandboxes and production are at different versions, as I've covered before in one of my earlier posts.

Once you are happy with the assignment, you notify Salesforce that it is ready for assessment and proceed to the final component of the exam.

Essay

The essay portion of the exam is also online proctored and has an allotted time of 1 hour.  Its important to stay focused for this exam - I found myself writing long paragraphs on the actual code I'd written, which I ended up deleting as it wasn't really relevant to the question.

While an essay exam sounds intimidating, you can expect questions that ask you to explain your approach, how you handled particular requirements and what compromises were made, so as long as you've taken the assignment seriously it shouldn't be a problem.  It is possible that the essay questions will make you think of something that you've missed, in which case you have the opportunity to try to come up with a plausible explanation as part of the answer.

The cynical side of me says that the essay questions are to ensure that whoever has submitted the project has actually written it, and isn't simply riding off other peoples's efforts.


Once this is done, there's a wait of around 6 weeks before the results get sent out.

Saturday, 26 November 2011

Retrieve Related Object Fields

A short post this week, again based on a question from the DeveloperForce Visualforce Discussion Board regarding the retrieval of a related objects fields.  In this particular case, an sobject is being created/edited via Visualforce and once a lookup field is populated, the developer wanted to display some fields related to the lookup.

Unsurprisingly, simply adding some outputfields for the  related object as shown below doesn't do the trick:


<apex:page standardcontroller="Contact">
 <apex:form >
   <apex:pageBlock title="Contact Create/Edit">
      <apex:pageBlockSection title="Contact Information">
       <apex:inputField value="{!contact.FirstName}"/>
       <apex:inputField value="{!contact.LastName}"/>
      </apex:pageBlockSection>
      <apex:pageBlockSection title="Account Information">
       <apex:inputField value="{!contact.AccountId}"/>
       <apex:outputField value="{!contact.Account.AccountNumber}"/>
       <apex:outputField value="{!contact.Account.Site}"/>
      </apex:pageBlockSection>
   </apex:pageBlock>
  </apex:form>
</apex:page>

Once the lookup is selected, the outputfield values remain empty, as all that has been specified is the id of the account via the inputfield - the related object details aren't populated in the sobject graph, so attempting to traverse the account relationship doesn't bring back any data:



One way to get the information back would be to save the contact once the lookup is populated and carry out a client side redirect to the current page with the id of the newly created contact.  When the standard controller retrieves the new sobject, it will populate the related Account information automatically.  This isn't a great user experience though, as the save is likely to be well before the user is ready, and doesn't give them a chance to change their mind part way through.  Likely to lead to a lot of unwanted and half-populated contacts.

Therefore it looks like an extension controller is the route to go. The page has been updated with an actionsupport component that is attached to the account lookup. This invokes an action method on the extension controller which executes a SOQL query to populate the related account information.

Revised Page:

<apex:page standardcontroller="Contact" extensions="RelatedController">
 <apex:form >
   <apex:pageMessages id="msgs"/>
   <apex:pageBlock title="Contact Create/Edit">
      <apex:pageBlockSection title="Contact Information">
       <apex:inputField value="{!contact.FirstName}"/>
       <apex:inputField value="{!contact.LastName}"/>
      </apex:pageBlockSection>
       <apex:actionRegion >
          <apex:pageBlockSection id="accinfo" title="Account Information">
         <apex:inputField value="{!contact.AccountId}">
            <apex:actionSupport event="onchange" action="{!AccountPopulated}" rerender="accinfo, msgs"/> 
         </apex:inputField>
         <apex:outputField value="{!contact.Account.AccountNumber}"/>
         <apex:outputField value="{!contact.Account.Site}"/>
        </apex:pageBlockSection>
      </apex:actionRegion>
      <apex:pageBlockButtons >
        <apex:commandButton value="Cancel" action="{!cancel}"/>
        <apex:commandButton value="Save" action="{!save}"/>
      </apex:pageBlockButtons>
   </apex:pageBlock>
  </apex:form>
</apex:page>

Extension controller:

public with sharing class RelatedController 
{
 private ApexPages.StandardController stdCtrl;
 
 public RelatedController(ApexPages.StandardController std)
 {
  stdCtrl=std;
 }
 
 public void AccountPopulated()
 {
  Contact cont=(Contact) stdCtrl.getRecord();
  cont.Account=[select AccountNumber, Site from Account where id=:cont.AccountId];
 }
}
Choosing the account now carries out an Ajax request and rerenders the account information with the fields populated.


Also, as I've been able to write the information into the object relationship, its the same markup that renders the account information regardless of whether it was retrieved via my extension controller or via the standard controller "reflection" when the page is opened with a specified contact id.

Finally, a word of advice - if you are writing an extension controller for this purpose, make sure that the related object has some data present in the fields, otherwise you'll be convinced your code is failing when in fact its working perfectly, just rendering empty fields!

Saturday, 19 November 2011

Bypass Validation Rules from Apex

Today's post concerns a topic that crops up pretty frequently on the Developerforce Discussion Boards - how to allow apex code to bypass validation rules.

In  my example scenario, I've created a validation rule against the Contact standard object that checks either the contact's email address or phone number has been provided:

Thus when I attempt to create a Contact via the UI, if I don't provide one of these pieces of information I receive an error message:


All well and good.  However, what about the situation where I am creating a Contact programmatically? In this case the validation rule is still applied:


Obviously creating via the system log is a contrived example, but in practice I may be receiving the details from an external system as part of an integration (via an apex web service) or data migration (via the Apex Data Loader), and the information may simply not be available in that system.  If its a data migration, I could  disable the validation rule for the duration, but if its a real-time integration that isn't an option.

The solution I came up with was to provide a mechanism for the record itself to indicate how it was being created/edited and to take that into account for in the validation rule.

The first step in the solution is to create a new custom field on the Contact object - a checkbox that if set to true indicates the record is being processed in an apex context.  This checkbox is not made available on any page layouts, as we don't want regular UI users to be able to check it.


Next, change the validation rule to allow both the email and phone fields to be empty if the apex context field is set to true:


Its tempting at this time to think that the problem is now solved - the Apex Context field can simply be set to true and the validation rule will allow the record through.  However, the record will then be saved to the database with the Apex Content field set to true, and the next time that a user edits the record in the UI, the validation rule will be bypassed - not the behaviour I am looking for.  Therefore I've created a workflow rule and associated field update to unset the checkbox whenever it is found to be set.

Workflow rule:


Field update:


and that's all there is to it.  Now I can create a contact via the system log without providing the email or phone field:


But if I then navigate to that contact via the UI and attempt to edit the record without providing these fields, the validation rule blocks this: