Tag Archives: Apex

Difference between rendered, renderAs and reRender in Visualforce Page

Rendered : It’s a Boolean value and the default value is always true, It works like “display” property of CSS. It is used to place condition for a component(field, outputpanel, section etc), that will show or not on page. (If it is true, it displays the block else it will be hidden).

For Example:
Visualforce Page:
In the controller we need to have get method to assign the value for this variable.

<apex:inputField value="{obj.Filed__c}" Rendered="{!val == true}"/>

Controller:

public boolean val {get;set;}

method(){
val = true;
}

Rerender: After Ajax which component should be refreshed. For this we need to assign id to field, sections or a block. It’s available on commandlink, commandbutton, actionSupport etc.

For Example:
Visualforce Page:

<apex:actionRegion>
    <apex:inputField value="{!TestValue}" >   
        <apex:actionSupport event="onchange" rerender="Id1,Id2,Id3,Id4" action="{!TestMethod}" >
            <apex:param name="Para" value="{!rowNum}" assignTo="{!IndexValue}" />
        </apex:actionSupport>
    </apex:inputField>   
</apex:actionRegion>

Here in actionSupport rerender attribute Id1,Id2,Id3,Id4 are the id’s of field and sections.

RenderAs: It is used for visualforce page show as pdf, excel or any other standard document format.

For Example:
Visualforce Page:

<apex:page controller="TestController" rederAs="pdf">

Custom Settings in Salesforce

Salesforce.com introduced Custom Settings in Winter ’10 which allows you to store custom data sets and associate them on an org-wide, profile or user basis. Custom settings data is exposed in the application cache and do not count against SOQL limits when fetched. This data can then be used by formula fields, validation rules, Apex, and the SOAP API.

Custom Settings support only Checkbox, Currency, Date, Date/Time, Email, Number, Percent, Phone, Text, Text Area, and URL field types. You can’t create Formula and Picklist, as well as field types that define relationships to other objects, like Lookup and Master/Detail. You can’t create lookups from Custom Objects to Custom Settings either. No Page layouts, record types, validation rules, triggers and workflow rules can be used on Custom Settings.

There are two types of custom settings:

List Custom Settings: It provides a reusable set of static data that can be accessed across your organization. If you use a particular set of data frequently within your application, putting that data in a list custom setting streamlines access to it. Data in list settings does not vary with profile or user, but is available organization-wide.

Hierarchy Custom Settings: Hierarchical Custom Settings are defined once and can hold a unique set of values for the Organization, each Profile or each individual User. Salesforce automatically grabs the lowest level of setting for the running user when a getInstance() call is made, or when accessed in a configuration such as a Validation Rule, Workflow or Formula Field. Only Hierarchical settings can be accessed declaratively whereas List settings are for Apex/Visualforce only.

Limitation of Custom Setting:

  • Maximum total data of 10 MB, but if you have less than 10 license users, multiply 1 MB with number of users.
  • 300 fields per custom setting..
  • Can’t share a custom setting record.
  • No owner assigned for each custom setting record.
  • Each custom setting counts against the total number of custom objects available for your organization.

Note: If you include custom settings in your distributed package you’ll need to build in some scripts which populate the settings with data after the package has been installed.

Difference between __c and __r in Salesforce

__c is for Custom objects For example: Custom_Object__c . It is used for reference custom object in Apex or visualforce page, formula field etc internally. Used as suffix.

__r is for Custom objects reference For example: Custom_Object__r . It is used for reference custom object relationship name in Apex or visualforce page, formula field etc. Used as suffix.

Difference between action function and action support

Action Function: Invoke the controller method from java script using AJAX and we can use action function from different places on visual force page.

Action Support: Invoke the controller method using AJAX when event occurs on page like onMouseOver, onClick, etc. and we can use action support for particular single apex component.

Salesforce Two-Factor Authentication Using Login Flow

For higher security standards one of the best practices to implement is two-factor authentication. This is the method of adding a second factor to the username and password, where the password is the first factor. The second factor is usually done with a random and time-based one-time password (TOTP), generated on an approved mobile device or an approved email address.

When a user logs in, Salesforce considers the user’s geographic location and browser. If they’re not recognized, Salesforce prompts the user to verify their identity using the highest-priority verification method available for that user.
The following is the order of priority for verification methods.

  • Verification code generated by a mobile authenticator app connected to the user’s account.
  • Verification code sent via SMS to the user’s verified mobile device.
  • Verification code sent via email to the user’s email address.

The user enters the code as a secondary verification of their identity. After verification, the user doesn’t need to provide this information again, unless they log in from a browser or location that isn’t verified by Salesforce.

But sometimes we require a second level of authentication on every login for stronger identity verification. We can enable Two-factor authentications for users by adding “Two-Factor Authentication for User Interface Logins” permission through a Profile or a Permission Sets.

The following are the verification methods:

  • Verification code generated by a mobile authenticator app connected to the user’s account.
  • Verification code sent via SMS to the user’s verified mobile device.
  • Verification code sent via email to the user’s email address.

