Showing posts with label Visualforce. Show all posts
Showing posts with label Visualforce. Show all posts

Wednesday, May 9, 2018

Build URL to display a case using case number instead of Salesforce CaseID

This can be implemented using below code.

Custom label:  
Name: Case_Number_Details

Value: Please enter the valid 8 character Case Number (e.g. 00123456) after the equal sign in the URL above to view the case details.


Visualforce Page:


<apex:page controller="GetCaseByNumber" title="Get Case By Number" showHeader="false">

  <script>

      if ("{!CaseQuery}".length > 0) {

          if ("{!CaseQuery}" != "<apex:outputText value="{!$Label.Case_Number_Details}"/>" && "{!CaseQuery}" != "You Must Supply a Case Number") window.location = "/{!CaseQuery}";

      }

  </script>

  <h1 style="display:block;margin:25px;font-size:16px;">{!CaseQuery}</h1>


</apex:page>


Apex Class:


public class GetCaseByNumber {

    public static String getCaseQuery () {
       String caseNumberDetails = Label.Case_Number_Details;

        string caseNumber = ApexPages.CurrentPage().getParameters().get('CaseNumber');
        List <Case> c = [SELECT Id FROM Case Where CaseNumber =: caseNumber];
        if (c.size()>0) {
            return string.valueOf(c[0].Id);
        }
        else return caseNumberDetails;

    }    

}

Apex test Class:



private class GetCaseByNumberTest {
    
