How to upload multi picklist values through data loader?

For inserting or updating multi select pick list fields through the Apex Data Loader, multiple values for the mulit picklist field are separated by a semi-colon ";".

For example, for a multi select field "Associate Users", containing the values Prakash and Admin,  the .csv spreadsheet column for inserting or updating the data would be entered as "Prakash;Admin".


Cheers!!!

Age calculation using Apex and Visualforce

Sample code:

Visualforce page:

<apex:page controller="Sample" >
<apex:form >
    <apex:pageblock >
        <apex:pageblockSection >
            <apex:pageblockSectionItem >Date:</apex:pageblockSectionItem>
            <apex:pageblockSectionItem ><apex:inputtext onfocus="DatePicker.pickDate(true, this , false);" value="{!dat}" id="dt"/></apex:pageblockSectionItem>
            <apex:pageblockSectionItem >Age:</apex:pageblockSectionItem>                       
            <apex:pageblockSectionItem ><apex:outputText value="{!age}" /></apex:pageblockSectionItem>           
        </apex:pageblockSection>
        <apex:pageblockButtons >
            <apex:commandButton value="Find" action="{!find}"/>
        </apex:pageblockButtons>
    </apex:pageblock>
</apex:form>   
</apex:page>


Apex Controller:

public class Sample
{  
    public Integer age {get;set;}    
    public Date dat {get;set;}
   
    public void find()
    {
        Integer temp = dat.daysBetween(Date.Today());
        age = Integer.valueOf(temp/365);
    }
}


Output:

How to import other language data using Apex Data loader?

Kindly follow the below steps to import other language data using Apex Data loader

1. Open the .xls file that displays the other language characters correctly and which was prepared for import.

2. Click File --> Save As.  In “Save as type”, kindly select Unicode Text (*.txt).

3. Click "Save" button.

4. Open the .txt file in Notepad.

5. In Notepad, click File --> Save As.
      i. In“File name”, change the file’s extension from .txt to .csv.
      ii. In “Save as type”, select "All Files".
      iii. In “Encoding”, select "UTF-8".
      iv. Click "Save" button.

6. Import the .csv file

To check the formatting of the .csv file before importing, you can open it using Excel (do not open by clicking  on the .csv file). To open using Excel, start Excel and click File --> Open and browse the .csv file.

Cheers!!!

How to use multiple substitute function in Salesforce?

We have to use nested SUBSTITUTE() methods for multiple replacing of characters.

Example:

SUBSTITUTE(SUBSTITUTE(Name," ", ""),"-","" )

In this example, we can remove "-" and space.

Validation rules for Country codes(USA, Mexico, Argentina, Canada, Australia) in Salesforce

Example:

OR(
AND(
ISPICKVAL( Country_Code__c , "USA"),NOT( REGEX( Pincode__c , "\\d{5}(-\\d{4})?") )
),
AND(
ISPICKVAL( Country_Code__c , "MEX"), NOT(REGEX( Pincode__c , "\\d{5}")), NOT(REGEX( Pincode__c , "\\d{6}"))
),
AND(
ISPICKVAL( Country_Code__c , "AUS"), NOT(REGEX( Pincode__c , "\\d{4}"))
),
AND(
ISPICKVAL( Country_Code__c , "CAN"), NOT(REGEX( Pincode__c , "[a-zA-Z]{1}[0-9]{1}[a-zA-Z]{1}\\s[0-9]{1}[a-zA-Z]{1}[0-9]{1}"))
),
AND(
ISPICKVAL( Country_Code__c , "ARG"), NOT(REGEX( Pincode__c , "[a-zA-Z]{1}\\d{4}[a-zA-Z]{3}")),NOT(REGEX( Pincode__c , "\\d{4}"))
)
)

What is Database.setSavepoint in Salesforce?

Database.setSavepoint() is used to define a point at which DML operations can be rolled back. If any error occurs during DML Operations, that contains many statements, the application will be rolled back to the most recent save point and the entire transaction will not be aborted.

Sample:

Savepoint sp = Database.setSavepoint();;

Account a = new Account();
a.Name='1';

a.AccountNumber = '2';
insert a;

Contact c = new Contact(Account = a.Id);
try
{
    
insert c;
}
catch(Exception e)
{
    Database.RollBack(sp);
}


In this example, if any error occurs while inserting the Contact 'c', then the entire transaction will be rolled back to savepoint sp ( as specified in the catch section by Database.rollback method).

