Invocable method in Salesforce

While the Process builder is very flexible out of the box, there are a few business use cases those are not achievable using it. For example

1. It doesn’t support outbound messages
2. It doesn't support creation of multiple records
3. It doesn’t allow us to delete a record

When no other process action can get the job done, add customized functionality to your Salesforce processes by calling an Apex method. To call an Apex method, add the Call Apex action to your process and select an Apex class with an @invocable method Annotation. It means they allow us to extend the Process Builder by writing Apex code that meets certain criteria, and then invoking the Apex from our Processes. If the class contains one or more invocable variables, manually enter values or reference field values from a related record. @InvocableMethod Annotation support bulk operations.

Check the below link for more information

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_annotation_InvocableMethod.htm

Cheers!!!

convertCurrency() in Salesforce

Use convertCurrency() in a SOSL query to convert currency fields to the user’s currency. This action requires that the organization is multi-currency enabled.

Syntax:

convertCurrency(Amount)

For example,

FIND {test} RETURNING Opportunity(Name, convertCurrency(Amount))

Use convertCurrency() in the SELECT statement of a SOQL query to convert currency fields to the user’s currency. This action requires that the org has multiple currencies enabled.

Syntax:

convertCurrency(field)

For example:

SELECT Id, convertCurrency(AnnualRevenue) FROM Account

Cheers!!!

Font Family CSS not working when Visualforce page rendered as pdf

If you face Font Family CSS not working when Visualforce page rendered as pdf, check the below link. When Visualforce page is rendered as pdf, it does not support all the font families.

To know the Fonts Available When Using Visualforce PDF Rendering, check the belo link

https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_supported_fonts.htm

Cheers!!!

How to add a new component in MavensMate for Salesforce?

1. Go to MavensMate --> Metadata --> New Apex Trigger..(for example).


2. Select Template.


3. Enter Trigger Name followed by comma and Object API Name.


Cheers!!!

How long it takes to refresh a developer sandbox in Salesforce?

The process can finish within a few hours but can take up to several days depending on your Sandbox's level of customization, data size, number of objects, your configuration choices, and server load.

For more information, check the below link

https://help.salesforce.com/apex/HTViewSolution?id=000204612&language=en_US

Cheers!!!

Salesforce Interview Questions with Answers Part 36

1. In a Master-Detail relationship how can we prevent duplicate child records under the same master?

Develop a trigger on child object with before insert event. Use Map data type iterating over the trigger.new list. In the next iteration find whether for the same master, duplicate is found.

2. Consider a scenario where we need to update 100,000 records daily. How can we do it?

Batch Apex with Scheduler class to schedule daily.

3. How can we avoid hard coding values in Salesforce?

Custom Label, Custom Settings, Custom Metadatatype.

4. Can we expose/provide access to a VisualForce page to users who do not have a salesforce login/who are not salesforce users? If so, how can we do it?

Force.com Site.

5. How can we load large amount of options on a Picklist field?

With Winter '16 you can add up to 500 values to a custom multi-select picklist, more than three times as many as before. This feature is available in both Lightning Experience and Salesforce Classic.

6. Suppose if we want to provide some of the System Admin access to a group of users, how can we do it?


Cheers!!!

Is there a way to auto-populate lookup fields when creating a new record on a custom object?

1. Go to Customize --> Search --> Search Settings.


2. In the Search Settings area, select the object lookups for which you want to enable auto-completion. Currently, only account, contact, opportunity, user, and custom object lookups can use this feature.

3. Click Save.

Cheers!!!

Link from Salesforce community not redirecting user to login

1. Go to Custom URLs.


2. Find the correct site detail for the community.

3. Map Authorization Required Page Salesforce (401) to CommunitiesLogin instead of UnderConstruction page.


Cheers!!!

How to get Salesforce base url in Visualforce Email template?

Use the below method in the controller to get Salesforce base url in Visualforce Email template.

        public String getfullURL() {
        return URL.getSalesforceBaseUrl().toExternalForm();
}

fullURL variable can be used in the Visualforce Email Template.

