Sunday, May 5, 2013

Salesforce Mobile SDK

Visualforce Page Sample Code


<!--
        Salesforce Developer Meetup Karachi April 21-27, 2013.
        Salesforce Mobile Developer Week.
        Worldwide Developer Gathering.
        April 21-27, 2013
     
        Salesforce Mobile Web(HTML5) Apps
-->
<apex:page docType="html-5.0" sidebar="false" showHeader="false" standardStylesheets="false" cache="false" controller="SalesforceDevMeetupKarachiCtrl">
<html>
    <apex:stylesheet value="{!URLFOR($Resource.MobileSample_Resources_jQueryMobile, 'jquery.mobile-1.3.0.min.css')}"/>
    <apex:includeScript value="{!URLFOR($Resource.MobileSample_Resources_jQueryMobile, 'jquery-1.9.1.min.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.MobileSample_Resources_jQueryMobile, 'jquery.mobile-1.3.0.min.js')}"/>
    <apex:includeScript value="{!URLFOR($Resource.MobileSample_Resources_jQueryMobile, 'ForceTk.js')}"/>
<head>
    <title>Salesforce Developer Meetup Karachi April 21-27, 2013</title>
 
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />  
 
    <script type="text/javascript">
        var $j = jQuery.noConflict();
        var leadRecs = new Array();
     
        var restAPIClient = new forcetk.Client();
        restAPIClient.setSessionToken('{!$Api.Session_ID}');
     
        $j(document).ready(function(){
            getAllLeads();
        });
         
        //Query and get list of Leads to show        
        function getAllLeads(){
            $j.mobile.showPageLoadingMsg();
            var q = "select id, firstName, lastName, phone, email, company, LeadSource, Status from Lead where isconverted = false order by FirstName";
            restAPIClient.query(q ,
            function(response){
                showLeads(response.records);
            });                              
        }

        //Show list of Leads to convert it into Account, Contact and Opportunity                  
        function showLeads(records){  
            $j('#leadListView').empty();
            leadRecs.length = 0;                            
            for(var i = 0; i < records.length; i++) { leadRecs[records[i].Id] = records[i]; }
            var x = 0;
            $j.each(records,
            function() {
                var newLi = $j('<li></li>');                              
                var newLink = $j('<a id="' +this.Id+ '" data-transition="flip">' +this.FirstName+ ' '+this.LastName+ '</a>');
                newLink.click(function(e){
                    e.preventDefault();
                    $j.mobile.showPageLoadingMsg();
                    $j('#fNameHeader').val(leadRecs[this.id].FirstName);
                    $j('#lNameHeader').val(leadRecs[this.id].LastName);
                    $j('#fName').val(leadRecs[this.id].FirstName);
                    $j('#lName').val(leadRecs[this.id].LastName);
                    $j('#phone').val(leadRecs[this.id].Phone);
                    $j('#email').val(leadRecs[this.id].Email);
                    $j('#company').val(leadRecs[this.id].Company);
                    $j('#leadSource').val(leadRecs[this.id].LeadSource);
                    $j('#status').val(leadRecs[this.id].Status);
                    $j('#leadId').val(leadRecs[this.id].Id);
                    $j('#error').html('');                  
                    $j.mobile.changePage('#leaddetailpage', {changeHash: true});
                });
                newLi.append(newLink);          
                newLi.appendTo('#leadListView');
                x++;
            });                                
            $j.mobile.hidePageLoadingMsg();
            $j('#leadListView').listview('refresh');
        }
     
        //Convert Lead into Account, Contact and Opportunity
        function convertLead(){
            var leadToConvert =  $j('#leadId').val();
            //Invoke JavaScript Remoting function convertLead in Apex controller to convert Lead into Account, Contact and Opportunity
            SalesforceDevMeetupKarachiCtrl.convertLead(leadToConvert,
            //Show the details of new Account created by convet Lead process
            function(result, e){
                $j.mobile.showPageLoadingMsg("b", "Converting Lead ...", true);
                $j('#acctName').val(result.Name);
                $j('#acctType').val(result.Type);
                $j('#acctId').val(result.Id);
                $j.mobile.hidePageLoadingMsg();            
                $j.mobile.changePage('#newconvertedaccountcontactopportunity', {changeHash: true});
                getUser(result);
                getContact(result);
                getOpportunity(result);
            });                                                                                                  
        }
     
        //Get and show the User Name associated with the Account Owner Id
        function getUser(result){
            var acctOwnerId = result.OwnerId;
            //Invoke JavaScript Remoting function getUser in Apex controller to get the User Name associated with the Account Owner Id
            SalesforceDevMeetupKarachiCtrl.getUser(acctOwnerId,
            //Show the User Name associated with the Account Owner Id
            function(result, e){
                $j.mobile.showPageLoadingMsg("b", "Converting Lead ...", true);
                $j('#acctOwner').val(result.Name);
                $j.mobile.hidePageLoadingMsg();            
                $j.mobile.changePage('#newconvertedaccountcontactopportunity', {changeHash: true});
            });                                      
        }
     
        //Get and show the details of new Contact created by convet Lead process
        function getContact(result){
            var newacctId = result.Id;
            //Invoke JavaScript Remoting function getContact in Apex controller to get the details of new Contact created by convet Lead process
            SalesforceDevMeetupKarachiCtrl.getContact(newacctId,
            //Show the details of new Contact created by convet Lead process
            function(result, e){
                $j.mobile.showPageLoadingMsg("b", "Converting Lead ...", true);
                $j('#contFirstName').val(result.FirstName);
                $j('#contLastName').val(result.LastName);
                $j('#contTitle').val(result.Title);
                $j('#contPhone').val(result.Phone);
                $j('#contEmail').val(result.Email);
                $j('#contId').val(result.Id);
                $j.mobile.hidePageLoadingMsg();            
                $j.mobile.changePage('#newconvertedaccountcontactopportunity', {changeHash: true});
            });                                      
        }
     
        //Get and show the details of new Opportunity created by convet Lead process          
        function getOpportunity(result){
            var newacctId = result.Id;
            //Invoke JavaScript Remoting function getOpportunity in Apex controller to get the details of new Opportunity created by convet Lead process
            SalesforceDevMeetupKarachiCtrl.getOpportunity(newacctId,
            //Show the details of new Opportunity created by convet Lead process
            function(result, e){
                $j.mobile.showPageLoadingMsg("b", "Converting Lead ...", true);
                $j('#opptyName').val(result.Name);
                $j('#opptyStageName').val(result.StageName);
                $j('#opptyCloseDate').val(result.Close_Date__c);
                $j('#opptyAmount').val(result.Amount);
                $j('#opptyId').val(result.Id);
                $j.mobile.hidePageLoadingMsg();            
                $j.mobile.changePage('#newconvertedaccountcontactopportunity', {changeHash: true});
            });                                      
        }
     
        function refreshThePage(){
            $.mobile.loadPage("/apex/VFSalesforceDevMeetupKarachi");
        }

        function displayError(e){
            var error = JSON.parse(e.responseText);
            $j('#error').html(error[0].message);
        }                              
    </script>  

    <style type="text/css" media="screen">
    th {
        text-align: right;
    }
    td {
        text-align: left;
        padding: 5px; 10px; 5px; 5px;
        color: #6099c6;
        font-weight: bold;
     }
    </style>
     