Note the following:
  • If you set more than one savepoint, then roll back to a savepoint that is not the last savepoint you generated, the later savepoint variables become invalid. For example, if you generated savepoint SP1 first, savepoint SP2 after that, and then you rolled back to SP1, the variable SP2 would no longer be valid. You will receive a runtime error if you try to use it.
  • References to savepoints cannot cross trigger invocations, because each trigger invocation is a new execution context. If you declare a savepoint as a static variable then try to use it across trigger contexts you will receive a runtime error.
  • Each savepoint you set counts against the governor limit for DML statements.
Cheers!!!

apex:outputLink in Salesforce

Sample code:

Visualforce page:

<apex:page controller="Sample" >
<apex:form >
    <apex:pageBlock >
        <apex:pageblockTable value="{!usrs}" var="u">
            <apex:column >
                <apex:outputLink target="_blank" value="/{!u.id}">{!u.Name}</apex:outputLink>
            </apex:column>
        </apex:pageblockTable>
    </apex:pageblock>   
</apex:form>   
</apex:page>


Apex Controller:

public class Sample
{
    public String obj;
    public List<User> usrs{get;set;}
   
    public Sample()
    {   
        usrs = [SELECT ID, Name FROM User];
    }      
}


Output:



Important attributes:


Attributes
Use
value
The URL used for the output link.

target
The name of the frame where the resource retrieved by this command link is displayed. Possible values for this attribute include "_blank", "_parent", "_self", and "_top". You can also specify your own target names by assigning a value to the name attribute of a desired destination.
disabled
A Boolean value that specifies whether this link is displayed in a disabled state. If set to true, the field appears disabled because an HTML span tag is used in place of the normal anchor tag. If not specified, this value defaults to false.

rendered
A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to

How to retrieve fields based on selected object by Dynamic Apex?

Sample Code:

Visualforce page:

<apex:page controller="Sample" >
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel value="Objects"/>
            </apex:pageBlockSectionItem>       
            <apex:pageBlockSectionItem >
                <apex:selectList size="1" value="{!obj}" >
                    <apex:selectOptions value="{!objs}"/>
                </apex:selectList>
            </apex:pageBlockSectionItem>                     
        </apex:pageBlockSection>
        <apex:pageblockButtons >
            <apex:commandButton value="Fetch Fields" action="{!fetchFields}" reRender="flds"/>
        </apex:pageblockButtons>
    </apex:pageBlock>
    <apex:pageblock id="flds" title="Fields">
        <apex:pageblockTable value="{!objFields}" var="f">
            <apex:column value="{!f}" />
        </apex:pageblockTable>
    </apex:pageblock>   
</apex:form>   
</apex:page>


Apex controller:

public class Sample
{
    public String obj;
    public List<String> objFields {get;set;}
   
    public Sample()
    {   
    }
   
    public String getobj()
    {
        return obj;
    }
   
    public void setobj(String obj)
    {
        this.obj = obj;
    }  
   
    public List<SelectOption> getobjs()
    {
        List<Schema.SObjectType> gd = Schema.getGlobalDescribe().Values();   
        List<SelectOption> options = new List<SelectOption>();
              
        for(Schema.SObjectType f : gd)
        {
            options.add(new SelectOption(f.getDescribe().getName(),f.getDescribe().getName()));
        }
        return options;
    }
 
    public void fetchFields()
    {
        List<String> fields = new List<String>();
        Map<String , Schema.SObjectType> globalDescription = Schema.getGlobalDescribe();
        System.debug('Selected Object is ' + obj);
        Schema.sObjectType objType = globalDescription.get(obj);
        System.debug('Object Type is ' + objType);
        Schema.DescribeSObjectResult r1 = objType.getDescribe();
       
        Map<String , Schema.SObjectField> mapFieldList = r1.fields.getMap(); 

        for(Schema.SObjectField field : mapFieldList.values()) 
        { 
            Schema.DescribeFieldResult fieldResult = field.getDescribe(); 
           
            if(fieldResult.isAccessible()) 
            { 
                System.debug('Field Name is ' + fieldResult.getName());
                fields.add(fieldResult.getName());
            } 
        }
        List<String> so = new List<String>();
        for(String f : fields)
        {
            so.add(f);
        }
        objFields = so;      
    }  
}



Output:

How to transfer mass approval requests or remove mass approval requests?

1.    Go to Setup --> Data Management --> Mass Transfer Approval Requests.



2.    Enter the search conditions that the approval requests you are transferring or removing must match.
3.    Click “Find” button to search for approval requests that match.
4.    Optionally, enter any comments to be stored with the approval requests. The comments you enter are displayed on the Approval History related list if your administrator has customized it to include the Comments field.
Choose an option:
    •    “Mass remove records from an approval process” unlocks the records and removes them from any approval process so they no longer appear on the approver's list of pending approval requests.
    •    “Mass transfer outstanding approval requests to a new user” allows you to select a user and assign that user as the approver for all approval requests selected.