Cheers!!!

How to get base url in Visualforce?

{!$Site.BaseUrl} is used to get base url in Visualforce.

Sample Code;

Visualforce Page:

<apex:page controller="Sample" sidebar="false">
    <apex:repeat value="{!listAcct}" var="a">
        <a href="{!$Site.BaseUrl}/{!a.Id}" target="_blank">{!a.Name}</a><br/>
    </apex:repeat>

</apex:page>

Apex Controller:

public class Sample {
    
    public List < Account > listAcct {get;set;}
    
    public Sample() {
        listAcct = [ SELECT Id, Name FROM Account ];
    }
    

}

Output:


Cheers!!!

Your connection is not private Attackers might be trying to steal your information Salesforce

Try to login from different browsers if you face the below issue.


Cheers!!!

CSS not working Span tag in HTML

The difference is not between <span> and <div> specifically, but between inline and block elements. <span> defaults to being display:inline; whereas <div> defaults to being display:block;. But these can be overridden in CSS.

To fix it, use the below code

Sample Code:
<span style="display: block;">

Cheers!!!

Unable to delete SAML Single Sign-On Settings in Salesforce

If you are unable to delete SAML Single Sign-On Settings in Salesforce, check the below before deleting it.

1. Go to Domain Management --> My Domain. Check whether the SAML Settings is disabled in "Authentication Configuration" section. If not, please disable it.

2. Please check the Portal Login and Registration Settings and Community Login and Registration Settings and do the same.

Cheers!!!

Your organization or community is currently using this Single Sign-On Setting as an authentication method, so you can’t delete it

If you face "Your organization or community is currently using this Single Sign-On Setting as an authentication method, so you can’t delete it", check the below

1. Go to Domain Management --> My Domain. Check whether the SAML Settings is disabled in "Authentication Configuration" section. If not, please disable it.

2. Please check the Portal Login and Registration Settings and Community Login and Registration Settings and do the same.

Cheers!!!

The 'MaintenanceRequest' trigger does not appear to be handling bulk operations correctly

If you face this issue "The 'MaintenanceRequest' trigger does not appear to be handling bulk operations correctly", make sure while creating new case, the existing case's subject is copied.

newCase.Subject = cas.Subject;

Cheers!!!

Could not find a match for URL

Organization with Namespace:

/services/apexrest/InfallibleTech/Accounts/001U000001ZwOUN

InfallibleTech is the namespace prefix.

Organization without Namespace:

/services/apexrest/Accounts/001U000001ZwOUN

Cheers!!!

Simple HTTP Class in Salesforce

Sample Code:

@RestResource(urlMapping='/Accounts/*')
global with sharing class AccountManager {
    @HttpGet
    global static Account getAccount() {
        RestRequest request = RestContext.request;
        String acctId = request.requestURI.removeEnd('/contacts').substring(request.requestURI.removeEnd('/contacts').lastIndexOf('/')+1);
        Account result =  [ SELECT Id, Name, ( SELECT Id, Name FROM Contacts ) FROM Account WHERE Id =: acctId ];
        return result;
    }
}

To test it, do the following

1. Log in into https://workbench.developerforce.com.

2. Select REST Explorer.


3. Enter /services/apexrest/InfallibleTech/Accounts/001U000001ZwOUN/contacts and click "Execute".


Cheers!!!

Your organization or community is currently using SAML as an authentication method, so you can’t disable it.

Your organization or community is currently using SAML as an authentication method, so you can’t disable it is a know issue.

Check the below link, whether it is fixed in your organization

https://success.salesforce.com/issues_view?id=a1p30000000sY1bAAE

Cheers!!!

Formula Expression is required on the action attributes

If you face "Formula Expression is required on the action attributes", check the below

1. action="{!methodname}" is mentioned properly.

2. Check the URL in PageReference declaration. Use forward slash "/" if by mistake "\" back slash is used.

Cheers!!!

Test class for SOAP Callout in Salesforce

Class generated from WSDL:
//Generated by wsdl2apex

