Salesforce Ajax Rest API

<apex:page showHeader="false" sidebar="false" standardStylesheets="false" id="page" docType="html-5.0">
    <script language="JavaScript1.2" src="/js/functions.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="//code.jquery.com/jquery-1.12.4.js"></script>
    <script src="/soap/ajax/19.0/connection.js" type="text/javascript"></script>
    <script type="text/javascript">
        var $j = jQuery.noConflict();
        var sessionId = '{!$Api.Session_ID}';
        $j(document).ready(function() {
            var leadDetails = {"LeadId": "00Q1k000000tqKJEAY"};
            //var leadDetails = {!$CurrentPage.parameters.attachedRecords};
            console.log('--->>>' + leadDetails.LeadId);
            var leadIdFromJS = leadDetails.LeadId;
            $('input[name=Lead_ID]').val(leadIdFromJS);
            console.log("sessionId :: " + sessionId);
            sessionId = '00D1k0000008bxO!AR0AQIdM77bzQ6JFPShWmVSGOAPad.WfIY_gt7pDjQYCJ7ozjJRIng1qfYn._HUnSQlQT4yRv1A5GTbvSgdI3uxJ8vsjBwgT';
            console.log("Formed Query is :: " + encodeURIComponent("SELECT Id,Name, Lead__c, createddate from CC_Response__c where Lead__c = " + "'"+$j.trim(leadIdFromJS)+"'" + " limit 1"));
            var respID;
            $j.ajax({
                type: "GET",
                url: '/services/data/v35.0/query?q=' + encodeURIComponent("SELECT Id,Name, Lead__c, createddate from CC_Response__c where Lead__c = " + "'"+ $j.trim(leadIdFromJS)+"'" + " limit 1"),
                headers: {
                    "Authorization": "OAuth " + sessionId
                },
                crossDomain: true,
                dataType: 'json',
                success: function(responseData) {
                    var jsonTemp = JSON.stringify(responseData.records);
                    console.log("jsonTemp :: "+jsonTemp);
                    console.log(" Success - 1 :: " + responseData.records[0].Id);
                    $('input[name=Response_ID]').val(responseData.records[0].Id);
                    //cmdSFDCForm();
                   cmdAjax2SFDC();
                },
                error: function(request, status, error) {
                    console.log(" error - 1 :: " + request.responseText);
                }
            });           
             
        });
        function cmdAjax2SFDC(){
            var jsonString = '{"prechatDetails":[{"label":"CompanyName","value":"ciscsc","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"OriginatingURLInput","value":"","entityMaps":[],"transcriptFields":["Originating_URL__c"],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"recordType","value":"01280000000GEtXAAW","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"FirstName","value":"cisco","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"Phone","value":"5985698658","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"LastName","value":"ciscos","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"countryName","value":"","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"sessionId","value":"89a9a262-0731-4830-ab26-789643e2eefb","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"Interested","value":"Accepted1","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"EmailAddress","value":"ciscsco@ciscsoc.com","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false},{"label":"status","value":"New Prospect","entityMaps":[],"transcriptFields":[],"displayToAgent":"true","doKnowledgeSearch":false}],"geoLocation":{"organization":"Cisco Systems","region":"CA","city":"San Jose","countryName":"United States","latitude":37.3394,"countryCode":"US","longitude":-121.895},"visitorId":"89a9a262-0731-4830-ab26-789643e2eefb","customDetails":[{"value":"Demo First name","entityMaps":[],"displayToAgent":false,"label":"FirstNameInput","transcriptFields":[]},{"value":"Demo Last name","entityMaps":[],"displayToAgent":false,"label":"LastNameInput","transcriptFields":[]},{"value":"+1(800)231-8323","entityMaps":[],"displayToAgent":false,"label":"PhoneInput","transcriptFields":[]},{"value":"Test@cisco.com","entityMaps":[],"displayToAgent":false,"label":"EmailAddressInput","transcriptFields":[]},{"value":"123123412341","entityMaps":[],"displayToAgent":false,"label":"data-c2c-ecid","transcriptFields":[]},{"value":"000775282","entityMaps":[],"displayToAgent":false,"label":"Keycode","transcriptFields":[]},{"value":"US","entityMaps":[],"displayToAgent":false,"label":"CountryInput","transcriptFields":[]},{"value":"Cisco Systems, INC.","entityMaps":[],"displayToAgent":false,"label":"CompanyInput","transcriptFields":[]},{"value":"abcd-abcd-abcd-abcd","entityMaps":[],"displayToAgent":true,"label":"CookieInput","transcriptFields":[]},{"value":"http://int-ciscosalescrm.cs78.force.com/chat","entityMaps":[],"displayToAgent":true,"label":"OriginatingURL","transcriptFields":[]}],"agent":{"userId":"00580000007Hbuc","agentName":"Fazurulla G","transfer":0}}';   
            //var jsonString = '{!$CurrentPage.parameters.chatDetails}';
            console.log(jsonString);                 
            obj = JSON.parse(jsonString);
            var uid = obj.agent['userId'];
            console.log(uid);
            $('input[name=User_ID]').val(uid);
           $j.ajax({
                type: "GET",
                url: '/services/data/v35.0/query?q=' + encodeURIComponent("select id, username, alias, name, Marketing_Call_Center__c from User where Id = " + "'" + uid + "'" + " limit 1"),
                headers: {
                    "Authorization": "OAuth " + sessionId
                },
                crossDomain: true,
                dataType: 'json',
                success: function(responseData) {
                    var jsonTemp = JSON.stringify(responseData.records);
                    console.log(jsonTemp);
                    console.log(responseData.records[0].Id);
                    $('input[name=Agent_Name]').val(responseData.records[0].Name);
                    cmdSFDCForm();
                },
                error: function(request, status, error) {
                    console.log("faz error***" + request.responseText);
                }
            }); 
        }
        function cmdSFDCForm() {
            var f = document.getElementById('TheForm');
            window.open('', '_top');
            f.submit();
        }
    </script>
    <form id="TheForm" method="GET" action="https://google.com/LP=7907" target="_top">
        <input type="hidden" name="Lead_ID" value="" />
        <input type="hidden" name="User_ID" value="" />
        <input type="hidden" name="Response_ID" id="Response_ID" value="" />
        <input type="hidden" name="Agent_Name" value="" />
    </form>
</apex:page>

Rest API Response in XML format Salesforce

Destination Org Access Token Snippet :

Public class Org_GlobalAccessToken_Cls {
    Public Static String clientId = EncodingUtil.urlEncode('3MVG9I5UQ_0k_hTm9p9qVC3ruJI49xkzjVd51JkCiNN7tPr.qUcphB8KZFvrQGm9XnO6r5PX6GJKyG_F9rRmK', 'UTF-8');
    Public Static String clientSecret = EncodingUtil.urlEncode('387843950858359729', 'UTF-8'); 
    Public Static String username = EncodingUtil.urlEncode('**your org name**', 'UTF-8');
    Public Static String password = EncodingUtil.urlEncode('**Password+Security Token**', 'UTF-8'); 
    Public Static String reqbody = 'grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password;
    public static string cmdAccessToken() {
        system.debug('clientSecret ----'+clientSecret);
        system.debug('password--'+password+' ----username ---'+username );
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://eu9.salesforce.com/services/oauth2/token');
        HttpResponse res = h.send(req);
        if (res.getstatuscode() == 200) {
            GrantAccessToken accessToken = (GrantAccessToken) JSON.deserialize(res.getbody(),GrantAccessToken.class);
            system.debug('**********'+res.getbody());
            if (accessToken.access_token != null) {
                system.debug('**********'+accessToken.access_token);
                return accessToken.access_token;
            } else {
                return null;
            }
        }
        return null;
    }
    public class GrantAccessToken {
        public String id {
            get;
            set;
        }
        public String issued_at {
            get;
            set;
        }
        public String instance_url {
            get;
            set;
        }
        public String signature {
            get;
            set;
        }
        public String access_token {
            get;
            set;
        }
    } 

}

Destination ORG Main Logic in XML format :

public class XMLparse{
    public String  XMLString;
    public String accessToken ;
    public String endPoint;
    public list<Account> pro;
    public Account temppro; 
    public XMLparse(){
        pro = new list<Account>();
        accessToken = Org_GlobalAccessToken_Cls.cmdAccessToken();
        endPoint = 'https://eu9.salesforce.com/services/apexrest/GETSaamTestSearches';
        Http h2 = new Http();
        HttpRequest req1 = new HttpRequest();
        req1.setHeader('Authorization', 'Bearer ' + accessToken);
        req1.setHeader('Content-Type', 'application/xml');
        req1.setHeader('accept', 'application/xml');
        req1.setMethod('GET');
        req1.setEndpoint(endPoint);
        HttpResponse resp = h2.send(req1);
        system.debug('XMLString---->>'+resp.getBody());
        XMLString = resp.getBody();
        //XMLString = '<?xml version="1.0" encoding="UTF-8"?><SearchestoProcess><row><Name>University of Arizona</Name><AccountNumber>0010O00001qotCnQAI</AccountNumber></row></SearchestoProcess>';
        DOM.Document doc=new DOM.Document();
        try{
            doc.load(XMLString);
            DOM.XmlNode rootNode=doc.getRootElement();
            parseXML(rootNode);
            pro.add(temppro);
            insert pro;
            system.debug('pro inserted successfully-----------'+pro);
            for(Account a : pro){
                a.XML_Response__c = XMLString;
             
            }
            upsert pro;
        }catch(exception e){
            system.debug(e.getMessage()+ ' Line Number  :'+e.getLineNumber()+' Field Name :'+e.getStackTraceString());
        }
    }
 
    public void parseXML(DOM.XMLNode node) {
        Map<String,Org_Account_Mapping__c> orgMapping = Org_Account_Mapping__c.getAll();
        if (node.getNodeType() == DOM.XMLNodeType.ELEMENT) {
            if(node.getName()=='row'){
                if(temppro!=null)
                    pro.add(temppro);
                temppro = new Account();
            }
            for(String sMapping : orgMapping.keySet()){
                if(node.getName()== sMapping && orgMapping.get(sMapping).Is_Text_Field__c){
                    if(node.getText().trim() !=Null){
                        temppro.put(orgMapping.get(sMapping).Target_Field__c,String.valueof(node.getText().trim()));
                        system.debug(orgMapping.get(sMapping).Target_Field__c+' Text Mapping values ---------->>>>>'+temppro);
                    }
                }else if(node.getName()== sMapping && orgMapping.get(sMapping).Is_Decimal_Field__c){
                    if(node.getText().trim() !=Null){
                        temppro.put(orgMapping.get(sMapping).Target_Field__c,Decimal.valueof(node.getText().trim()));
                        system.debug(orgMapping.get(sMapping).Target_Field__c+' Decimal Mapping values ---------->>>>>'+temppro);
                    }
                }else if(node.getName()== sMapping && orgMapping.get(sMapping).Is_Date_Field__c){
                    if(node.getText().trim() !=Null){
                        temppro.put(orgMapping.get(sMapping).Target_Field__c,Date.valueof(node.getText().trim()));
                        system.debug(orgMapping.get(sMapping).Target_Field__c+' Date Mapping values ---------->>>>>'+temppro);
                    }
                }else if(node.getName()== sMapping && orgMapping.get(sMapping).Is_Integer__c){
                    if(node.getText().trim() !=Null){
                        temppro.put(orgMapping.get(sMapping).Target_Field__c,node.getText().trim());
                        system.debug(orgMapping.get(sMapping).Target_Field__c+' Integer Mapping values ---------->>>>>'+temppro);
                    }
                }
            }
        }
        for (Dom.XMLNode child: node.getChildElements()) {
            parseXML(child);
        }
    }

}

Source Org code snippet for exposing XML :


@RestResource(urlMapping = '/GETSaamTestSearches/*')
global with sharing class GETSaamTestSearches {
    @HttpGet
    global static void doGet() {
        string sResOutPut = '';
        try {
            RestRequest req = RestContext.request;
            RestResponse res = RestContext.response;
            res.addHeader('Content-Type', 'application/xml');
            SVendorId = req.requestURI.substring(req.requestURI.lastIndexOf('/') + 1);
            sResOutPut = '<?xml version="1.0" encoding="UTF-8"?>';
            sResOutPut += '<SearchestoProcess>';
            date dCurrentDate = System.today();
            for (Account oBGS: [SELECT Id, name, AccountNumber, Website, Site, Type, Phone, Rating, Fax, Sic, Industry, Source__c, Source_Description__c, AnnualRevenue, Ownership, TickerSymbol, CustomerPriority__c, SLA__c, Active__c, NumberofLocations__c, UpsellOpportunity__c, SLASerialNumber__c, SLAExpirationDate__c FROM Account where Annualrevenue != null and Industry != null and Source__c != null ORDER BY name desc]) {
                sResOutPut += '<row>';
                //************************************
                sResOutPut += '<Name>' + ChecknullString(oBGS.name) + '</Name>';
                sResOutPut += '<Source__c>' + ChecknullString(oBGS.Source__c) + '</Source__c>';
                sResOutPut += '<Type>' + ChecknullString(oBGS.Type) + '</Type>';
                sResOutPut += '<Rating>' + ChecknullString(oBGS.Rating) + '</Rating>';
                sResOutPut += '<Phone>' + ChecknullString(oBGS.Phone) + '</Phone>';
                sResOutPut += '<Fax>' + ChecknullString(oBGS.Fax) + '</Fax>';
                sResOutPut += '<Site>' + ChecknullString(oBGS.Site) + '</Site>';
                sResOutPut += '<Source_Description__c>' + ChecknullString(oBGS.Source_Description__c) + '</Source_Description__c>';
                sResOutPut += '<Website>' + ChecknullString(oBGS.Website) + '</Website>';
                sResOutPut += '<Sic>' + ChecknullString(oBGS.Sic) + '</Sic>';
                sResOutPut += '<Industry>' + ChecknullString(oBGS.Industry) + '</Industry>';
                sResOutPut += '<AnnualRevenue>' + ChecknullString(String.valueof(oBGS.AnnualRevenue)) + '</AnnualRevenue>';
                sResOutPut += '<Ownership>' + ChecknullString(oBGS.Ownership) + '</Ownership>';
                sResOutPut += '<TickerSymbol>' + ChecknullString(oBGS.TickerSymbol) + '</TickerSymbol>';
                sResOutPut += '<CustomerPriority__c>' + ChecknullString(oBGS.CustomerPriority__c) + '</CustomerPriority__c>';
                sResOutPut += '<SLA__c>' + ChecknullString(oBGS.SLA__c) + '</SLA__c>';
                sResOutPut += '<Active__c>' + ChecknullString(oBGS.Active__c) + '</Active__c>';
                sResOutPut += '<NumberofLocations__c>' + ChecknullString(String.valueof(oBGS.NumberofLocations__c)) + '</NumberofLocations__c>';
                sResOutPut += '<UpsellOpportunity__c>' + ChecknullString(oBGS.UpsellOpportunity__c) + '</UpsellOpportunity__c>';
                sResOutPut += '<SLASerialNumber__c>' + ChecknullString(oBGS.SLASerialNumber__c) + '</SLASerialNumber__c>';
                sResOutPut += '<SLAExpirationDate__c>' + ChecknullString(String.valueof(oBGS.SLAExpirationDate__c)) + '</SLAExpirationDate__c>';
                sResOutPut += '<AccountNumber>' + ChecknullString(oBGS.AccountNumber) + '</AccountNumber>';
                //************************************
                sResOutPut += '</row>';
            }
            //sResOutPut += '<message>Success</message>';
            sResOutPut += '</SearchestoProcess>';
            Dom.Document domDoc = new Dom.Document();
            domDoc.load(sResOutPut);
        } catch (exception ex) {
            sResOutPut = '<?xml version=\'1.0\' encoding=\'UTF-8\'?><SearchestoProcess><message>';
            sResOutPut += 'Error while processing the records +' + ex.getmessage() + '</message></SearchestoProcess>';
        }
        RestContext.response.responseBody = Blob.valueOf(sResOutPut);
    }

    public static string SVendorId {
        get;
        private set;
    }

    public static string ChecknullString(string sVal) {
        if (sVal == null) {
            sVal = '';
        } else {
            //*****XML scape charactor
            sVal = sVal.Replace('&', '&amp;').Replace('>', '&gt;').Replace('<', '&lt;').Replace('\'', '&apos;').Replace('"', '&quot;');
        }
        return sVal;
    }

Output :

<?xml version="1.0" encoding="UTF-8"?>
<SearchestoProcess>
    <row>
        <Name>United Oil &amp; Gas, UK</Name>
        <Source__c>SFDC</Source__c>
        <Type>Customer - Direct</Type>
        <Rating>Warm</Rating>
        <Phone>+44 191 4956203</Phone>
        <Fax>+44 191 4956620</Fax>
        <Site>www.site.com</Site>
        <Source_Description__c>To make historical trend reports available to your users, start by using filters to configure the amount of data that’s captured for historical trend reporting. Then select the fields needed for historical reports.</Source_Description__c>
        <Website>http://www.uos.com</Website>
        <Sic>4437</Sic>
        <Industry>Energy</Industry>
        <AnnualRevenue>100000</AnnualRevenue>
        <Ownership>Public</Ownership>
        <TickerSymbol>UOS</TickerSymbol>
        <CustomerPriority__c>High</CustomerPriority__c>
        <SLA__c>Platinum</SLA__c>
        <Active__c>Yes</Active__c>
        <NumberofLocations__c>34</NumberofLocations__c>
        <UpsellOpportunity__c>No</UpsellOpportunity__c>
        <SLASerialNumber__c>3479</SLASerialNumber__c>
        <SLAExpirationDate__c>2017-12-05</SLAExpirationDate__c>
        <AccountNumber>CD355119-A</AccountNumber>
    </row>

</SearchestoProcess>

Search one salesforce organization records from another salesforce organization using Rest API callouts

Access Token Snippet :


Public class Org_GlobalAccessToken_Cls {
    Public Static String clientId = EncodingUtil.urlEncode('3MVG9I5UQ_0k_hTm9p9qVC3ruJI49xkzjVd51JkCiNN7tPr.qUcphB8KZFvrQGm9XnO6r5PX6GJKyG_F9rRmK', 'UTF-8');
    Public Static String clientSecret = EncodingUtil.urlEncode('387843950858359729', 'UTF-8');
    Public Static String username = EncodingUtil.urlEncode('sourceorganization@yopmail.com', 'UTF-8');
    Public Static String password = EncodingUtil.urlEncode('Mardal786*', 'UTF-8');
    Public Static String reqbody = 'grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password;
    public static string cmdAccessToken() {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://eu9.salesforce.com/services/oauth2/token');
        HttpResponse res = h.send(req);
        if (res.getstatuscode() == 200) {
            GrantAccessToken accessToken = (GrantAccessToken) JSON.deserialize(res.getbody(),GrantAccessToken.class);
            system.debug('**********'+res.getbody());
            if (accessToken.access_token != null) {
                system.debug('**********'+accessToken.access_token);
                return accessToken.access_token;
            } else {
                return null;
            }
        }
        return null;
    } 
    public class GrantAccessToken {
        public String id {
            get;
            set;
        }
        public String issued_at {
            get;
            set;
        }
        public String instance_url {
            get;
            set;
        }
        public String signature {
            get;
            set;
        }
        public String access_token {
            get;
            set;
        }
    }   
}

Main apex logic :

Public class GlobalAccessToken_Cls {
   
    Public String acctId {
        get;
        set;
    }
    public void cmdListContact() {
        callgetContact(acctId);
    }
    public List <Contact> lstContact {
        get;
        set;
    }
    public String jsonString {get;set;}
    public List < Contact > callgetContact(String accId) {
        lstContact = new List <Contact>();
        String accessToken = Org_GlobalAccessToken_Cls.cmdAccessToken();  
        system.debug('~~~~~~~~~~~~~~~'+accessToken);
        if (accessToken != null) {
            system.debug('~~~~~~~~~~~~~~~'+accessToken);
            String endPoint = 'https://eu9.salesforce.com/services/apexrest/v1/getContacts/' + accId;
            Http h2 = new Http();
            HttpRequest req1 = new HttpRequest();
            req1.setHeader('Authorization', 'Bearer ' + accessToken);
            req1.setHeader('Content-Type', 'application/json');
            req1.setHeader('accept', 'application/json');
            req1.setMethod('GET');
            req1.setEndpoint(endPoint);
            HttpResponse res1 = h2.send(req1);
            system.debug('~~~~~~~~~~~~~~~'+res1.getBody());
            String trimmedResponse = res1.getBody().unescapeCsv().remove('\\');
            system.debug('@@@RESPONSE@@' + trimmedResponse);
            JSONParser parser = JSON.createParser(res1.getBody());
            set < Contact > contList = new set < Contact > ();
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME)) {
                    Contact cont;
                    if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'Id')) {
                        parser.nextToken();
                        string sId = parser.getText();
                        cont = new Contact();
                        cont.Id = sId;
                        parser.nextToken();
                        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'Name')) {
                            parser.nextToken();
                            String sName = parser.getText();
                            cont.LastName = sName;
                        }
                        parser.nextToken();
                        if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&(parser.getText() == 'Email')) {
                            parser.nextToken();
                            string sEmail = parser.getText();
                            cont.Email = sEmail;
                        }
                    }
                    contList.add(cont);
                }
                contList.remove(null);
            }
            lstContact.AddAll(contList);
            system.debug('ContList@@@@' + Json.serialize(lstContact));
            jsonString = Json.serialize(lstContact);
        }
        return LstContact;
    }
}