5.    Select the checkbox next to each approval request you want to transfer or remove from the approval process, depending on the option you selected previously.
6.    Click Transfer or Remove, depending on the option you selected previously.

Mass remove records from an approval process:


Mass transfer outstanding approval requests to a new user:


Cheers!!!

How to recall a approved record in Salesforce?

Apex Class:

global class approvalRecall
{
    webservice static void recallApproval(Id recId)   
    {       
        List<ProcessInstanceWorkitem> piwi = [SELECT Id, ProcessInstanceId, ProcessInstance.TargetObjectId FROM ProcessInstanceWorkitem WHERE ProcessInstance.TargetObjectId =: recId];
        Approval.ProcessWorkitemRequest req = new Approval.ProcessWorkitemRequest();
        req.setAction('Removed');       
        req.setWorkitemId(piwi.get(0).Id);
  
        Approval.process(req,false);
    }
}


Custom Button Javascript:

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}

var r = confirm("Are you sure want to recall the approval process?");
if(r == true)
{
sforce.apex.execute("approvalRecall","recallApproval",{ID:"{!Member__c.Id}"});
alert("Approval has been recalled");
window.open('/{!Member__c.Id}');
}
else
{
alert("Recall Cancelled");
}



 Output:




Difference between Lookup and Master-Detail relationship in Salesforce



Lookup
Master-Detail
Loosely coupled.     
Tightly coupled.
Parent is not a required field while creating child record.          
Parent is a required field while creating child record.
We cannot create roll-up summary field.
We can create roll-up summary field.
No cascade delete. 
Cascade delete.

Cheers!!!

Field history tracking in Salesforce

We can track only up to 20 fields per object.

We cannot track all the Standard fields, Roll-up Summary fields and Formula fields.

It won't show modified values and old values for Multi-Picklist, Long Textarea fields and Field's length more than 255 characters.

History tracking shows the following:
  1. Prior value - old value.
  2. Current value - value.
  3. Who has done the changes - person who modified it.
  4. When it was changed - date and time of modification.
For Standard Object:

1. Go to any standard object fields and click "Set History Tracking" button.


2. Enable "Enable Account History" check box, select the fields for tracking and click "Save" button.


3. Go to the page layout and add the tracking history related list.


For Custom Object:

1. Go to any custom object and click "Set History Tracking" button.


Note: If Set History Tracking button is not available for Custom object, make sure that Track Field History check box is checked.


2. Select the fields for tracking and click "Save" button.


3. Go to the page layout and add the tracking history related list.


Output:

Salesforce scenario based Interview Questions

1. When Workflow limit has over in your Salesforce organization, what are all the alternatives for workflows?
  • Triggers
  • Schedulable class
2. Is it possible to write test classes for your triggers?

Yes.

3.  If you want to write a workflow for a record in which age should be greater than 18 and it should be a new record. The workflow should not fire for old records. How will you achieve this?

It can be achieved throught IsNew() and age>18 condition in Workflow.

4. If an user is saying that he is unable to login into Salesforce, how will you troubleshoot his login issue?

Login history.

5. Where Roll-up summary field will be there and when it can be used?

Roll-up summary field is applicable only in Master-Detail relationship and it will be present in parent object.

6. Have you used Data loader? If yes, how many records have you migrated to the maximum?

7. What is the difference between Queue and Public Group?

8. If an user is not able to view Reports and Dashboards, how will you provide access to him to Reports and Dashboards?

Create and Customize Reports and Manage public Reports permissions in Profile.

Will update more scenario based questions soon!!!

Organization-Wide Permission Sets in Salesforce

Organization-wide permission sets are not associated with a specific user license. You can create a single permission set and assign it to users with different user licenses.

While creating a Permission Set, it asks for User license and it can be associated to that license users.

But Organization-wide permission sets are not associated with a specific user license. So, it can be assigned to any user with any license.

 To create this go to Setup --> Manage Users --> Permission Sets.

Geolocation field in Salesforce

The Geolocation custom field allows you to create a field that identifies a location by its latitude and longitude. You can then use the Geolocation field with the DISTANCE and GEOLOCATION formula functions to calculate distances between locations.

Limitations of Geolocation Field:
  1. Geolocation is a compound field that counts toward your organization’s limits as three custom fields: one for latitude, one for longitude, and one for internal use.
  2. History tracking is not available for geolocation fields.
  3. Geolocation fields are not supported in custom settings.
  4. Geolocation fields are not available in reports, dashboards, validation rules, Visual Workflow, or workflow and approvals.
  5. Geolocation fields cannot be searched.
  6. Geolocation fields are not available in Schema Builder.
  7. DISTANCE and GEOLOCATION formula functions are available only when creating formula fields and in Visual Workflow.
  8. Geolocation is supported in Apex only through SOQL queries, and only at the component level.