    static testmethod void TestAccdata(){ 
        Profile prof = [select id from profile where name='System Administrator'];    
        User us      = new User(alias = 'tuser', email='TestUser@testingorg.com',    
                                emailencodingkey='UTF-8', lastname='TestingUser', languagelocalekey='en_US', 
                                localesidkey='en_US', profileid = prof.Id,   
                                timezonesidkey='America/Los_Angeles', username='TestUser@testingorg.com');
        insert us;  
        System.runAs (us) { 
            Account ac = new Account(Name    ='Test', OwnerId  =us.Id);            
            insert ac;
            
            
            Contact cn  = new Contact (FirstName  = 'Test', LastName = 'Test',AccountId = ac.Id,email='testcase@org.com');
            insert cn;
            
            Test.startTest();
            string RTID = [select id from RecordType where SobjectType = 'Case' and Name = 'Support Case'].Id;
            System.assertNotEquals(null,RTID);
            
            case c = new Case(AccountId=ac.Id ,ContactId =  cn.Id,Status='New',Origin='Phone',RecordTypeId = RTID,Subject = 'TestCase',Description ='Test',Product_Type__c = 'My Product);
            
            insert c;
            PageReference myVfPage = Page.getCaseByNumber;
            Test.setCurrentPage(myVfPage);
           ApexPages.currentPage().getParameters().put('CaseNumber',ApexPages.currentPage().getParameters().get(c.CaseNumber));
            
            GetCaseByNumber controller = new GetCaseByNumber();
            GetCaseByNumber.getCaseQuery();
            
            Test.stopTest();
            
        }

    }



Friday, October 13, 2017

JavaScript in Strict Mode

JavaScript code that runs in a browser can access a user's private information. To protect this information, LockerService requires you to use ECMAScript (ES5) strict mode, and enforces it in your code. This mode makes it easier to write secure JavaScript. A few code tweaks to comply with ES5 can substantially reduce the need for checking data at runtime.

Here’s a simple example of how strict mode prevents JavaScript from traversing the call-stack and modifying other functions. Without strict mode, the following function would have returned the name of the function that called primaryFunction().

JavaScript code:
function primaryFunction() {
  'use strict'
  console.log("The function calling the current method is: “+ primaryFunction.caller.name);
}
function callerFunction() {
  return primaryFunction(); 
}
callerFunction();

Output:
Uncaught TypeError: 'caller' and 'arguments' are restricted function properties and cannot be accessed in this context.
at primaryFunction (<anonymous>:3:72) at callerFunction (<anonymous>:6:10) at <anonymous>:8:1

Strict mode restricts access to several other entities. When it is enforced, you can no longer reference the window object through the JavaScript variable this, for example. These restrictions eliminate a lot of potential security vulnerabilities.

Monday, April 17, 2017

How To Allow Only Numbers in Phone Number Field in Visual Force Page

If your trying to restrict your phone number field to accept only Numbers in visual force page you can use the below simple JavaScript code to achieve this easily.
<script>

function isNumber(evt) {
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }
}

</script>

<apex:inputfield value="{!c.Phone__c}" id="boPhone" onkeypress="return isNumber(event)"/>

Friday, April 14, 2017

What is difference between JavaScript Remoting and Remote Objects

JavaScript Remoting and Remote Objects offer similar features, and both are useful tools for creating dynamic, responsive pages. They have some important differences that you should consider before choosing which to use.

In general, Remote Objects is well-suited to pages that need to perform only simple Create-Read-Update-Delete, or “CRUD”, object access. JavaScript Remoting is better suited to pages that access higher-level server actions. Remote Objects lets you get up and running quickly without a lot of ceremony, while JavaScript Remoting is suited for more complex applications that require some up front API-style design work.

Visualforce Remote Objects:

1. Makes basic “CRUD” object access easy
2. Doesn’t require any Apex code
3. Supports minimal server-side application logic
4. Doesn’t provide automatic relationship traversals; you must look up related objects yourself

JavaScript Remoting:

1. Requires both JavaScript and Apex code
2. Supports complex server-side application logic
3. Handles complex object relationships better
4. Uses network connections (even) more efficiently

What is difference between JavaScript Remoting and 

The <apex:actionFunction> component also lets you call controller action methods through JavaScript.
In general, <apex:actionFunction> is easier to use and requires less code, while JavaScript remoting offers more flexibility.

Here are some specific differences between the two.
The <apex:actionFunction> tag:

 1. lets you specify rerender targets
 2. submits the form
 3. doesn’t require you to write any JavaScript
JavaScript remoting:

1. lets you pass parameters
2. provides a callback
3. requires you to write some JavaScript

Tuesday, April 11, 2017

Salesforce record Id 15 digit 18 digit conversion

Salesforce record Id uniquely identifies each record in salesforcce. Salesforce record Id can either be 15 digit or 18 digit. 15 digit salesforce record  id is case sensitive and 18 digit salesforce record id is case insensitive. Every record in salesforce is identified by unique record Id in every salesforce organization.
15 digit case-sensitive version is referenced in the UI and also visible in browser
18 digit case-insensitive version which is referenced through the API
The last 3 digits of the 18 digit Id is a checksum of the capitalization of the first 15 characters, this Id length was created as a workaround to legacy system which were not compatible with case-sensitive Ids. The API will accept the 15 digit Id as input but will always return the 18 digit Id.

Visualforce Code:

<apex:page controller="idConvertor">
    <apex:form >
        <apex:pageBlock >
        <apex:pageMessages id="showmsg"></apex:pageMessages>
            <apex:pageBlockButtons >
                <apex:commandButton value="Convert" action="{!convert}"/>
            </apex:pageBlockButtons>
            <apex:pageBlockSection >
            <apex:inputText value="{!inputId}" label="Input Id:"/>
            <apex:outPutText value="{!outputId}" label="Output Id:"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex Code:
public with sharing class idConvertor {
    public String inputId{get;set;}
    public String outputId{get;set;}
public PageReference convert(){
       outputId = convertId(inputId);
        return null;
    }

    String convertId(String inputId){
        string suffix = '';
        integer flags;
        try{
            for (integer i = 0; i < 3; i++) {
                flags = 0;
                for (integer j = 0; j < 5; j++) {
                    string c = inputId.substring(i * 5 + j,i * 5 + j + 1);
                    if (c.toUpperCase().equals(c) && c >= 'A' && c <= 'Z') {
                        flags = flags + (1 << j);
                    }
                }
                if (flags <= 25) {
                    suffix += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(flags,flags+1);
                }else{
                    suffix += '012345'.substring(flags - 26, flags-25);
                }
            }
        }
        catch(Exception exc){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Valid 15 digit Id'));
        }
        String outputId = inputId+suffix;
        return outputId;
    }
}