SlideShare a Scribd company logo
S-Controls for Dummies Chris Sommers, Salesforce.com Senior Sales Engineer, Global Enterprise Accounts Track: Enterprise Edition Administrators
Safe Harbor Statement “ Safe harbor” statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements the achievement of which involves risks, uncertainties and assumptions. If any such risks or uncertainties materialize or if any of the assumptions proves incorrect, our results could differ materially from the results expressed or implied by the forward-looking statements we make.  All statements other than statements of historical fact could be deemed forward-looking, including any projections of subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include - but are not limited to - risks associated with the integration of Sendia Corporation’s technology, operations, infrastructure and personnel with ours; unexpected costs or delays incurred in integrating Sendia with salesforce.com, which could adversely affect our operating results and rate of growth; any unknown errors or limitations in the Sendia technology; any third party intellectual property claims arising from the Sendia technology; customer and partner acceptance and deployment of the AppExchange and AppExchange Mobile platforms; interruptions or delays in our service or our Web hosting; our new business model; breach of our security measures; possible fluctuations in our operating results and rate of growth; the emerging market in which we operate; our relatively limited operating history; our ability to hire, retain and motivate our employees and manage our growth; competition; our ability to continue to release and gain customer acceptance of new and improved versions of our CRM service; unanticipated changes in our effective tax rate; fluctuations in the number of shares outstanding; the price of such shares; foreign currency exchange rates and interest rates. Further information on these and other factors that could affect our financial results is included in the reports on Forms 10-K, 10-Q and 8-K and in other filings we make with the Securities and Exchange Commission from time to time, including our Form 10-K for the fiscal year ended January 31, 2006. These documents are available on the SEC Filings section of the Investor Information section of our website at  www.salesforce.com /investor . Any unreleased services or features referenced in this or other press releases or public statements are not currently available and may not be delivered on time or at all.  Customers who purchase our services should make purchase decisions based upon features that are currently available.  Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements, except as required by law.
Agenda What are S-Controls? When to use S-Controls S-Controls Techniques & Examples AJAX Introduction Examples and Resources Take Home Exercises
What are Custom S-Controls? Light-weight web applications/tools hosted by salesforce.com and executed on the client browser An s-control can contain any type of content that can be displayed or run in a browser Java Applet ActiveX Control HTML / JavaScript / AJAX S-Controls are activated via Custom Links, Web Tabs, Web Apps or HYPERLINK custom formulae fields in salesforce.com (after 4 th  Quarter release, executable in Detail Pages of records, and Custom Buttons)
S-Control Options No back-office access State persistence Versioning issues IE Specific COM calling COM ActiveX Java Applet JSP / ASP AJAX Rich UI Can be “trusted” Tricky deployment eg. Salesforce.com Mail Merge Rich UI Can be “trusted” Cross-browser JVM versioning SOAP stack deployment Large footprint Java developer Rich UI Good access to internal systems Familiar dev environment Need a hosting stack Expensive development Packaging and sharing is difficult Pretty rich UI Simple API access Asynchronous Familiar html environment Javascript / cross-browser Quick and easy cycle Easy to package and share
When to Use Custom S-controls (Value!) Consider using Custom S-controls if you…  Want to enhance the Salesforce UI streamline a process reduce number of clicks Know that your process flow is closed loop, i.e., no outside databases or data sources Have less than 500 records to create or update per session Have few means to host a custom web application yourself
User Interface Enhancement Add your own UI Advanced Capabilities (trees, graphs etc) Build Custom Logic Client-side Workflow (wizard) “Mass” Change to records When to Use Custom S-controls
When NOT to Use Custom S-controls Do NOT use Custom S-controls if you…  Are looking to build heavy-weight, computationally intensive extensions to Salesforce Are seeking a complex integrate with a system external to Salesforce.com (simple web-service and HTTP post/get will work!) Have more than 500 records to create or update per session
Example: Pre-populate / create records in  One Click What:  One-click creation of a record Why:  Efficiency, user adoption Value:  Simplicity, adoption, data quality Example:   One click to log a case (eg. Password Reset)   Create a Custom Link on a Contact page to create a Case and prepopulate the fields (and save) How:  In the app, from a Contact, click on “New Case”.  Copy the URL – this is your web link BASE. https://na1.salesforce.com/500/e?retURL=%2F0033000000M1lut&def_contact_id=0033000000M1lut
Log Password Reset Case Tip: After Winter ’07 Launch, use a Custom Button Instead
Example: Pre-populate / create records Remove everything up to and including the “.com” Need to make it server agnostic /500/e?retURL=%2F{!Contact_ID}&def_contact_id= {!Contact_ID}&cas14=Password%20Reset&cas11=Phone&save=1 retURL is the page to which user should return after completing action “ 003…” is the Contact ID.  Replace this with merge field: “{!Contact_ID}” Replace the second Contact ID with the same {!Contact_ID}  Continue building out parameters View the page source, or use Form View in Firefox Web Developer to get the “name” of the fields you wish to pre-populate eg. Case Subject is “cas14”, Case Origin is “cas11”
Preventing Double-Tabbing <script language=&quot;Javascript&quot;> function redirect() { parent.frames .location.replace('/500/e?retURL=%2F{!Contact_ID} &def_contact_id={!Contact_ID}&cas14=Password%20Reset &cas11=Phone&save=1'); } redirect(); </script>
Example: Parameterize Reports What:  One-click dynamic generation of a report Why:  Efficiency, scalability Value:  Simplicity Example:   Generate a report dynamically passing filters Tip: After Winter ’07 Launch, use a Custom Button Instead
Example: Parameterize Reports How:   Create a report, filter by desired field Copy the report URL Create a Custom Link on the entity In the custom link URL box, paste in the report URL  At the end of this URL string add the following text: ?pv0=[MERGE_FIELD] Eg. /00O30000001D5tZ?pv0={!Account_Name} Use pv0 if your criteria filter is in position 1 in your report, pv1 if it is in the 2 nd  position, and so on
AJAX What:   A synchronous  J avascript  A nd  X ML Why:  Rapid Software, Component Development Value:  Adoption, low cost Example:  Mass  Update Contact Addresses Before AJAX With AJAX
The AJAX Toolkit  – Object Model
SforceClient Method Summary QueryMore  (queryLocator, callback)    QueryResult Query  (soql, callback)    QueryResult Login  (userName, password, callback)    LoginResult Init  (sessId, serverUrl)   void   GetUserInfo  (callback)    GetUserInfoResult   GetUpdated  (objectType, startDate, endDate, callback)    GetUpdatedResult   getSessionId  ()    String   getServerUrl  ()    String   GetServerTimestamp  (callback)    GetServerTimestampResult   GetDeleted  (objectType, startDate, endDate, callback)    GetDeletedResult DescribeTabs  (callback)    DescribeTabSetResult[] DescribeSObject  (objectType, callback)   DescribeSObjectResult DescribeLayout  (objectType, callback)   DescribeLayoutResult   DescribeGlobal  (callback)    DescribeGlobalResult Delete  (ids, callback)    SaveResult[] debugMessage  (msg)                void   Create  (objects, callback)    SaveResult[] ConvertLead  (leadConverts, callback)    ConvertLeadResult[] Update  (objects, callback)    SaveResult[] timingDebugClear  ()                void   timingDebug  (msg)                void   setTimingDebugger  (textarea)    void   setSessionId  (sid)   void   setServerUrl  (newurl)   void   SetPassword  (userId, password, callback)    SetPasswordResult setDebugContainer  (container)    void   setBatchSize  (size)    void   SendRequest2  (soapMessage, handler, operation, url)    void   Search  (searchString, callback)    SearchResult Retrieve  (fieldList, objectType, idArray, callback)    SObject[] ResetPassword  (userId, callback)    ResetPasswordResult
SforceClient https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js Dynamic SObject - DynaBean S-Control Context and Merge Fields Common Functions: Query Call Retrieve Create Call Update Call Delete Call Save Call AJAX - Key Components
sForceClient Within the <head> section: <script src=&quot;https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js&quot; type=&quot;text/javascript&quot;></script> Instantiated on script inclusion sforceClient.init(&quot;{!API_Session_ID}&quot;, &quot;{!API_Partner_Server_URL_70}&quot;);  Call sforceClient.init or sforceClient.Login sforceClient.init(&quot;{!API_Session_ID}&quot;, &quot;{!API_Partner_Server_URL_70}&quot;);
Dynamic SObject - Dynabean Uses a single object  - a Dynabean - to represent every available “table” in the database  Dynabean is a dynamic object that contains both data and metadata that determines its character Example:   var myLead =  new Sforce.Dynabean(“Lead&quot;) myLead.set(“FirstName”, “Stan”); myLead.set(“LastName”, “Lee”); myLead.set(“Company”, “ABC Company”); var saveResult = sforceClient.Create(myLead)[0];
Query Call Example: var queryResult =sforceClient.Query(&quot;Select BillingCity, BillingCountry, from Account Where Id = '&quot; + accId + &quot;'&quot;);  var address = queryResult.records[0]; var BillingCity = address.BillingCity;  var BillingCountry = address.get(“BillingCountry”);
Example: Close Opportunity, Create Order and Order Items What:  In one click from an Opportunity, need to: Close Opportunity Create Contract Create Order with Contract Reference Copy Opportunity Products to Order Items Why:  Too many clicks without, poor user-experience Value:  Minimizes user error, improves data quality and  user satisfaction
Example: Search First, Create What:  Enforce that users search for existing data before creating new records Custom Web Tab (today) Override Standard “New” button after Winter ’07 Use search parameters to populate new records if desired Why:  Cleaner data – NO DUPLICATES Value:  Minimizes duplicates/improves data quality and  user satisfaction
Create Call var accounts = new Array(); accounts[0] =  new Sforce.Dynabean  (&quot;Account&quot;); accounts[0].set(&quot;Name&quot;, &quot;test1&quot;); accounts[1] =  new Sforce.Dynabean  (&quot;Account&quot;); accounts[1].set(&quot;Name&quot;, &quot;test2&quot;); var rc = sforceClient.Create(accounts); if (dltypeof(rc) == &quot;array&quot;) { // do something with the returned created ids } else { alert( rc.toString() ); }
Update Call accs[0] =  new Sforce.Dynabean  (&quot;Account&quot;); accs[0].set(&quot;Id&quot;, “{!Account_ID}&quot;); accs[0].set(&quot;Name&quot;, &quot;test Updated&quot;); var sr = sforceClient.Update(accs); …… var qr =sforceClient.Query(&quot;Select Id, MailingCountry from Contact Where AccountId = '&quot; + accId + &quot;'&quot;);  var updateObjects = new Array(); for (var i=0;i<qr.records.length;i++){ var contact = qr.records[i]; contact.set(&quot; MailingCountry “, “United Kingdom”); // push updated record into new array for update process updateObjects.push(contact); } var saveResults = sforceClient.Update(updateObjects);
Delete Call var accounts = new Array(); accounts[0] = new DynaBean(&quot;Account&quot;); accounts[0].set(&quot;Name&quot;, &quot;test&quot;); var sr = sforceClient.Create([accounts])[0];  var dr = sforceClient.Delete([sr[0].id]); if (dltypeof(dr) == &quot;array&quot;) { for (var i=0;i<dr.length;i++) { alert( dr[i].toString()); } } else { alert( dr[i].toString()); }
Calling an S-Control using HYPERLINK field For HYPERLINK custom formulae fields or for calling an scontrol from another scontrol Create a Custom Link as usual Add to page layout View record and right click on link-properties and copy the url section: /servlet/servlet.Integration?lid=00b30000000hXeL&eid=00130000005YmJ5  lid = s-control id and eid = context entity record Replace the hard coded eid with the id of the current record
Tools and Techniques Development Environment Text editor (Wordpad, 1 st  Page 2000, Ultraedit) Eclipse (javascript specific plugins) Visual Studio .NET Other standard IDEs Debugging MS Script Debugger (ok) Visual Studio .NET (best) Mozilla/Venkman Debugger (ok) Mozilla Javascript Console
Tools and Techniques Recommend installing Firefox and then adding the following extensions: Web Developer 0.9.3 JavaScript Debugger 0.9.84 View Rendered Source 1.0.01 Test with IE and Firefox. Handle cross browser exceptions Firefox doesn’t allow cross site scripting Firefox is stricter on language semantics Firefox better for debugging
Techniques - Debugging Debugging support in the toolkit setDebugContainer(element) sforceClient.setDebugContainer(document.getElementById(“mydiv”); sforeceClient.setDebugContainer(document.getElementById(“myTextArea”); sforceClient.debugMessage(“This is a point in the script.”); setMessageLog(textArea) Displays the SOAP requests and responses setTimingDebugger(textArea) displays the elapsed time to execute a method. Javascript alert statement alert(“Error message = “+error); Debugger / output to the Javascript console
Passing parameters to an S-Control Yes: if the scontrol is called via HYPERLINK in a custom formulae field, YES, this is possible No: if the scontrol is called via a Custom Link or Web Tab Yes: within an scontrol additional parameters can be added to the URI for a call to a second scontrol HYPERLINK(&quot;/servlet/servlet.Integration?lid=01N3000000009KE&eid=&quot; & {!Id} & &quot;&address=billing&quot;, &quot;Test Link&quot;) eid parameter can be accessed in the s-control to get the current entity context record if needed
Other (Non AJAX) S-Controls Techniques Parameterise Reports Pre-populate / create records Preventing double tabbing on salesforce.com web links Manipulating return urls and page chaining Calling an S-Control Passing parameters to an S-Control Style Sheets – Replicating salesforce.com look and feel Standalone AJAX application  Calling s-controls on home page HTML components
Style Sheets – Replicating salesforce.com look and feel Different style sheets per language and for ‘Salesforce Classic’ and the new interface Need to pickup the right style sheet to maintain look and feel within the scontrol userUiSkin returns a value indicating the CSS path that should be specified  Salesforce1: /dCSS/Theme1/en/common.css Salesforce2: /dCSS/Theme2/en/common.css common.css should be the only file you need to use to replicate the salesforce.com's look and feel. For full details see tech note   http://www.sforce.com/resources/tn-16.jsp
Standalone AJAX application Use divs to present / hide a login screen Call  sforceClient.Login(“username@somedomain.com”, “secret”); instead of sforceClient.init(sessionid, endpoint) to initialise sforceClient If running as a standalone application use the ‘frontdoor’ urls when calling  back into salesforce.com to prevent the user being prompted to login to salesforce.com through the web interface https://<instance>.salesforce.com/secur/frontdoor.jsp?sid= {!API_Session_ID} &retURL=/<URI to required page>
Calling s-controls on home page HTML components Can be used to display dynamic content on the home page S-controls and merge fields are not supported directly within the HTML component so uses an embedded iframe calling an scontrol web link  Create an scontrol Create a home page custom link and temporarily add it to a home page layout (to capture the URI) Create an HTML component My Salesforce.com (name not important )
Calling s-controls on home page HTML components Check the ‘Show HTML’ check box Add the following text to the HTML component: <IFRAME  src =&quot;/servlet/servlet.Integration?lid=00b20000000i5QO&amp;eid=00520000000hTCf&quot; frameBorder=0 width=&quot;100%&quot; height=&quot;100%&quot;></IFRAME> (Replace the lid and eid parameter values with those captured in the step above) Note as no record has context from the home page you cannot use merge fields in the scontrol (other than  {!API_Enterprise_Server_URL_60} and {!API_Session_ID} )
Additional Examples AJAX Account create New Opp and Task.htm - this is a pure s-control that is designed to work from a web link on an account.  It creates an opportunity, amends the opp return url and opens the opp in edit mode. AJAX update address of all contacts on an account.htm - this one is another pure s-control again driven from the account which updates all the addresses of linked contacts to the account to have the account address.  This one shows a small popup window 'Updating Contact Addresses' as it does the processing and then self closes in this case as nothing has changed on the account it doesn't bother to refresh the underlying record. AJAX List of all cases and associated solutions.htm - this one can be used either as an s-control or as a standalone browser app.  It loops through all the cases and sees what solutions are associated with it and displays the results with clickable links to the cases and solutions referenced.  It is specific to na1 and when used standalone needs another login when the urls are clicked (urls do not use the 'frontdoor' notation).
Resources AJAX Toolkit http://blog.sforce.com/sforce/2006/04/ajax_toolkit_be.html Can host locally Can include in document repository /servlet/servlet.FileDownload?file=[Document_ID] www.salesforce.com/developer Tech Notes Community forums – search on AJAX

More Related Content

S-Controls for Dummies

  • 1. S-Controls for Dummies Chris Sommers, Salesforce.com Senior Sales Engineer, Global Enterprise Accounts Track: Enterprise Edition Administrators
  • 2. Safe Harbor Statement “ Safe harbor” statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements the achievement of which involves risks, uncertainties and assumptions. If any such risks or uncertainties materialize or if any of the assumptions proves incorrect, our results could differ materially from the results expressed or implied by the forward-looking statements we make.  All statements other than statements of historical fact could be deemed forward-looking, including any projections of subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services. The risks and uncertainties referred to above include - but are not limited to - risks associated with the integration of Sendia Corporation’s technology, operations, infrastructure and personnel with ours; unexpected costs or delays incurred in integrating Sendia with salesforce.com, which could adversely affect our operating results and rate of growth; any unknown errors or limitations in the Sendia technology; any third party intellectual property claims arising from the Sendia technology; customer and partner acceptance and deployment of the AppExchange and AppExchange Mobile platforms; interruptions or delays in our service or our Web hosting; our new business model; breach of our security measures; possible fluctuations in our operating results and rate of growth; the emerging market in which we operate; our relatively limited operating history; our ability to hire, retain and motivate our employees and manage our growth; competition; our ability to continue to release and gain customer acceptance of new and improved versions of our CRM service; unanticipated changes in our effective tax rate; fluctuations in the number of shares outstanding; the price of such shares; foreign currency exchange rates and interest rates. Further information on these and other factors that could affect our financial results is included in the reports on Forms 10-K, 10-Q and 8-K and in other filings we make with the Securities and Exchange Commission from time to time, including our Form 10-K for the fiscal year ended January 31, 2006. These documents are available on the SEC Filings section of the Investor Information section of our website at www.salesforce.com /investor . Any unreleased services or features referenced in this or other press releases or public statements are not currently available and may not be delivered on time or at all.  Customers who purchase our services should make purchase decisions based upon features that are currently available.  Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements, except as required by law.
  • 3. Agenda What are S-Controls? When to use S-Controls S-Controls Techniques & Examples AJAX Introduction Examples and Resources Take Home Exercises
  • 4. What are Custom S-Controls? Light-weight web applications/tools hosted by salesforce.com and executed on the client browser An s-control can contain any type of content that can be displayed or run in a browser Java Applet ActiveX Control HTML / JavaScript / AJAX S-Controls are activated via Custom Links, Web Tabs, Web Apps or HYPERLINK custom formulae fields in salesforce.com (after 4 th Quarter release, executable in Detail Pages of records, and Custom Buttons)
  • 5. S-Control Options No back-office access State persistence Versioning issues IE Specific COM calling COM ActiveX Java Applet JSP / ASP AJAX Rich UI Can be “trusted” Tricky deployment eg. Salesforce.com Mail Merge Rich UI Can be “trusted” Cross-browser JVM versioning SOAP stack deployment Large footprint Java developer Rich UI Good access to internal systems Familiar dev environment Need a hosting stack Expensive development Packaging and sharing is difficult Pretty rich UI Simple API access Asynchronous Familiar html environment Javascript / cross-browser Quick and easy cycle Easy to package and share
  • 6. When to Use Custom S-controls (Value!) Consider using Custom S-controls if you… Want to enhance the Salesforce UI streamline a process reduce number of clicks Know that your process flow is closed loop, i.e., no outside databases or data sources Have less than 500 records to create or update per session Have few means to host a custom web application yourself
  • 7. User Interface Enhancement Add your own UI Advanced Capabilities (trees, graphs etc) Build Custom Logic Client-side Workflow (wizard) “Mass” Change to records When to Use Custom S-controls
  • 8. When NOT to Use Custom S-controls Do NOT use Custom S-controls if you… Are looking to build heavy-weight, computationally intensive extensions to Salesforce Are seeking a complex integrate with a system external to Salesforce.com (simple web-service and HTTP post/get will work!) Have more than 500 records to create or update per session
  • 9. Example: Pre-populate / create records in One Click What: One-click creation of a record Why: Efficiency, user adoption Value: Simplicity, adoption, data quality Example: One click to log a case (eg. Password Reset) Create a Custom Link on a Contact page to create a Case and prepopulate the fields (and save) How: In the app, from a Contact, click on “New Case”. Copy the URL – this is your web link BASE. https://na1.salesforce.com/500/e?retURL=%2F0033000000M1lut&def_contact_id=0033000000M1lut
  • 10. Log Password Reset Case Tip: After Winter ’07 Launch, use a Custom Button Instead
  • 11. Example: Pre-populate / create records Remove everything up to and including the “.com” Need to make it server agnostic /500/e?retURL=%2F{!Contact_ID}&def_contact_id= {!Contact_ID}&cas14=Password%20Reset&cas11=Phone&save=1 retURL is the page to which user should return after completing action “ 003…” is the Contact ID. Replace this with merge field: “{!Contact_ID}” Replace the second Contact ID with the same {!Contact_ID} Continue building out parameters View the page source, or use Form View in Firefox Web Developer to get the “name” of the fields you wish to pre-populate eg. Case Subject is “cas14”, Case Origin is “cas11”
  • 12. Preventing Double-Tabbing <script language=&quot;Javascript&quot;> function redirect() { parent.frames .location.replace('/500/e?retURL=%2F{!Contact_ID} &def_contact_id={!Contact_ID}&cas14=Password%20Reset &cas11=Phone&save=1'); } redirect(); </script>
  • 13. Example: Parameterize Reports What: One-click dynamic generation of a report Why: Efficiency, scalability Value: Simplicity Example: Generate a report dynamically passing filters Tip: After Winter ’07 Launch, use a Custom Button Instead
  • 14. Example: Parameterize Reports How: Create a report, filter by desired field Copy the report URL Create a Custom Link on the entity In the custom link URL box, paste in the report URL At the end of this URL string add the following text: ?pv0=[MERGE_FIELD] Eg. /00O30000001D5tZ?pv0={!Account_Name} Use pv0 if your criteria filter is in position 1 in your report, pv1 if it is in the 2 nd position, and so on
  • 15. AJAX What: A synchronous J avascript A nd X ML Why: Rapid Software, Component Development Value: Adoption, low cost Example: Mass Update Contact Addresses Before AJAX With AJAX
  • 16. The AJAX Toolkit – Object Model
  • 17. SforceClient Method Summary QueryMore (queryLocator, callback)   QueryResult Query (soql, callback)   QueryResult Login (userName, password, callback)   LoginResult Init (sessId, serverUrl)   void GetUserInfo (callback)   GetUserInfoResult GetUpdated (objectType, startDate, endDate, callback)   GetUpdatedResult getSessionId ()   String getServerUrl ()   String GetServerTimestamp (callback)   GetServerTimestampResult GetDeleted (objectType, startDate, endDate, callback)   GetDeletedResult DescribeTabs (callback)   DescribeTabSetResult[] DescribeSObject (objectType, callback)   DescribeSObjectResult DescribeLayout (objectType, callback)   DescribeLayoutResult DescribeGlobal (callback)   DescribeGlobalResult Delete (ids, callback)   SaveResult[] debugMessage (msg)              void Create (objects, callback)   SaveResult[] ConvertLead (leadConverts, callback)   ConvertLeadResult[] Update (objects, callback)   SaveResult[] timingDebugClear ()              void timingDebug (msg)              void setTimingDebugger (textarea)   void setSessionId (sid)   void setServerUrl (newurl)   void SetPassword (userId, password, callback)   SetPasswordResult setDebugContainer (container)   void setBatchSize (size)   void SendRequest2 (soapMessage, handler, operation, url)   void Search (searchString, callback)   SearchResult Retrieve (fieldList, objectType, idArray, callback)   SObject[] ResetPassword (userId, callback)   ResetPasswordResult
  • 18. SforceClient https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js Dynamic SObject - DynaBean S-Control Context and Merge Fields Common Functions: Query Call Retrieve Create Call Update Call Delete Call Save Call AJAX - Key Components
  • 19. sForceClient Within the <head> section: <script src=&quot;https://www.salesforce.com/services/lib/ajax/beta3.3/sforceclient.js&quot; type=&quot;text/javascript&quot;></script> Instantiated on script inclusion sforceClient.init(&quot;{!API_Session_ID}&quot;, &quot;{!API_Partner_Server_URL_70}&quot;); Call sforceClient.init or sforceClient.Login sforceClient.init(&quot;{!API_Session_ID}&quot;, &quot;{!API_Partner_Server_URL_70}&quot;);
  • 20. Dynamic SObject - Dynabean Uses a single object - a Dynabean - to represent every available “table” in the database Dynabean is a dynamic object that contains both data and metadata that determines its character Example: var myLead = new Sforce.Dynabean(“Lead&quot;) myLead.set(“FirstName”, “Stan”); myLead.set(“LastName”, “Lee”); myLead.set(“Company”, “ABC Company”); var saveResult = sforceClient.Create(myLead)[0];
  • 21. Query Call Example: var queryResult =sforceClient.Query(&quot;Select BillingCity, BillingCountry, from Account Where Id = '&quot; + accId + &quot;'&quot;); var address = queryResult.records[0]; var BillingCity = address.BillingCity; var BillingCountry = address.get(“BillingCountry”);
  • 22. Example: Close Opportunity, Create Order and Order Items What: In one click from an Opportunity, need to: Close Opportunity Create Contract Create Order with Contract Reference Copy Opportunity Products to Order Items Why: Too many clicks without, poor user-experience Value: Minimizes user error, improves data quality and user satisfaction
  • 23. Example: Search First, Create What: Enforce that users search for existing data before creating new records Custom Web Tab (today) Override Standard “New” button after Winter ’07 Use search parameters to populate new records if desired Why: Cleaner data – NO DUPLICATES Value: Minimizes duplicates/improves data quality and user satisfaction
  • 24. Create Call var accounts = new Array(); accounts[0] = new Sforce.Dynabean (&quot;Account&quot;); accounts[0].set(&quot;Name&quot;, &quot;test1&quot;); accounts[1] = new Sforce.Dynabean (&quot;Account&quot;); accounts[1].set(&quot;Name&quot;, &quot;test2&quot;); var rc = sforceClient.Create(accounts); if (dltypeof(rc) == &quot;array&quot;) { // do something with the returned created ids } else { alert( rc.toString() ); }
  • 25. Update Call accs[0] = new Sforce.Dynabean (&quot;Account&quot;); accs[0].set(&quot;Id&quot;, “{!Account_ID}&quot;); accs[0].set(&quot;Name&quot;, &quot;test Updated&quot;); var sr = sforceClient.Update(accs); …… var qr =sforceClient.Query(&quot;Select Id, MailingCountry from Contact Where AccountId = '&quot; + accId + &quot;'&quot;); var updateObjects = new Array(); for (var i=0;i<qr.records.length;i++){ var contact = qr.records[i]; contact.set(&quot; MailingCountry “, “United Kingdom”); // push updated record into new array for update process updateObjects.push(contact); } var saveResults = sforceClient.Update(updateObjects);
  • 26. Delete Call var accounts = new Array(); accounts[0] = new DynaBean(&quot;Account&quot;); accounts[0].set(&quot;Name&quot;, &quot;test&quot;); var sr = sforceClient.Create([accounts])[0]; var dr = sforceClient.Delete([sr[0].id]); if (dltypeof(dr) == &quot;array&quot;) { for (var i=0;i<dr.length;i++) { alert( dr[i].toString()); } } else { alert( dr[i].toString()); }
  • 27. Calling an S-Control using HYPERLINK field For HYPERLINK custom formulae fields or for calling an scontrol from another scontrol Create a Custom Link as usual Add to page layout View record and right click on link-properties and copy the url section: /servlet/servlet.Integration?lid=00b30000000hXeL&eid=00130000005YmJ5 lid = s-control id and eid = context entity record Replace the hard coded eid with the id of the current record
  • 28. Tools and Techniques Development Environment Text editor (Wordpad, 1 st Page 2000, Ultraedit) Eclipse (javascript specific plugins) Visual Studio .NET Other standard IDEs Debugging MS Script Debugger (ok) Visual Studio .NET (best) Mozilla/Venkman Debugger (ok) Mozilla Javascript Console
  • 29. Tools and Techniques Recommend installing Firefox and then adding the following extensions: Web Developer 0.9.3 JavaScript Debugger 0.9.84 View Rendered Source 1.0.01 Test with IE and Firefox. Handle cross browser exceptions Firefox doesn’t allow cross site scripting Firefox is stricter on language semantics Firefox better for debugging
  • 30. Techniques - Debugging Debugging support in the toolkit setDebugContainer(element) sforceClient.setDebugContainer(document.getElementById(“mydiv”); sforeceClient.setDebugContainer(document.getElementById(“myTextArea”); sforceClient.debugMessage(“This is a point in the script.”); setMessageLog(textArea) Displays the SOAP requests and responses setTimingDebugger(textArea) displays the elapsed time to execute a method. Javascript alert statement alert(“Error message = “+error); Debugger / output to the Javascript console
  • 31. Passing parameters to an S-Control Yes: if the scontrol is called via HYPERLINK in a custom formulae field, YES, this is possible No: if the scontrol is called via a Custom Link or Web Tab Yes: within an scontrol additional parameters can be added to the URI for a call to a second scontrol HYPERLINK(&quot;/servlet/servlet.Integration?lid=01N3000000009KE&eid=&quot; & {!Id} & &quot;&address=billing&quot;, &quot;Test Link&quot;) eid parameter can be accessed in the s-control to get the current entity context record if needed
  • 32. Other (Non AJAX) S-Controls Techniques Parameterise Reports Pre-populate / create records Preventing double tabbing on salesforce.com web links Manipulating return urls and page chaining Calling an S-Control Passing parameters to an S-Control Style Sheets – Replicating salesforce.com look and feel Standalone AJAX application Calling s-controls on home page HTML components
  • 33. Style Sheets – Replicating salesforce.com look and feel Different style sheets per language and for ‘Salesforce Classic’ and the new interface Need to pickup the right style sheet to maintain look and feel within the scontrol userUiSkin returns a value indicating the CSS path that should be specified Salesforce1: /dCSS/Theme1/en/common.css Salesforce2: /dCSS/Theme2/en/common.css common.css should be the only file you need to use to replicate the salesforce.com's look and feel. For full details see tech note http://www.sforce.com/resources/tn-16.jsp
  • 34. Standalone AJAX application Use divs to present / hide a login screen Call sforceClient.Login(“username@somedomain.com”, “secret”); instead of sforceClient.init(sessionid, endpoint) to initialise sforceClient If running as a standalone application use the ‘frontdoor’ urls when calling back into salesforce.com to prevent the user being prompted to login to salesforce.com through the web interface https://<instance>.salesforce.com/secur/frontdoor.jsp?sid= {!API_Session_ID} &retURL=/<URI to required page>
  • 35. Calling s-controls on home page HTML components Can be used to display dynamic content on the home page S-controls and merge fields are not supported directly within the HTML component so uses an embedded iframe calling an scontrol web link Create an scontrol Create a home page custom link and temporarily add it to a home page layout (to capture the URI) Create an HTML component My Salesforce.com (name not important )
  • 36. Calling s-controls on home page HTML components Check the ‘Show HTML’ check box Add the following text to the HTML component: <IFRAME src =&quot;/servlet/servlet.Integration?lid=00b20000000i5QO&amp;eid=00520000000hTCf&quot; frameBorder=0 width=&quot;100%&quot; height=&quot;100%&quot;></IFRAME> (Replace the lid and eid parameter values with those captured in the step above) Note as no record has context from the home page you cannot use merge fields in the scontrol (other than {!API_Enterprise_Server_URL_60} and {!API_Session_ID} )
  • 37. Additional Examples AJAX Account create New Opp and Task.htm - this is a pure s-control that is designed to work from a web link on an account.  It creates an opportunity, amends the opp return url and opens the opp in edit mode. AJAX update address of all contacts on an account.htm - this one is another pure s-control again driven from the account which updates all the addresses of linked contacts to the account to have the account address.  This one shows a small popup window 'Updating Contact Addresses' as it does the processing and then self closes in this case as nothing has changed on the account it doesn't bother to refresh the underlying record. AJAX List of all cases and associated solutions.htm - this one can be used either as an s-control or as a standalone browser app.  It loops through all the cases and sees what solutions are associated with it and displays the results with clickable links to the cases and solutions referenced.  It is specific to na1 and when used standalone needs another login when the urls are clicked (urls do not use the 'frontdoor' notation).
  • 38. Resources AJAX Toolkit http://blog.sforce.com/sforce/2006/04/ajax_toolkit_be.html Can host locally Can include in document repository /servlet/servlet.FileDownload?file=[Document_ID] www.salesforce.com/developer Tech Notes Community forums – search on AJAX