Cheers!!!

Invalid Date error in Apex

Use the below format for the date to avoid this error.


yyyy-mm-dd

Example:

String a = '2013-02-14';
Date d = Date.valueOf(s); // It won't show invalid date error.

Expiry notification through email using schedulable class in Salesforce

Sample Code:

Batch Apex Class:

global class expireNotify implements Database.Batchable<sObject> {
    global Database.QueryLocator start(Database.BatchableContext bc) {
        Date d = Date.today();
        String soql = 'SELECT Expiry_Date__c, Name, Email_Address__c FROM Member__c WHERE Expiry_Date__c =: d';
        return Database.getQueryLocator(soql);
    }
  
    global void execute(Database.BatchableContext bc, List<Member__c> recs) {
        List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
        for(Member__c m : recs) {
            List<String> toAddresses = new List<String>();          
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            toAddresses.add(m.Email_Address__c);
            mail.setToAddresses(toAddresses);
            mail.setSubject('Welcome to Sweet 16 Siebel Batch');
            String messageBody = '<html><body>Hi ' + m.Name + ',<br>Your account Expires today. <br>Kindly contact your administrator.<br><br><b>Regards,</b><br>Magulan D</body></html>';
            mail.setHtmlBody(messageBody);
            mailList.add(mail);         
        }
        Messaging.sendEmail(mailList);
    }
  
    global void finish(Database.BatchableContext bc) {
    }
}


Schedulable Class:

global class scheduleExpireNotify implements Schedulable {
    global void execute(SchedulableContext sc) {
        expireNotify en = new expireNotify();

        Database.executeBatch(en);
    }
}


Schedule the 'scheduleExpireNotify' as mentioned below in App Setup --> Apex Classes --> Schedule Apex and select 'sscheduleExpireNotify' class. Check Weekly and select all the days. Give Start and End dates and Preferred Start time and Click 'Save' button.


Unable to see Work with Portal button

If an user is not able to view the "Work with Portal" button, then go the user's profile  and check the  "Manage Partners" checkbox under "Administrative Permissions". After checking this checkbox, create an Account and see. You will be able to view "Work with Portal" button.

Customer Portal implementation in Salesforce

Step 1: Enable Customer Portal

To enable Customer Portal, follow the below steps

1. Click Your Name > Setup > Customize > Customer Portal > Settings.

2. Click Edit.

3. Select Enable Customer Portal.

4. Click Save.

5. Continue setting up the portal.


Step 2: Click "New" button.
You must have the “Customize Application” permission to set up and modify the Customer Portal.

Step 3: Enter the details and click "Save" button


Step 4:

When you enable a Customer Portal, the following profiles are automatically created if you purchased user licenses for them:

• High Volume Customer Portal
• Authenticated Website
• Customer Portal User
• Customer Portal Manager

Create a profile and then assign it to the customer portal.


 Step 5: Edit the Contact page layout and add "Allow Customer Portal Self-Registration" to it.


Step 6: Create an Account and click "Enable Partner" under "Work with Partner" button.


Step 7: Create a contact under the account and click "Enable as Customer portal User" under "Work with Portal" button.


Step 8: Fill in the details and click "Save" button.


Step 9: Check your email for username and password.


Step 10: Get the URL from the Portal Default Settings in the Customer portal.


Step 11: Open the URL, enter the username and password and click "Login" button.

Step 12: It will ask you to create new password. So, enter the new password and click "Save" button.


Customize Application permission

“Customize Application” permission is in Administration Permission under profile.

How to test static methods in Salesforce?

To test static methods in Salesforce, we have to call the method along with the controller name, not with the object of the controller.

Example:

Apex Class:

public class example
{
    public static integer add(integer a, integer b)
    {
        return (a+b);  
    }

    static testMethod void testforExample()
    {
        example.add(8,9);
    }
}

How to return value from Apex method to Javascript in Salesforce using a custom button?

Example:

Apex Class:

global class web
{
    Webservice static String fetch(Id localId)
    {
        return localId;
    }
}


Custom Button Javascript:

{!REQUIRESCRIPT("/soap/ajax/15.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/15.0/apex.js")}

var r = confirm("Are you sure want to fetch?");

if(r == true)
{
    var a = sforce.apex.execute("web","fetch",{ID:"{!Account.Id}"});
    alert(a);
}
else
{
    alert('Operation aborted');
}


Output: