Saturday, 1 September 2012

How to Create a Validation Rule in Salesforce.com(Force.com)

What Are Validation Rules in Salesforce.com:
From Salesforce.com Premier Support Rep:
"Validation rules verify that the data a user enters in a record meets the standards you specify before the user can save the record. A validation rule can contain a formula or expression that evaluates the data in one or more fields and returns a value of "True" or "False." Validation rules also include an error message to display to the user when the rule returns a value of "True" due to an invalid value."

In simplest terms, some rule that you would like to do checks on your system, record.

So, Validation Rules are Available in: Group, Professional, Enterprise, Unlimited, and Developer Editions.

To create validation rules:
  • Go to the Object you would like to create the validation rule on. To get to that object click Setup and then Customize. If it is a standard object like Account, Contact, Opportunity, Product, etc.
  • If it is a Customize Object then click on Setup==> Create==>Objects and then click on the object you like.
  • Now click on Validation Rule and click New.
  • Give your Validation a Name
  • Give it a Description (not needed but helps in the long run and good practice)
  • Check the Active Box to make it Active
  • Error Condition Formula: This is where you place in your expression to validate the field. For example: Let say you want to validate that US States Field to have 2 abbreviations in it. The rule would be something like:
  • AND (
    OR(BillingCountry = "US", BillingCountry="USA", LEN(BillingCountry)=0),
    OR(
    LEN(BillingState) < 2, NOT( CONTAINS("AL:AK:AZ:AR:CA:CO:CT:DE:DC:FL:GA:HI:ID:" & "IL:IN:IA:KS:KY:LA:ME:MD:MA:MI:MN:MS:MO:MT:NE:NV:NH:" & "NJ:NM:NY:NC:ND:OH:OK:OR:PA:RI:SC:SD:TN:TX:UT:VT:VA:" & "WA:WV:WI:WY:PR:MP", BillingState) )))
  • Now in the Error Message Place in the Error you would like the User to see or get.
  • Like : A valid two-letter state code is required.
  • Error Location: Do you want to display the error on top of the page or next to the field itself. If you want it next to the field then click field and choose your field from the picklist.
  • Click Save to finish or Save & New to create additional validation rules.
Done...

Salesforce.com Dataloader for Sandbox


Scenario:
   You want to load data, update data through Salesforce.com Dataloader to the Sandbox Instance.

Solution:
  1. Open up the Apex Dataloader tool.
  2. Go to Settings==>Settings
  3. Where it States Server Host (clear for Default) replace the https://login.salesforce.com with https://test.salesforce.com
See attach pic
Thanks
Ashok.

Interview Questions for Salesforce Administrators

Hi, Welcome Back.
Is your company currently looking for a Salesforce Administrator? If yes, then you need to asked them correct questions so you get the right candidate and not someone you need to teach.

A Salesforce Administrator should have knowledge of Validation Rules, Objects, Fields, Workflow Rules, User Profiles and General Knowledge. So I have prepared questions to ask interviewee  about Salesforce.com. This may even help people who are going to the interview for a salesforce.com administrator position.
Lets Start:
  1. What is the difference between Lookup Relationship and Master-Detail Relationship?
  2. True or False? If you were to delete a record that had a lookup to a child object, all child object records would get deleted as well.
  3. Where is the view Account hierarchy link?
  4. What does the Account Hierarchy tell or do?
  5. Where can you make a field required?
  6. I'm setting up different page layouts for different user profiles.  As a system administrator, is there another way to see what the user sees instead of them granting log in access to you?
  7. What type of Workflow Alerts are there?
  8. Validation Rules, What are they use for in Salesforce?
  9. What is Dataloader?
  10. What is the difference between Profiles and Roles in Salesforce.com?
Thanks
Ashok.

How to use Substring in Apex Code - Force.com

Hi everyone:

Scenario:
We have a string value to be copied from one field in a Standard object to the Custom Object Standard field "Name". Yes you can do this in a formula field but if the objects are not related directly you can not.

So, a little bit about Custom Object regarding the standard field "Name". 
Name field in a custom object its length is 80 MAX. No one can change the attribute on this field to go over 80 length.
So since we are utilizing code to do the update, Apex will not automatically cut off the string if it is more then 80. It will submit an error.

Solution:
We utilized substring method in Apex to accomplish anything more then 80 characters going into the name.
Substring Method - "Returns a new String that begins with the character at the specifiedstartIndex and extends to the character at endIndex - 1." Click Here for more on String Methods

To clarify this, if we have a string such as 'ABC' length is 3 characters. If you place this in a substring and you wanted the first 2 characters, it would be 'ABC'.substring(1,3) = 'AB' ... Make it mathically easier, 3-1=2 which gets you the first 2 characters in your string.

Now the catch in code, you would need utilize the actually name of the field instead of placing it in a string.
String ProdName;