public class ParkService {
    public class byCountryResponse {
        public String[] return_x;
        private String[] return_x_type_info = new String[]{'return','http://parks.services/',null,'0','-1','false'};
        private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};
        private String[] field_order_type_info = new String[]{'return_x'};
    }
    public class byCountry {
        public String arg0;
        private String[] arg0_type_info = new String[]{'arg0','http://parks.services/',null,'0','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://parks.services/','false','false'};
        private String[] field_order_type_info = new String[]{'arg0'};
    }
    public class ParksImplPort {
        public String endpoint_x = 'https://th-apex-soap-service.herokuapp.com/service/parks';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'http://parks.services/', 'ParkService'};
        public String[] byCountry(String arg0) {
            ParkService.byCountry request_x = new ParkService.byCountry();
            request_x.arg0 = arg0;
            ParkService.byCountryResponse response_x;
            Map<String, ParkService.byCountryResponse> response_map_x = new Map<String, ParkService.byCountryResponse>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://parks.services/',
              'byCountry',
              'http://parks.services/',
              'byCountryResponse',
              'ParkService.byCountryResponse'}
            );
            response_x = response_map_x.get('response_x');
            return response_x.return_x;
        }
    }
}

Class making use of WSDL generated Class:
public class ParkLocator {
    public static List < String > country(String Country) {
        ParkService.ParksImplPort obj = 
            new ParkService.ParksImplPort();
        return obj.byCountry(Country);
    }
}

Mock for test class:
@isTest
global class ParkServiceMock implements WebServiceMock {
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
        ParkService.byCountryResponse response_x = 
            new ParkService.byCountryResponse();
        response_x.return_x = new List < String > {'a', 'b'};
        response.put('response_x', response_x); 
   }
}

Test Class:
@isTest
private class ParkLocatorTest {
    @isTest static void testCallout() {              
        Test.setMock(WebServiceMock.class, new ParkServiceMock());
        List < String > result = ParkLocator.country('Test');
    }
}

Cheers!!!

How to write test class for HTTPCallouts in Salesforce?

Sample HTTPCallout Class:
public class AnimalLocator {
    public static String getAnimalNameById(Integer id) {
        Http http = new Http();
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');
        HttpResponse response = http.send(request);
        String strResp = '';
        if (response.getStatusCode() == 200) {
           Map < String, Object > results = (Map < String, Object >) JSON.deserializeUntyped(response.getBody());
           Map < string, Object > animals = (Map < String, Object >) results.get('animal');
           strResp = string.valueof(animals.get('name'));
        }
        return strResp ;
    }  
}

Sample HTTP Mock Callout Class:
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest request) {
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal": {"id":2, "name":"Test"}}');
        response.setStatusCode(200);
        return response; 
    }
}

Test Class:
@isTest 
private class AnimalLocatorTest {
    static testMethod void testPostCallout() {
        Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());  
        String strResp = AnimalLocator.getAnimalNameById(2);
    }
}

Cheers!!!

What are all the mock HTTPCallOuts available in Salesforce?

The mock HTTPCallOuts available in Salesforce are below

1. StaticResourceCalloutMock
2. HttpCalloutMock

Cheers!!!

PDF generation failed. Check the page markup is valid

If you face "PDF generation failed. Check the page markup is valid" issue while rendering a Visulaforce page as PDF, do the following

1. Remove RenderAs attribute from apex:page and check whether any error pops out. Sometimes, error will not be shown on the PDF page.

2. Remove sections of codes and find the exact code where the issues is.

Cheers!!!

How to set scroll bar in Inline VF in page layout in Salesforce?

1. Go to the VF properties in page layout.


2. Select Show scrollbars check box.


Cheers!!!

How to find current API version of Salesforce organization?

1. Go to Develop --> API.

2. Click "Generate Partner WSDL".


3. First line will show the version.


Cheers!!!

Unable to refresh the file metadata Force.com IDE

If you face "Unable to refresh the file metadata" while installing Force.com IDE, the main reason for this is difference between Force.com IDE version and your organization API version.

To check the Force.com IDE API Version in Eclipse, check the below steps.