Here is an example of two-factor authentication using login flow, which will send an one-time password (OTP) via email to the user’s email address.

  1. Create an Apex class “OTPGenerator”:
    This class provides a random 6 digit “one-time password”(OTP).

    global class OTPGenerator implements Process.Plugin
    {    
        global Process.PluginResult invoke(Process.PluginRequest request)
        {   
            Map<String, Object> result = new Map<String, Object>();  
            
            String rand = string.valueof(Math.abs(Crypto.getRandomInteger()));
            String otp = rand.substring(0,6);
            result.put('OTP', otp);
            
            return new Process.PluginResult(result);
        }
    
        global Process.PluginDescribeResult describe()
        {
            Process.PluginDescribeResult result = new Process.PluginDescribeResult();
            result.description = 'This plug-in generates a radnom 6-digits code';
            result.tag = 'Identity';
            
            result.inputParameters = new List<Process.PluginDescribeResult.InputParameter> {};
            
            result.outputParameters = new List<Process.PluginDescribeResult.OutputParameter> {
                new Process.PluginDescribeResult.OutputParameter('OTP',
                    Process.PluginDescribeResult.ParameterType.STRING)
            };
               
            return result;
        }
    }
    
  2. Click on Setup | App Setup | Create | Workflows & Approvals | Flows
  3. Click on New Flow, it will open flow canvas.
  4. Create “LoggedInUserId” Formula – Drag and drop Formula from Resources – Give the Unique name “LoggedInUserId” – And put the value “$User.Id” as shown in the below screenshot.
    1
  5. Create “OTP” Variable – Drag-and-drop Variable from Resources – Give the Unique name “OTP” as shown in the below screenshot.
    2
  6. Create “UserEmailAddress” Variable – Drag and drop Variable from Resources – Give the Unique name “UserEmailAddress” as shown in the below screenshot.
    18
  7. Create “UserFirstName” Variable – Drag and drop Variable from Resources – Give the Unique name “UserFirstName” as shown in the below screenshot.
    17
  8. Create “UserName” Variable – Drag and drop Variable from Resources – Give the Unique name “UserName” as shown in the below screenshot.
    16
  9. Create “TwoFactorAuthenticationLoginOTP” Text Template – Drag and drop Text Template from Resources – Give the Unique name “TwoFactorAuthenticationLoginOTP” – And put the “{!OTP}” variable any where in value for OTP as shown in the below screenshot.
    4
  10. Drag-and-drop “Record Lookup” from Palette(Data) – Give the Name “Get User Info”.
    • In Look Up – Select Standard Object “User”
    • Enter criteria Id = {!LoggedInUserId}
    • Assign Logged in User field value to variables.
      • Email to {!UserEmailAddress}
      • FirstName to {!UserFirstName}
      • Username to {!UserName}

    3

  11. Get random 6 digit “one-time password”(OTP) – Drag-and-drop “OTPGenerator” from Palette(Identity) – Give the name “Generate Random OTP”
    • Map the Source – Target as OTP – {!OTP} in outputs as shown in the below screenshot.

    5

  12. Send the OTP to the User – Drag-and-drop “Send Email” from Palette(Static Action) – Give the name “Send Email”
    • For Body add the Text Template “TwoFactorAuthenticationLoginOTP”.
    • Enter Subject “Login One Time Password”.
    • For Email Address (Comma-separated) Select {!UserEmailAddress} variable, as shown in the following screenshot.

    6

  13. Now allowing user to enter OTP – Drag and drop “Screen” element from Palette(User Interface) – Give the name “Get OTP”
    • Add a Textbox to enter OTP – Give Unique name “OTPInput” as shown in the below screenshot.

    7

  14. To verify OTP(Generated by “OTPGenerator” Class) – Drag and drop “Decision” element from Palette(Logic) – Give the name “OTP Validation”. On the window to check whether variable {!OTP} is equal to Screen Input element {!OTPInput}. If both the values is not same, then it means don’t allow user to login into Salesforce.
    8
  15. For invalid OTP add a screen to show error message –  Drag and drop “Screen” element from Palette(User Interface) – Give the name “Invalid OTP”
    • Add a “Display Message” – Give the name “InvalidTitle” – With the value “Invalid OTP!” as shown in the below screenshot.

    9

  16. Set “Record Lookup” (Get User Info) element as Start element as shown in below screenshot.
    21
  17. Finally the Flow will look like the following screenshot.
    20
  18. Save the flow with name “Two Factor Authentication Using Email” then Activate it and close the canvas.
  19. Now To create a Login Flow follow the below instructions:
    • Click on Name | SetupAdministration Setup | Security Controls | Login Flows
    • Click on the New button.
    • Enter the Login Flow Name, Select the flow, User license and Profile, It will look like the below screenshot.

    19

Now its time to test the “Two Factor Authentication”. To test it follow the below instructions:

  • Login into Salesforce through User who have same profile that you have used in Login Flow, In my case it’s “Custom Standard User”. After Successful login you will receive an email, it will look like the below screenshot.
    10
  • Enter OTP(One-time Password) onto the screen input field (i.e. OTP) and click on the Next Button, as shown in the below screenshot.
    11
  • If Security Code is matched then you will redirect to Salesforce Home Page else it will display an error message as shown in the below screenshot.
    12

Note : I will suggest to implement and test it in your Developer or Sandbox org, and then move it to Production.