</head>

<body>
    <div data-role="page" data-theme="b" id="listpage">              
        <div data-role="header" data-theme="b" data-position="fixed">
            <h2>Salesforce Mobile Developer Week</h2>
            <h4>Worldwide Developer Gathering</h4>
            <h4>April 21-27, 2013</h4>                          
        </div>
     
        <!-- Show list of Leads -->
        <div data-role="content" id="leadList">
            <h2>Search Salesforce Leads</h2>          
            <ul id="leadListView" data-filter="true" data-inset="true" data-role="listview"
            data-theme="c" data-dividertheme="b" data-autodividers="true" data-filter-placeholder="Search Salesforce Leads">
            </ul>
        </div>                      
    </div>  
 
    <!-- Show Lead Detail -->      
    <div data-role="page" data-theme="b" id="leaddetailpage">
        <div data-role="header" data-position="fixed" data-theme="b">
            <h1><output name="fNameHeader" id="fNameHeader"></output> <output name="lNameHeader" id="lNameHeader"></output>'s Detail</h1>
            <a href='#listpage' id="back2Home" data-role="button" class='ui-btn-left' data-icon="home" data-transition="slide" onClick="refreshThePage();">Back to Home</a>  
        </div>          

        <div data-role="content">
            <a href="#" data-role="button" data-icon="star" data-iconpos="left" style="background: #E29221; color: white;">Lead</a>
            <table>                            
            <tr>
            <th>First Name</th>
            <td><output name="fName" id="fName"></output></td>
            </tr>              
            <tr>
            <th>Last Name</th>
            <td><output name="lName" id="lName"></output></td>
            </tr>              
            <tr>
            <th>Company</th>
            <td><output name="company" id="company"></output></td>
            </tr>                            
            <tr>
            <th>Lead Source</th>
            <td><output name="leadSource" id="leadSource"></output></td>
            </tr>                            
            <tr>
            <th>Lead Status</th>
            <td><output name="status" id="status"></output></td>
            </tr>
            <tr>
            <th>Phone</th>                  
            <td><a href="tel:"><output name="phone" id="phone"></output></a></td>
            </tr>              
            <tr>
            <th>Email</th>
            <td><a href="mailto:"><output name="email" id="email"></output></a></td>
            </tr>                            
            <tr>
            <th></th>
            <td>
            <h2 style="color:red" id="error"></h2><br/>
            <input type="hidden" id="leadId" />
            </td>
            </tr>
            </table>
            <hr size="2"/>
            <center>
            <a href="#newconvertedaccountcontactopportunity" id="convertLead" data-theme="b" data-role="button" data-icon="star" data-direction="reverse" data-transition="flip" class='ui-btn-left' onClick="convertLead();" >Convert Lead</a>
            </center>
        </div>                        
    </div>
         
    <!-- Show detail of new Account, Contact and Opportunity created by convert Lead process -->
    <div data-role="page" data-theme="b" id="newconvertedaccountcontactopportunity">  
        <div data-role="header" data-position="fixed" data-theme="b">
            <h1>Converted Lead Detail</h1>
            <a href='#listpage' id="back2Home" data-role="button" class='ui-btn-left' data-icon="home" data-transition="slide" onClick="refreshThePage();">Back to Home</a>
        </div>
     
        <!-- Show detal of new Account created by convert Lead process -->
        <div data-role="content">
            <a href="#" data-role="button" data-icon="star" data-iconpos="left" style="background: #236EBC; color: white;">Account</a>
            <div data-role="fieldcontain">
                <table>
                <tr>
                <th>Account Owner</th>
                <td><output name="acctOwner" id="acctOwner"></output></td>
                </tr>
                <tr>
                <th>Account Name</th>
                <td><output name="acctName" id="acctName"></output></td>
                </tr>
                <tr>
                <th>Account Type</th>
                <td><output name="acctType" id="acctType"></output></td>
                </tr>
                </table>
            </div>
            <h2 style="color:red" id="error"></h2><br/>
            <input type="hidden" id="acctId" />
        </div>  
        <hr size="2"/>

        <!-- Show detal of new Contact created by convert Lead process -->        
        <div data-role="content">
            <a href="#" data-role="button" data-icon="star" data-iconpos="left" style="background: #55448B; color: white;">Contact</a>
            <div data-role="fieldcontain">
                <table>
                <tr>
                <th>First Name</th>
                <td><output name="contFirstName" id="contFirstName"></output></td>
                </tr>
                <tr>
                <th>Last Name</th>
                <td><output name="contLastName" id="contLastName"></output></td>
                </tr>
                <tr>
                <th>Title</th>
                <td><output name="contTitle" id="contTitle"></output></td>
                </tr>
                <tr>
                <th>Phone</th>
                <td><output name="contPhone" id="contPhone"></output></td>
                </tr>
                <tr>
                <th>Email</th>
                <td><output name="contEmail" id="contEmail"></output></td>
                </tr>
                </table>
            </div>
            <h2 style="color:red" id="error"></h2><br/>
            <input type="hidden" id="contId" />
        </div>  
        <hr size="2"/>
     
        <!-- Show detal of new Opportunity created by convert Lead process -->  
        <div data-role="content">
            <a href="#" data-role="button" data-icon="star" data-iconpos="left" style="background: #E3BF30; color: white;">Opportunity</a>
            <div data-role="fieldcontain">
                <table>
                <tr>
                <th>Opportunity Name</th>
                <td><output name="opptyName" id="opptyName"></output></td>
                </tr>
                <tr>
                <th>Opportunity Stage</th>
                <td><output name="opptyStageName" id="opptyStageName"></output></td>
                </tr>
                <tr>
                <th>Opportunity Close Date</th>
                <td><output name="opptyCloseDate" id="opptyCloseDate"></output></td>
                </tr>
                <tr>
                <th>Opportunity Amount</th>
                <td><output name="opptyAmount" id="opptyAmount"></output></td>
                </tr>
                </table>
            </div>
            <h2 style="color:red" id="error"></h2><br/>
            <input type="hidden" id="opptyId" />
        </div>          
        <center>
        <a href='#listpage' id="back2Home" data-role="button" class='ui-btn-left' data-icon="home" data-transition="slide" onClick="refreshThePage();">Back to Home</a>
        </center>
    </div>  