Product2 prod = [ SELECT p.ProductCode, p.Name, p.Id, 
FROM Product2 p 
WHERE p.Id =: oppLineItem.PricebookEntry.Product2Id];
 
if(prod.Name.length()>80){


//This would get the first 90 characters of the string
ProdName = prod.Name.SubString(0,80); customobject__c.Name = prodName; }
I hope this helps... 
A little lesson in code sometime does not hurt anyone.
Thanks
Ashok.

Change Password via Developer Console in Salesforce without resetting password

Scenario:
      We need to reset a password or change the password on an user utilizing a 3rd party app in salesforce. This user is there for the app only and not really a physical user in the instance. The email for this user is a person who has left the company or is on vacation but you need the app to work.

Solution:
    You can do this 2 ways:
  1. Change the Email of the user in question
  2. Click on Generate Password and click save.
But lets say you can not change the Email of the user because you should not be the owner of the app or you are not part of the app as an admin. Here is where you change using Developer Console.

Go to Setup and Drop it down to Developer Console or sometimes called the System Log




Within the "Logs" tab you will see a button called "Execute".
 

Click on the text box or white space next to it.

It shall open up another window which is titled "Enter Apex Code"
 
Place in the following SOQL query:
User usr = [select Id from User where username='appuser@myzc.com'];
System.setPassword(usr.Id,'welcome1234'); 

Then click on Execute.
It should bring up a success window and you should be good to go.
Now you may need to log in and make sure everything is ok.

Hope this helps... I am not responsible for anyone utilizing this method... It can be a risk... I would check before you do this task.
Thanks
Ashok.

How to get the latest Case Comment on an Email Template/Alert in Salesforce.com

Hi everyone:

Recently, I was asked on how would one get the most latest case comment onto a Email Template for an Email alert to go out.
Of course as you know if you place in {!CaseComment.Comments} it will not work. No such thing.
So how do you do get the case comments to show in a email alert.

Solution:
Step 1:
   Create a new field on the Case Object. Name it whatever you want and make sure it is Text Area(Long) as an attribute for the field.

Navigate to:
Setup | App Setup | Customize | Cases | Fields | New Field
Create your new field make sure you select Text Area(Long) for the attribute.




Step 2:
Create a workflow rule off the Case Comment Object to update the new field.
Navigate to:
Setup | App Setup | Create | Workflow Rules & Approvals | Workflow Rules | New Rule



  1. Select Case Comment as the object
  2. Place in the Rule Name
  3. Select the first option:
  4. When a record is created, or when a record is edited and did not previously meet the rule criteria
  5. For criteria:
  6. Case Comment: Body is not equal to null

Click Save & Next.
Under Workflow Action Click on Field Update.
Place in a Name.
Field to Update, Select Case Object and select the new field that was created in Step 1.
Select Use a formula to set the new value
Place in the formula:
 CommentBody 
Click Save.
Click Done and Activate.
Final view of your workflow rule should look like:

Go to an existing case, create a new case comment.
The workflow rule should fire and update the new field.

Step 3:
   Now that we know it is working, lets go to an email template.

Place it the new field from the case object within that email template.

Now if you have an existing workflow rule that does Email alert as an workflow action for that rule, you should receive the latest comments on that email template now.


Thank you
I hope this helped.

Thursday, 26 April 2012

Step by Step Salesforce Tutorial – Creating Trigger and test cases

 This is the last tutorial in series and we will see that how to create a Trigger and Test Cases in salesforce.
A trigger is an Apex script that executes before or after specific data manipulation language (DML) events occur, such as before object records are inserted into the database, or after records have been deleted.
Triggers are stored as metadata in Salesforce.com. A list of all triggers in your organization is located at Setup | Develop | Apex Triggers. In addition to this list, triggers are associated and stored with specific objects.
To define a trigger:


  1. For a standard object, click Setup | Customize, click the name of the object, then click Triggers.For a custom object, click Setup | Create | Objects and click the name of the object.For campaign members, click Setup | Customize | Campaigns | Campaign Member | Triggers.For case comments, click Setup | Cases | Case Comments | Triggers.
    For email messages, click Setup | Cases | Email Messages | Triggers.
  2. In the Triggers related list, click New.
  3. Click Version Settings to specify the version of Apex and the API used with this trigger. If your organization has installed managed packages from the AppExchange, you can also specify which version of each managed package to use with this trigger. Generally, you should use the default values for all versions. This associates the trigger with the most recent version of Apex and the API, as well as each managed package. You can specify an older version of a managed package if you want to access components or functionality that differs from the most recent package version. You can specify an older version of Apex and the API to maintain specific behavior.
  4. Select the Is Active checkbox if the trigger should be compiled and enabled. Leave this checkbox deselected if you only want to store the script in your organization’s metadata. This checkbox is selected by default.
  5. In the Body text box, enter the Apex for the trigger. A single trigger can be up to “1 million” characters in length.
Read this URL for Governor limit reference.
To define a trigger, use the following syntax:

trigger triggerName on ObjectName (trigger_events) {
   code_block
}
where trigger_events can be a comma-separated list of one or more of the following events:

  • before insert
  • before update
  • before delete
  • after insert
  • after update
  • after delete
  • after undelete
So, lets start with creating trigger.
I want that duplicate student should not be created on the basis of Email id. we can achieve this by other way also, like during creation of email field, we can specify it as unique field.
Open eclipse and right click on salesforce project and select Create new Trigger, as shown in below image

Creating Trigger in Salesforce using force.com IDE
Creating Trigger in Salesforce using force.com IDE
As you can see, to create trigger we have to select the Apex version and operations in wizard.
During Trigger creation, keep in mind that it may be required in bulk operations so governor limit may be problem.
So instead of getting query for all triggers individually, I created an array and after that created a set of email entered for all records, and loop through all records invidually and checked for duplicity.
Only one SOQL is fired instead of all triggers individually and thus can work for bulk insert.

For SOQL Best Practice refer :
http://wiki.developerforce.com/index.php/Best_Practice:_Avoid_SOQL_Queries_ Inside_FOR_Loops


trigger DuplicateStudentCheck on Student__c (before insert) {

       //Get all Student__c related to the incoming Student records in a single SOQL query.
       Student__c[] studentsList = Trigger.new;
       Set emailSet = new Set();
       for(Student__c s : studentsList)
       {
        emailSet.add(s.Email__c);
       }

       //Get list of duplicate Students
       List duplicateStudentList = [Select s.Name, s.Email__c From Student__c s
where s.Email__c IN :emailSet];

       Set duplicateEmailIds = new Set();

       for(Student__c s : duplicateStudentList)
       {
        duplicateEmailIds.add(s.Email__c);
       }

       for(Student__c s : studentsList)
       {
            if(duplicateEmailIds.contains(s.Email__c))
            {
             s.Email__c.addError('Record already exist with same email Id');
            }
       }
}
Note: You can add, edit, or delete Apex using the Salesforce.com user interface only in a Developer Edition organization, a Salesforce.com Enterprise Edition trial organization, or sandbox organization. In a Salesforce.com production organization, you can only make changes to Apex by using the Metadata API deploy call, the Force.com IDE, or theForce.com Migration Tool. The Force.com IDE and Force.com Migration Tool are free resources provided by salesforce.com to support its users and partners, but are not considered part of our Services for purposes of the salesforce.com Master Subscription Agreement.
Test Cases in Salesforce :

Test case integral part of code developement.


  • You must have at least 75% of your Apex scripts covered by unit tests to deploy your scripts to production environments. In addition, all triggers should have some test coverage.
  • Salesforce.com recommends that you have 100% of your scripts covered by unit tests, where possible.
  • Calls to
    System.debug 
    are not counted as part of Apex code coverage in unit tests.
So, here we are going to create Test Case for trigger which we have written:

@isTest
private class TestTriggers {

    static testMethod void myUnitTest() {
        Student__c s = new Student__c();
        s.Name = 'Om Test';
        s.l_Name__c = 'LastName';

        Course__c c = new Course__c();
        c.Name = 'SFDC';
        c.Fees__c = 2000;
        insert c;

        s.Course__c = c.Id;
        s.Installment_1__c = 2000;
        s.Email__c = 'admin@shivasoft.in';
        try
        {
         insert s;
        }
        catch(System.DMLException e)
        {
         System.assert(e.getMessage().contains('Record already exist with same email Id'));
        }
    }
}
To run the test case from Eclipse, right click on test class as shown in below image:

Run Test Case using Eclipse in Salesforce
Run Test Case using Eclipse in Salesforce
The output of the test case, Test coverage result:

Test Coverage result Eclipse in Salesforce
Test Coverage result Eclipse in Salesforce
Run test cases from salesforce.com browser:

click Setup | Develop | Apex Classes, click the name of the class, then click Run Test. If your class calls another class or causes a trigger to execute, those Apex scripts are included in the total amount used for calculating the percentage of code covered.
To run all the unit tests in your organization, click Setup | Develop | Apex Classes, then click Run All Tests.

 Possibly Related posts:

1.Step by Step Salesforce Tutorial – Creating custom object – 1 of 6 
2.Step by Step Salesforce Tutorial – Creating Email Template – 4 of 6 
3.Step by Step Salesforce Tutorial – Creating Tab and Validation Rule – 3 of 6
4.Step by Step Salesforce Tutorial – Creating fields – 2 of 6 
5.Step by Step Salesforce Tutorial – Creating Workflow rule – 5 of 6