Visualforce Page :

<apex:page controller="GlobalAccessToken_Cls">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:outputPanel >
                <apex:outputLabel value="Account ID"/>&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:inputText value="{!acctId}" label="AccountID"/>&nbsp;&nbsp;&nbsp;&nbsp;
                <apex:commandButton value="Go" action="{!cmdListContact}"/>
                </apex:outputPanel>
            </apex:pageBlockSection>
            {!jsonString}
            <apex:pageBlockTable value="{!lstContact}" var="c">
               <apex:column value="{!c.Id}"/> 
               <apex:column value="{!c.LastName}"/>
               <apex:column value="{!c.Email}"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Screenshot For Reference :


Integration between two Salesforce organizations using Rest API

Step 1 : Create one connect app in target organization. Refer the below screenshot



Step 2 : Here we are going to integrate between two two account objects. Whenever we create any account record though Rest API. It would be created one account record in target org.

Trigger Code Snippet :

trigger Org_RestAPIEmployee_Trg on Account (after insert) {
    for(Account acct : trigger.new){
        Org_RestAPIEmployee_Cls.createAccount(acct.Id);
    }
}

Helper Code Snippet :

global class Org_RestAPIEmployee_Cls {
    @future(callout = true)
    global static void createAccount(String acctID) {
        String accessToken = Org_GlobalAccessToken_Cls.cmdAccessToken();
        String queryString;
        String JSONString;
        List < Account > acctTemp = null;
        system.debug('accessToken ********' + accessToken);
        if (accessToken != null) {
            queryString = 'select id';
            //Created Org_EMployeeRules fieldset for future reference i.e no need to edit the class in future just we need to add the requered fields for mapping purpose
            for (Schema.FieldSetMember fld: SObjectType.Account.FieldSets.Org_EMployeeRules.getFields()) {
                queryString += ', ' + fld.getFieldPath();
            }
            queryString += ' from Account where Id=:acctID limit 1 ';
            system.debug(accessToken);
            String endPoint = 'https://eu9.salesforce.com/services/data/v32.0/sobjects/Account/';
            if (String.isNotBlank(queryString)) {
                acctTemp = database.query(queryString);
            }
            Map < String, object > mapEmpTemp = new Map < String, object > ();
            //Store all the required fields in custom settings for accessing dynamically
            for (Org_Employee_Constant__c strTemp: Org_Employee_Constant__c.getAll().values()) {
                mapEmpTemp.put(strTemp.name, acctTemp[0].get(strTemp.name));
            }
            if (!mapEmpTemp.isEmpty()) {
                JSONString = JSON.serialize(mapEmpTemp);
            }
            Http h2 = new Http();
            HttpRequest req1 = new HttpRequest();
            req1.setHeader('Authorization', 'Bearer ' + accessToken);
            req1.setHeader('Content-Type', 'application/json');
            req1.setHeader('accept', 'application/json');
            req1.setBody(JSONString);
            req1.setMethod('POST');
            req1.setEndpoint(endPoint);
            HttpResponse resp = h2.send(req1);
            system.debug(resp.getbody());
            if (resp.getStatusCode() == 200 || resp.getStatusCode() == 201) {
                deserializeResponse deserializeResponseTemp = (deserializeResponse) JSON.deserialize(resp.getbody(), deserializeResponse.class);
                List < Account > acctList = new List < Account > ();
                Account a = [SELECT Id FROM Account WHERE Id =: acctID];
                a.externalId__c = deserializeResponseTemp.id;
                a.description = queryString;
                a.Json_Response__c = JSONString;
                acctList.add(a);
                Database.SaveResult[] updateResults = Database.update(acctList, false);
                String successErrorMessage;
                for (Integer i = 0; i < updateResults.size(); i++) {
                    if (updateResults.get(i).isSuccess()) {
                        updateResults.get(i).getId();
                        successErrorMessage = 'Successfully inserted account. Account ID: ' + updateResults.get(i).getId() + '\n';

                    } else if (!updateResults.get(i).isSuccess()) {
                        Database.Error error = updateResults.get(i).getErrors().get(0);
                        String failedDML = error.getMessage();
                        acctList.get(i);
                        system.debug('Failed ID' + acctList.get(i).Id);
                        successErrorMessage = 'Error Messge : ' + error.getMessage() + '\n' + 'Failed ID' + acctList.get(i).Id;
                    }
                }
                system.debug(successErrorMessage);
            }
        }
    }
    public class deserializeResponse {
        public String id;
        public String access_token;
    }

}

Access Token Code Snippet :


Public class Org_GlobalAccessToken_Cls {
    Public Static String clientId = EncodingUtil.urlEncode('3MVG9I5UQ_0k_hTm9p9qVC3ruJI49xkzjVd51JkCiNN7tPr.qUcphB8KZFvrQGm9XnO6r5PX6GJKyG_F9rRmK', 'UTF-8');
    Public Static String clientSecret = EncodingUtil.urlEncode('387843950858359729', 'UTF-8');
    Public Static String username = EncodingUtil.urlEncode('******User Name*****', 'UTF-8');
    Public Static String password = EncodingUtil.urlEncode('******Password*****', 'UTF-8');
    Public Static String reqbody = 'grant_type=password&client_id=' + clientId + '&client_secret=' + clientSecret + '&username=' + username + '&password=' + password;
    public static string cmdAccessToken() {
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        req.setBody(reqbody);
        req.setMethod('POST');
        req.setEndpoint('https://eu9.salesforce.com/services/oauth2/token');
        HttpResponse res = h.send(req);
        if (res.getstatuscode() == 200) {
            GrantAccessToken accessToken = (GrantAccessToken) JSON.deserialize(res.getbody(),GrantAccessToken.class);
            system.debug('**********'+res.getbody());
            if (accessToken.access_token != null) {
                system.debug('**********'+accessToken.access_token);
                return accessToken.access_token;
            } else {
                return null;
            }
        }
        return null;
    } 
    public class GrantAccessToken {
        public String id {
            get;
            set;
        }
        public String issued_at {
            get;
            set;
        }
        public String instance_url {
            get;
            set;
        }
        public String signature {
            get;
            set;
        }
        public String access_token {
            get;
            set;
        }
    }   
}

Get Salesforce ID from mixed combination

Code Snippet :

String s = '01:a3E340000005BqbEAE,02:a3E340000005BqcEAE,03:a3E340000005BqdEAE';
Set<Id> setAnsId = new Set<id>();
for(String ss : s.split(',')){
    setAnsId.add(Id.valueOf(ss.subString(ss.indexOf(':')+1,ss.length())));
}
system.debug(setAnsId);

Solution :

{a3E340000005BqbEAE, a3E340000005BqcEAE, a3E340000005BqdEAE}

Insert Custom VF into standard layout and refresh both standard layout and Custom VF

<apex:page standardController="Leave_Plan__c" extensions="_Leaveplan_CTE" action="{!approvalNeeded}">
        <center>
            <apex:pageMessages ></apex:pageMessages>                
         
            <apex:outputPanel rendered="{!IF(Leave_Plan__c.Status__c == 'Approved',true,false)}">
                <font color="green" size="2"><b>
                <apex:image id="theImage" value="{!$Resource.Smily}" width="15" height="15"/>Your request has been approved.</b></font>
            </apex:outputPanel><br/><br/>
         
            <apex:outputPanel rendered="{!IF(Leave_Plan__c.Status__c == 'Rejected',true,false)}">
                <font color="red" size="2"><b>
                <apex:image id="theImage1" value="{!$Resource.Sad}" width="15" height="15"/>Your request has been rejected.</b></font>
            </apex:outputPanel>
         
            <apex:outputPanel rendered="{!IF(AND(Leave_Plan__c.Status__c == 'Cancel',CONTAINS($UserRole.Name,'Employee')),true,false)}">
                <font color="red" size="2"><b>
                <apex:image value="{!$Resource.Sad}" width="15" height="15"/>Something went wrong please create new record don't edit this record</b></font>
            </apex:outputPanel>
         
            </center>
            <center><apex:outputLabel rendered="{!showAlert}">
                <apex:image id="theImage2" value="{!$Resource.Smily}" width="15" height="15"/>
                <font color="red" size="2"><b>Please refresh the page.This record has been sent for Approval already.</b></font>
                </apex:outputLabel></center>
                <center><apex:outputLabel rendered="{!showAlert1}">
                <apex:image id="theImage4" value="{!$Resource.Smily}" width="15" height="15"/>
                <font color="red" size="2"><b>You are not an authorized to submit this record for Approval</b></font>
                </apex:outputLabel></center>
            <center>
            <apex:outputpanel rendered="{!refreshPage}" style="margin-left:-30%;">
                <script>
                window.top.location='/{!Leave_Plan__c.id}';
            </script>
            </apex:outputpanel>
            <apex:form >
                <apex:outputPanel rendered="{!requiredSection}">
                <b>Please Select cancel reason : </b>&nbsp; &nbsp;
                <apex:selectList value="{!strComment}" size="1" required="true">
                    <apex:selectOptions value="{!Options}"></apex:selectOptions>
                </apex:selectList><br/>
                <apex:commandButton value="Cancel Leave" action="{!cmdCancelLeave}" title="Cancel Leave" alt="Cancel Leave"/>
              </apex:outputPanel>                              
                    <apex:commandButton value="Approve" action="{!cmdApprove}" rendered="{!approveShow}"/>
                    <apex:commandButton value="Reject" action="{!cmdReject}" rendered="{!rejectShow}" />
                    <apex:commandButton value="Submit for Approval" action="{!cmdSubmitforApproval}"
                    rendered="{!IF(Leave_Plan__c.Status__c=="New Request",true,false)}"/>
                    <apex:commandButton value="Cancel Request" action="{!cmdCancelRequest}"
                    rendered="{!IF(AND(Leave_Plan__c.Status__c!="Cancel",NOT(CONTAINS($UserRole.Name, 'Employee'))),true,false)}"/>
                    <!--<apex:commandButton value="Cancel Leave" action="{!cmdCancelLeave}"                  
                    rendered="{!IF(AND(OR(Leave_Plan__c.Status__c=="New Request",
                                      Leave_Plan__c.Status__c=="Approval Pending",
                                      Leave_Plan__c.Status__c=="Approved",
                                      Leave_Plan__c.Status__c=="Recancelled"),
                                      NOT(CONTAINS($UserRole.name, 'Employee'))),true,false)}"/>-->
                    <apex:commandButton value="Reassign"  action="{!Reassign}" rendered="{!reassignShow}"/>
                    <apex:commandButton value="Cancel" action="{!cmdCancel}" rendered="{!IF(OR(Leave_Plan__c.Status__c=="New Request",
                                      Leave_Plan__c.Status__c=="Approval Pending",
                                      Leave_Plan__c.Status__c=="Approved",
                                      Leave_Plan__c.Status__c=="Recancelled"),true,false)}"/>
                    <apex:commandButton value="Re-Request" action="{!cmdRerequest}"
                    rendered="{!IF(Leave_Plan__c.Status__c=="Rejected",true,false)}"/>
            </apex:form>
        </center>
</apex:page>


Apex:--

public class _Leaveplan_CTE{
    //@Initial varialbles declaration
    public final Leave_Plan__c leaveIds ;
    public final Leave_Plan__c leaveDetail;
    public boolean refreshPage {get;set;}
    public boolean approveShow {get;set;}
    public boolean rejectShow {get;set;}
    public boolean reassignShow {get;set;}
    public boolean showAlert {get;set;}
    public boolean showAlert1 {get;set;}
    public boolean cmdCancelLeaveShow  {get;set;}
    public boolean cmdCancelShow {get;set;}
    public boolean requiredSection {get;set;}
    public string strComment {get;set;}
    //@Standard controller defination
    public _Leaveplan_CTE(Apexpages.standardcontroller controller){
        refreshPage = false;
        showAlert = false;
        showAlert1 = false;
        cmdCancelLeaveShow = true;
        requiredSection = false;
        this.leaveIds = (Leave_Plan__c) controller.getRecord();
        //@fetching complete record details from standard UI to class based on Id
        leaveDetail = [select id,name,Company__c,Current_Approval_Status__c,Date_From__c,Date_To__c,
                      Email_Id__c,Employee_ID__c,Employee_Name1__c,First_Approval__c,Description__c,
                      Leave_Type__c,Location__c,Manager_Approval__c,Number_of_Days__c,Request_Submitted_on__c,
                      Status__c,Time_out_of_office__c,Employee_Name__c from Leave_Plan__c where id =:leaveIds.id limit 1];
    }
    //@This method will call at the time of user clicks on submit for approval process button
    public pageReference cmdSubmitforApproval(){
        cmdCancelLeaveShow = true;
        User usr = [select id,name,userroleid,UserRole.Name from user where userroleid=:UserInfo.getUserRoleId() limit 1];
        Leave_Plan__c l = new Leave_Plan__c();
        l = [select id,status__c from Leave_Plan__c where id=:leaveDetail.id];
        if(l.status__c == 'Approval Pending'){
           // ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.Info, 'Your Lead is sent to Approval process already.');
            //ApexPages.addMessage(msg);
            showAlert = true;
            return null;
        }
        if(usr.UserRole.Name.contains('Employee')){
        try{
         Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
           req1.setObjectId(leaveIds.id);
           Approval.ProcessResult result = Approval.process(req1);
           refreshPage = true;
           }catch(Exception e){
               ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error occured' + e.getMessage()));
           }
        return null;
        }else{
            showAlert1 = true;
            return null;
        }
    return null;
    }
    //@Method: This will call and display Approve or Reject buttons based on user group membership
    public void approvalNeeded(){
        cmdCancelLeaveShow = true;
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
                    LIST < GroupMember > actList = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                             UserOrGroupId IN : mapIdGroup.keySet()];
                    set<Id> actId = new set<Id>();
                    if (actList.size() > 0) {
                        for(GroupMember g:actList){
                            actId.add(g.GroupId);
                        }
                    }

                    Integer i = [SELECT count()
                        FROM ProcessInstanceWorkItem
                        WHERE ProcessInstance.Status = 'Pending'
                        AND ProcessInstance.TargetObjectId = : leaveIds.Id AND(ActorId IN : actId OR ActorId = : UserInfo.getUserId())
                        LIMIT 1
                    ];

                    if (i > 0) {
                        approveShow = true;
                        rejectShow = true;
                        reassignShow = true;
                    } else {
                        approveShow = false;
                        rejectShow = false;
                        reassignShow = false;
                    }
    }
    //@Method:This method will call at the time of user clicks on Approval button
    public pageReference cmdApprove(){
        cmdCancelLeaveShow = true;
        Set<id> actId = new Set<Id>();
        //@Fetching group membership here
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
        List<GroupMember > grp = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                  UserOrGroupId IN : mapIdGroup.keySet()];
        for(GroupMember g : grp){
            actId.add(g.GroupId);
        }
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and
            processinstance.targetobjectid = :leaveIds.id AND(ActorId = :UserInfo.getUserId() or ActorId=:actId ) limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Approve');
            req.setComments('Approved Happy vacation');
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            refreshPage = true;
    return null;  
    }
    //@Method : This method will call at the time of Lead or Manager clicks on reject button
    public pageReference cmdReject(){
        try{
        cmdCancelLeaveShow = true;
        Set<id> actId = new Set<Id>();
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
        List<GroupMember > grp = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                  UserOrGroupId IN : mapIdGroup.keySet()];
        for(GroupMember g : grp){
            actId.add(g.GroupId);
        }
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and
            processinstance.targetobjectid = :leaveIds.id AND(ActorId = :UserInfo.getUserId() or ActorId=:actId ) limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Reject');
            req.setComments('Rejected adjust your days');
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            refreshPage = true;
            }catch(Exception e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error occured' + e.getMessage()));
            }
    return null;  
    }
    //@Method:This method will refresh standard and custom UI
    public pageReference cmdCancel(){
        refreshPage = true;
    return null;
    }
    //@Method : Re-request will happen here
    public pageReference cmdRerequest(){  
     try{
     User usr = [select id,name,userroleid,UserRole.Name from user where userroleid=:UserInfo.getUserRoleId() limit 1];
     if(usr.UserRole.Name.contains('Employee')){}
     cmdCancelLeaveShow = true;
     Leave_Plan__c l1 = new Leave_Plan__c();
        l1 = [select id,status__c,Date_From__c,Date_To__c,First_Approval__c,Manager_Approval__c,
            Current_Approval_Status__c from Leave_Plan__c where id=:leaveDetail.id limit 1];
            l1.status__c = 'New Request';
            l1.Date_From__c = null;
            l1.Date_To__c = null;
            l1.Time_out_of_office__c = null;
            l1.First_Approval__c = false;
            l1.Manager_Approval__c = false;
            l1.Current_Approval_Status__c = '';
            Database.update(l1);
            refreshPage = true;
       }catch(Exception e){
           ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, 'Error occured' + e.getMessage()));
           refreshPage = true;
       }      
     refreshPage = true;
     return null;
    }
    //@Method:method re-assignment will be done here
   public PageReference Reassign(){
       try{
        cmdCancelLeaveShow = true;
        List<ProcessInstanceWorkItem> workItemList = [Select p.ProcessInstance.Status, p.ProcessInstance.TargetObjectId,p.ProcessInstanceId,p.OriginalActorId,p.Id,p.ActorId
        From ProcessInstanceWorkitem p where p.ProcessInstance.TargetObjectId = :leaveIds.Id];
        Leave_Plan__c l = new Leave_Plan__c();
        l = [select id from Leave_Plan__c where id=:leaveDetail.id limit 1];
        String retId =l.id;
        String strAppId = workItemList[0].Id;
        String partialURL = '/' + strAppId + '/e?et=REASSIGN&retURL=%2F'+retId;
        PageReference pageRef = new PageReference(partialURL);
        refreshPage = true;
        return pageRef;
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,''+ e.getMessage()));
        }
        return null;
        }
    //@Method:It will cancel leaves and leave process will end here
    /*public Pagereference cmdCancelLeave(){
        try{
     
       Set<id> actId = new Set<Id>();
        map<Id,Group> mapIdGroup = new map<Id,Group>([SELECT Id from Group where RelatedId = : UserInfo.getUserRoleId()]);
        List<GroupMember > grp = [SELECT GroupId from GroupMember where UserOrGroupId =: UserInfo.getUserId() OR
                                  UserOrGroupId IN : mapIdGroup.keySet()];
        for(GroupMember g : grp){
            actId.add(g.GroupId);
        }
        if(leaveDetail.status__c == 'Approval Pending'){
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and
            processinstance.targetobjectid = :leaveIds.id AND(ActorId = :UserInfo.getUserId() or ActorId=:actId ) limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Reject');
            req.setComments('Cancelled apply for new leave');
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            }
            Leave_Plan__c l = new Leave_Plan__c();
            l = [select id,status__c,recordtypeid from Leave_Plan__c where id=:leaveDetail.id limit 1];
            l.status__c = 'Cancel';
            l.First_Approval__c = false;
            l.Manager_Approval__c = false;
            l.recordtypeid = '012280000005BKGAA2';
            Database.update(l);
            refreshPage = true;
            reassignShow = false;
            approveShow = false;
            rejectShow = false;
            cmdCancelLeaveShow = false;
            cmdCancelShow = false;
            }catch(Exception e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,''+ e.getMessage()));
            }
    return null;  
    }*/
    //@Method:It will cancel leaves and leave process will end here
    public Pagereference cmdCancelLeave(){
        ObjectRecordTypeIds__c orgConstant = ObjectRecordTypeIds__c.getInstance();
        String closedLeaveRecordtypeId = orgConstant.Marketing_Lead_RecordType__c;
        try{
        if(leaveDetail.status__c == 'Approval Pending'){
        List <ProcessInstanceWorkItem> items = [select id,processinstanceid,processinstance.status,processinstance.targetobjectid,ActorId from ProcessInstanceWorkitem
            where processinstance.status='Pending' and processinstance.targetobjectid = :leaveIds.id limit 1];
            Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
            req.setAction('Reject');
            req.setComments(strComment);
            req.setWorkitemId(items[0].Id);
            Approval.ProcessResult result = Approval.process(req);
            }
            Leave_Plan__c l = new Leave_Plan__c();
            l = [select id,status__c,First_Approval__c,Manager_Approval__c,recordtypeid,Cancel_Reason__c from Leave_Plan__c where id=:leaveDetail.id limit 1];
            l.status__c = 'Cancel';
            l.First_Approval__c = false;
            l.Manager_Approval__c = false;
            l.Cancel_Reason__c=strComment;
            l.recordtypeid = ObjectRecordTypeId__c.getInstance('Closed Leave').Marketing_Lead_RecordType__c;
            Database.update(l);
            refreshPage = true;
            reassignShow = false;
            approveShow = false;
            rejectShow = false;
            cmdCancelLeaveShow = false;
            cmdCancelShow = false;
            }catch(Exception e){
                ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,''+ e.getMessage()));
            }
    return null;  
    }
    public pagereference cmdCancelRequest(){
    requiredSection = true;
    reassignShow = false;
    approveShow = false;
    rejectShow = false;
 
    return null;
    }
    public List<SelectOption> getOptions(){
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Adjust your days','Adjust your days'));
        options.add(new SelectOption('Cancelled no requalification','Cancelled no requalification'));
        options.add(new SelectOption('Cancel your request','Cancel your request'));
        options.add(new SelectOption('Something went wrong on dates','Something went wrong on dates'));
        options.add(new SelectOption('Dont plan this week','Dont plan this week'));
        return options;
    }
    //@Method : Invoke apex method at the time of user clicking send to leaves button
    public pagereference cmdSendLeave(){
        User usr = [select id,name,userroleid,UserRole.Name from user where userroleid=:UserInfo.getUserRoleId() limit 1];
     if(usr.UserRole.Name.contains('Employee')){}
     cmdCancelLeaveShow = true;
       
     Leave_Plan__c l1 = new Leave_Plan__c();
        l1 = [select id,status__c,Date_From__c,Date_To__c,First_Approval__c,Manager_Approval__c,
            Current_Approval_Status__c from Leave_Plan__c where id=:leaveDetail.id limit 1];
            //Map<string,ObjectRecordTypeId__c> orga =ObjectRecordTypeId__c.getAll();
            //if(orga.containsKey('Closed Leave')){
            //l1.recordtypeId = orga.get(l1.id).name;
            //}
            l1.status__c = 'send to report';
            l1.Date_To__c = null;
            l1.Time_out_of_office__c = null;
            l1.First_Approval__c = false;
            l1.Manager_Approval__c = false;
            l1.Current_Approval_Status__c = '';
            Database.update(l1);          
            refreshPage = true;
            requiredSection = true;
            reassignShow = false;
            approveShow = false;
            rejectShow = false;
     return null;  
    }
    public static void deletePreventTriggerMethod(List<Leave_Plan__c> leaveIds){
        User currentUserRole = [select id,profileid,profile.name from User where id=:UserInfo.getUserId() limit 1 ];
        if(!currentUserRole.profile.name.contains('System Administrator')){
        for(Leave_Plan__c leaveId : leaveIds){
            leaveId.addError('You are not an authorized to delete this record contact your Admin');
        }
     }
   }
}

Choosen Picklist and jQuery form validation in visualforce with css



VF Code:

<apex:page controller="myController" docType="html-5.0" standardStylesheets="false" sidebar="false" showHeader="false">  
        <apex:pageMessages ></apex:pageMessages>
        <apex:includeScript value="{!$Resource.jQuery_Min}"/>      
        <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" />  
        <apex:includeScript value="https://ajax.microsoft.com/ajax/jquery.validate/1.6/jquery.validate.min.js"/>      
        <apex:includeScript value="{!$Resource.chosen_jquery_min}"/>
        <apex:stylesheet value="{!$Resource.cssFile}"/>
        <apex:stylesheet value="{!$Resource.chosen_min}"/>
        <style>
            .choiceChosen, .productChosen {
                  width: 300px ;
             }
            .error{
              color:red;
            }
        </style>
        <script>
            $(document).ready(function(){
             
                $(".choiceChosen, .productChosen").chosen({});
                  $(".choiceChosen").change(function(){
                    if($(".choiceChosen option:selected").val()=="no"){
                      $(".productChosen option[value='2']").attr('disabled',true).trigger("chosen:updated");
                      $(".productChosen option[value='1']").removeAttr('disabled',true).trigger("chosen:updated");
                    } else {
                      $(".productChosen option[value='1']").attr('disabled',true).trigger("chosen:updated");
                      $(".productChosen option[value='2']").removeAttr('disabled',true).trigger("chosen:updated");
                    }
                })
             
            });
        </script>
        <apex:form id="CustomerForm">
        <body>
            <br/><br/><br/><br/>
            <div id="wrapper">
                <fieldset style="width: 600px;!important">
                    <legend>Wait List form for Attendee </legend>
                    <div>
                        <label id=""></label>
                        <apex:inputText value="{!FirstName}" html-placeholder="First Name" id="firstName"/>
                    </div>
                    <div>
                        <apex:inputText value="{!LastName}" html-placeholder="Last Name" id="lastName"/>
                    </div>
                    <div>
                        <apex:inputSecret value="{!password}" html-placeholder="Password" id="password"/>
                    </div>
                    <div>
                        <apex:inputText value="{!email}" html-placeholder="Email" id="emailID"/>
                    </div>
                      <div>
                          <apex:selectList styleClass="choiceChosen" value="{!InactiveListValue}" id="InactiveList">
                              <apex:selectOptions value="{!InactiveList}"/>
                          </apex:selectList>
                      </div><br/>
                      <div>
                          <apex:selectList styleClass="choiceChosen" multiselect="true" value="{!countryListValue}" id="countryList">
                              <apex:selectOptions value="{!countryList}"/>
                          </apex:selectList>
                      </div>
                      <apex:commandButton action="{!createRecord}" value="Submit" id="submit" styleClass="submit"/>
                </fieldset>
            </div>
        <script type="text/javascript">
            $('[id$=CustomerForm]').validate();
            $('[id$=firstName]').rules("add",{
                required: true,
                minlength: 5,
                maxlength: 50,            
                messages:{
                required:"Required First Name",
                minlength: jQuery.validator.format("Please etner at least 5 characters are necessary"),
                }                        
            });
            $('[id$=lastName]').rules("add",{
                required: true,
                minlength: 5,
                maxlength: 50,            
                messages:{
                required:"Required Last Name",
                minlength: jQuery.validator.format("Please etner at least 5 characters are necessary"),
                }                        
            });
            $('[id$=emailID]').rules("add",{
                required: true,
                email:true,            
                messages:{
                required:"Required Email",
                email: jQuery.validator.format("Please enter valid email id"),
                }                        
            });
            $('[id$=password]').rules("add",{
                required: true,                        
                messages:{
                required:"Required Password",              
                }                        
            });
                   
        </script>
        </body>
    </apex:form>

</apex:page>

Apex Class :--

public with sharing class myController {
    public String email { get; set; }
    public String password { get; set; }
    public String LastName { get; set; }
    public String FirstName { get; set; }
    public string countryListValue { get;set; }
    public string InactiveListValue {get;set;}
    public static Map<string,MappingDetails__c> custMap;
    static {
       custMap = MappingDetails__c.getAll();      
    }
    public List<SelectOption> getCountryList(){
        List<SelectOption> options =  new List<SelectOption>();
        for(String custDetails : custMap.keySet()){
            options.add(new selectoption(custDetails,custDetails));
        }
    return options;
    }
     public List<SelectOption> getInactiveList(){
        List<SelectOption> options =  new List<SelectOption>();
        for(MappingDetails__c custDetails : custMap.values()){
            options.add(new selectoption(custDetails.Inactive_Queue__c,custDetails.Inactive_Queue__c));
        }
    return options;
    }
    public string testMessage {get;set;}
    public PageReference createRecord() {
        testMessage = FirstName +'-'+LastName+'-'+email+'-'+password+'-'+countryListValue;
        Car_Models__c c = new Car_Models__c();
        c.recordtypeid=Schema.SObjectType.Car_Models__c.getRecordTypeInfosByName().get('Employee Details').getRecordTypeId();
        c.First_Name__c = FirstName ;
        c.Last_Name__c = LastName;
        c.Password__c = password;
        c.Email__c = email;
        c.Inactive_Queue_Name__c = InactiveListValue ;
        c.Country_List__c = countryListValue;
        insert c;
        return new pagereference('/'+c.id);
    }
}

Featured

What is Cryptography in salesforce and what are all the algorithms provided by them ?

A). It is a security protocal between two systems. Lets say we are integration two systems without any encrytion mechanism then hackers wil...

Popular