</body>
</html>  
</apex:page>




Visualforce Controller Sample Code
/*
* @Created Date : 4/26/2013
* @Modified Date : 4/26/2013
* @Modified By : Salesforce Developer Meetup Karachi User
* @Purpose: 
* (a) To show Salesforce Leads.
* (b) To show details of Leads.
* (c) To convert Lead into Account, Contact and Opportunity.
* (d) To show newly created Account, Contact and Opportunity created by Convert Lead process.
*/
public with sharing class SalesforceDevMeetupKarachiCtrl{

    //Controller constructor
    public SalesforceDevMeetupKarachiCtrl(){
    }
    
    //Remote Function to convert Lead into Account, Contact and Opportunity
    @RemoteAction
    public static Account convertLead(String leadId){
        //Query Lead record to convert Lead into Account, Contact and Opportunity
        Lead lead = [SELECT Id FROM Lead WHERE Id =:leadId LIMIT 1];

        
        //Query Lead status to convert Lead into Account, Contact and Opportunity
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];

        //Convert Lead into Account, Contact and Opportunity
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(lead.id);        
        lc.setConvertedStatus(convertStatus.MasterLabel);        
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());

        //Query new Account record created by created by convert Lead process        
        Account newConvertedAccount = [SELECT Id, Name, Type, Owner.Name, OwnerId FROM Account WHERE Id =:lcr.getAccountId() LIMIT 1];                 
        return newConvertedAccount;
    }
    
    //Remote Function to get the User Name associated with the Account Owner Id
    @RemoteAction
    public static User getUser(String userId){
        //Query User record for Account Owner       
        User user = [SELECT Id, Name FROM User WHERE Id =:userId LIMIT 1];
        return user;
    }

    //Remote Function to get the details of new Contact created by convert Lead process
    @RemoteAction
    public static Contact getContact(String accountId){
        //Query new Contact record created by created by convert Lead process        
        Contact cont = [SELECT Id, FirstName, LastName, Title, Email, Phone FROM Contact WHERE AccountId =:accountId LIMIT 1];
        return cont;
    }

    //Remote Function to get the details of new Opportunity created by convert Lead process
    @RemoteAction
    public static Opportunity getOpportunity(String accountId){
        //Query new Opportunity record created by created by convert Lead process        
        Opportunity oppty = [SELECT Id, Name, StageName, Close_Date__c, Amount FROM Opportunity WHERE AccountId =:accountId LIMIT 1];
        oppty.Amount = 100.00;
        update oppty;
        return oppty;
    }
}