1. Go to Installation Details.


2. Check for Force.com IDE.


To fix it, uninstall the Force.com IDE and install it again with the correct API Version.


Cheers!!!

Force.com IDE for 37.0 Version

Force.com IDE for 37.0 Version is https://developer.salesforce.com/media/force-ide/beta_eclipse45.

Check the below link for more information

https://github.com/forcedotcom/idecore/wiki/Downloading-the-Beta-Version-of-the-Force.com-IDE

Cheers!!!

Background CSS not working print preview in Salesforce

Add the below CSS in the Visualforce page to fix it.

<style >
           
           @media print {
body {-webkit-print-color-adjust: exact;}
}

</style>

Cheers!!!

Dynamic SOQL

Dynamic SOSL refers to the creation of a SOSL string at run time with Apex code. Dynamic SOSL enables you to create more flexible applications.

Sample SOSL:

String strName = 'Test';
String searchquery = 'FIND \'' + strName + '*\' IN ALL FIELDS RETURNING Account(Id,Name), Contact, Lead'; 
List < List < SObject > > searchList=search.query(searchquery);
system.debug('Search List is ' + searchList);

Cheers!!!

How to deploy Compact Layout in Salesforce using ANT tool?

Sample Package.xml:

<?xml version="1.0" encoding="UTF-8"?>
<Package xmlns="http://soap.sforce.com/2006/04/metadata">
    <types>
<members>Task.Compact_Layout_Name</members>
        <name>CompactLayout</name>
    </types>
    <types>
<members>Task.RecordTypeName</members>
        <name>RecordType</name>
    </types>
    <types>
<members>ProfileName</members>
        <name>Profile</name>
    </types>
    <version>36.0</version>
</Package>

Cheers!!!

Missing New button in Authentication Settings for External Systems

Go to the user record and select new in Authentication Settings for External Systems section.


Cheers!!!

Flex Queue

The Apex Flex queue enables you to submit up to 100 batch jobs for execution. Any jobs that are submitted for execution are in holding status and are placed in the Apex Flex queue. Up to 100 batch jobs can be in the holding status.

Jobs are processed first-in first-out—in the order in which they’re submitted. You can look at the current queue order and shuffle the queue, so that you could move an important job to the front, or less important ones to the back.

When system resources become available, the system picks up the next job from the top of the Apex Flex queue and moves it to the batch job queue. The system can process up to five queued or active jobs simultaneously for each organization. The status of these moved jobs changes from Holding to Queued. Queued jobs get executed when the system is ready to process new jobs. Like other jobs, you can monitor queued jobs in the Apex Jobs page.


Cheers!!!

Queueable Apex

Queueable Apex is similar to future methods, but provide additional job chaining and allow more complex data types to be used.

Queueable Apex allows you to submit jobs for asynchronous processing similar to future methods with the following additional benefits:
  1. Non-primitive types: Your Queueable class can contain member variables of non-primitive data types, such as sObjects or custom Apex types. Those objects can be accessed when the job executes.
  2. Monitoring: When you submit your job by invoking the System.enqueueJob method, the method returns the ID of the AsyncApexJob record. You can use this ID to identify your job and monitor its progress, either through the Salesforce user interface in the Apex Jobs page, or programmatically by querying your record from AsyncApexJob.
  3. Chaining jobs: You can chain one job to another job by starting a second job from a running job. Chaining jobs is useful if you need to do some sequential processing.
Things to Remember

Queueable Apex is a great new tool but there are a few things to watch out for:

  1. The execution of a queued job counts once against the shared limit for asynchronous Apex method executions.
  2. You can add up to 50 jobs to the queue with System.enqueueJob in a single transaction.
  3. When chaining jobs, you can add only one job from an executing job with System.enqueueJob, which means that only one child job can exist for each parent queueable job. Starting multiple child jobs from the same queueable job is a no-no.
  4. No limit is enforced on the depth of chained jobs, which means that you can chain one job to another job and repeat this process with each new child job to link it to a new child job. However, for Developer Edition and Trial orgs, the maximum stack depth for chained jobs is 5, which means that you can chain jobs four times and the maximum number of jobs in the chain is 5, including the initial parent queueable job.

Sample Code:

Queueable Apex:
public class AddPrimaryContact implements Queueable {
    Contact con;
    String strState;
    public AddPrimaryContact(Contact con, String strState) {
        this.con = con;
        this.strState = strState;
    }
    
    public void execute(QueueableContext qc) {
        List < Account > listAccount = [ SELECT Id FROM Account WHERE BillingState =: strState LIMIT 200 ];
        List < Contact > listContact = new List < Contact >();
        for ( Account acc : listAccount ) {
            Contact c = con.clone();
            c.AccountId = acc.Id;
            listContact.add(c);
        }
        insert listContact;
    }

}

Cheers!!!

Why objects can’t be passed as arguments to future methods in Salesforce

The reason why objects can’t be passed as arguments to future methods is because the object can change between the time you call the method and the time that it actually executes. Remember, future methods are executed when system resources become available. In this case, the future method may have an old object value when it actually executes, which can cause all sorts of bad things to happen.

Cheers!!!

OAuth token expired Salesforce

If you face "OAuth token expired" in Salesforce, go to the External Data Source, edit it and just save it.

Even after following the above step, still if you face Token Expiration, check with the third party OAuth app.

Cheers!!!

How to view files from Google Drive in Salesforce?

1. Enable Files Connect - http://www.infallibletechie.com/2016/08/how-to-enable-salesforce-files-connect.html

2. Create a Permission Set with User License None.



3. Go to System Permissions and select "Files Connect Cloud".


4. Assign the Permission Set to the user.


5. Go to Security Controls --> Remote Site Settings.


7. Add the below remote site settings.



8. Create Authentication Provider - http://www.infallibletechie.com/2016/08/how-to-create-authentication-provider.html

9. Define External Data Source - http://www.infallibletechie.com/2016/08/how-to-define-external-data-source-for.html

10. Go to Files tab to check.


Cheers!!!

How to enable Drive API in Google?

1. Click "Go to APIs Overview".


2. Click "Enable API".


3. Click "Drive API".


4. Click "Enable".


Cheers!!!

How to Define an External Data Source for Google Drive in Salesforce?

1. Go to External Data Sources.


2. Click "New".


3. Enter the details as below and Save.


4. Use the below link if the Identity Type is Per User, else skip this step.

http://www.infallibletechie.com/2016/11/steps-to-be-followed-for-per-user.html

Cheers!!!

How to create an Authentication Provider for Google Drive in Salesforce?

1. Log in to https://console.cloud.google.com.

2. Click Create Project. Enter the project name and click "Create".



3. Click "Enable and Manage APIs".


4. Click "Credentials".


5. Click "Create Credentials".


6. Select "OAuth Client Id".


7. Click "Configure Consent Screen".


8. Enter the details and click "Save".


9. Select Web Application, enter Name and click "Create".


10. Go to Security Controls --> Auth. Providers.


11. Click "New".


12. Enter the details as below

Name - Enter the name you want to appear in Salesforce.

URL Suffix - Enter the suffix at the end of the URL path. For example, in the path, https://login.salesforce.com/services/authcallback/00Dx00000000001/MyGoogleProvider, the suffix is “MyGoogleProvider”

Consumer Key - Enter the client ID you copied when creating the Google project.

Consumer Secret - Enter the client secret you copied when creating the Google project.

Authorize Endpoint URL - Enter https://accounts.google.com/o/oauth2/auth?access_type=offline&approval_prompt=force

Token Endpoint URL -  Enter https://accounts.google.com/o/oauth2/token

Default Scopes - Enter openid email profile https://www.googleapis.com/auth/drive


13. Copy the Call Back URL.


14. Enter Call Back URL in Google project and Save.


Cheers!!!

How to enable Salesforce Files Connect for Your Organization?

1. Go to Salesforce Files --> Settings --> Files Connect.


2. Edit Files Connect Settings.


3. Enable "Enable Files Connect".


Cheers!!!