Wednesday, 10 December 2014

How to add Salesforce Chatter Information in Visualforce Page??

Adding chatter functionality in to visualforce is quite simple. Use below tags.

  • <chatter:feed>: Displays the Chatter feed for a record.

  • <chatter:feedWithFollowers>: An integrated UI component that displays the Chatter feed for a record, its list of followers, and optionally, a header bar that allows users to show or hide the Chatter feed and subscribe to it.

  • <chatter:follow>: Renders a button for a user to follow or unfollow a Chatter record.

  • <chatter:followers>: Displays the list of Chatter followers for a record.

<chatter:feed entityId="{!Leadid}" />

<chatter:follow entityId="{!Leadid}" />
<chatter:followers entityId="{!Leadid}" />

Id LeadId =  ApexPages.currentPage().getParameters().get('id');


Monday, 8 December 2014

Phone Validation For USA format.

Hi 
We all know USA phone number "(999) 999-9999" . How do we restrict user from invalid entry ?

We can create validation rule.

Error Condition Formula:- NOT(REGEX(Phone__c, "^\\(\\d{3}\\)\\s?\\d{3}-\\d{4}"))

Error Message:- US phone numbers should be in this format: (999) 999-9999.

if you want to add validation in controller, below is the method



public static boolean isValid(String phone){
    
        
        String PhoneRegex =  '^\\(\\d{3}\\)\\s?\\d{3}-\\d{4}';
        
        Pattern MyPattern = Pattern.compile(PhoneRegex);
        
        // then instantiate a new Matcher object “MyMatcher”
        Matcher MyMatcher = MyPattern.matcher(phone);
        if (!MyMatcher.matches()) {
        return false;
        }else{
        return true;
        }

    }

public PageReference insertValue(){
        if(Email_PhoneValidationController.isValid(testObj.Phone__c)){
            insert testObj;
        }
        else{
            testObj.Phone__c.addError('Invalid Phone Number format ...US phone numbers should be in this format: (999) 999-9999 ');
           
        }
        return null;

    }

For the above regex "9999999999" & "999-999-9999" are invalid entry. This format "999-999-9999 "  is aleo an USA format. If you want to make it valid entry then use below regex

NOT(REGEX(Phone, "\\D*?(\\d\\D*?){10}")) .


How to refer custom html page from document in visualforce page.

Hi All, 

I came across one requirement during work, thought to share, it will be useful info for you. I was working on designing partner portal site for user,as you all know for designing site,we have to take care of company branding, header and footer and lot more style sheet and css, and it's not a best practice to use all the code in vf page itself ,because same header and footer might be required to be used in several pages,so it's better we will keep it separately whenever it is required we can refer it.

We have stored header and footer code(html page with css) in document object in sfdc.Now the question is how can we refer it in vf page? If we have stored in static resource it is quite simple to refer it.(use global variable $Resource).

Solution:- Use Below code to refer this.
   public String getHeader() {
        
        return [Select Body,Name From Document Where Name  = 'Header'].Body.toString();
    }
  
  
    public String getFooter() {
        
        return [Select Body,Name From Document Where Name= 'Footer'].Body.toString();
    }

In visual-force 
<apex:outputText value="{!Header}" escape="false"/>
<apex:outputText value="{!Footer}" escape="false"/>

It is quite simple,is not it ?????

Monday, 17 November 2014

Searching Component In SFDC

Hi All,

This is a  cool post for me.Here I have created one page where you can search many sfdc component(apex class,vf pages, user,report,approval process, trigger). 

Useful for Whom ?

  • All developers who always try to finish work as son as possible.
  • Don't want click on Next & Prev link to reach at particular component(if more than 100 is there).
  • Want to get all different component in one page.
  • The best thing is with in less time to get component.

We can search these component as below image.if you want to search more than add that component in options list rest will be take care.




Here is the Page:-

<apex:page controller="SearchApexComponent">
    <apex:form >
        
        <apex:pageBlock title="Find Your SFDC Component" id="pblock">
        <apex:pageMessages id="message"></apex:pageMessages>
         <apex:outputLabel value="Choose Search Item">
                <apex:selectList value="{!objectname}" size="1" multiselect="false">
                    <apex:selectOptions value="{!options }" >
                    </apex:selectOptions>
                </apex:selectList>
            </apex:outputLabel>
            <apex:outputLabel value="Enter Name" for="txt"></apex:outputLabel>
            <apex:inputText value="{!inputString}" id="txt"/>
            <apex:commandButton value="Search" action="{!Showclasses}" reRender="pbt,message,pblock"/>
            <apex:pageBlockTable value="{!Classes}" var="cls" id="pbt">
                <apex:column headerValue=" Name">
                <apex:commandLink action="{!Go}" target="_blank">
                    <apex:param name="clsid" value="{!cls['id']}"/>
                     <apex:outputField value="{!cls['name']}"/> 
                     
                </apex:commandLink>
                </apex:column>
                <apex:column headerValue=" Created By">
                     <apex:outputField value="{!cls['CreatedByid']}"/> 
                </apex:column>
                <apex:column headerValue=" Modified By">
                     <apex:outputField value="{!cls['LastModifiedByid']}"/> 
                </apex:column>
                
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
  
</apex:page>

Here is Controller :-

public with sharing class SearchApexComponent {
    public String inputString{get;set;}
    public String objectname{get;set;}
    public List<sObject> Classes{get;set;}
    string classId;
    public List<SelectOption> options{get;set;}
    public SearchApexComponent(){
        Classes = new List<sObject>();
        options = new List<SelectOption>();
        options.add(new selectOption('','--None--'));
        options.add(new selectOption('ApexClass','ApexClass'));
        options.add(new selectOption('ApexPage','VisualForce Page'));
        options.add(new selectOption('ApexTrigger','Trigger'));
        options.add(new selectOption('Approval','Approval Process'));
        options.add(new selectOption('User','User'));
        options.add(new selectOption('Document','Document'));
        options.add(new selectOption('Profile','Profile'));
        options.add(new selectOption('PermissionSet','PermissionSet'));
        options.add(new selectOption('Report','Report'));
        
    }
    
    public PageReference Showclasses(){
        system.debug('printing claaneem---'+Objectname );
        if(Objectname ==null || Objectname == '' || Objectname == '--None--'){
            
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please choose component what you want to search');
            ApexPages.addMessage(myMsg);
            return null;   
        }
        else if(inputString ==null || inputString == ''){
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Please Enter Some Input String');
            ApexPages.addMessage(myMsg);
        }
        else{
            String sQuerry  = 'select id,name,CreatedByid,LastModifiedById from '+Objectname +' where name LIKE '+'\'%'+inputString+'%\''+'LIMIT 100';
            System.debug('Print sQuerry  -->'+sQuerry  );
            classes = Database.query(sQuerry );
        }
        
        system.debug('printing Classes list---'+Classes);
        return null;
    }
     
    public PageReference Go(){
        classId = Apexpages.currentpage().getparameters().get('clsid');
        
        PageReference requestPage = new pagereference('https://cs1.salesforce.com/'+classId);
        requestPage.setRedirect(true);
        return requestPage;
    }
}


Wednesday, 5 November 2014

Filtering Record Using Long Text Area Field

Hi All,

We might have come across a scenario to filter some record based on a field value which is long text area type.This is post is all about how can we filter records using text area field value.

Here is code:-

String s;
list<Account> listOfAccounts = [SELECT id,name FROM Account WHERE TextAreaFiedl__c like :'%'+s+'%'];

If we write same code then compiler will fire a error like below image.


Below is work around for above error.

String s = 'asish';
list<Account> listOfAccounts;
 listOfAccounts = new list<Account>();
for(Account acc:[SELECT id,name,TextAreaFiedl__c FROM Account where name='test']){
    if(acc.TextAreaFiedl__c.Contains(s)){
       listOfAccounts.add(acc);
    }
}

Saturday, 1 November 2014

How would we get recordtype id and recordtype name of an particular Object?

Hi All,

Sometimes it may require to know the recordtypeid and recordtypename of an object in apex class.This is post is all about to make you comfortable with Recordtype methods.I am assuming you have concept of recordtype. Below is few code snippet to make you comfortable with recordtype method.

RecordTypeInfo is a class contains methods for accessing recordtype information for an sObject with associated recordtype.

getRecordTypeInfosByName(); - Returns maps that associate RecordTypeInfo with  record labels.

getRecordTypeInfosById();- Returns maps that associate RecordTypeInfo with  record Id.

getname():- Returns recordtype name.

getRecordTypeId() :- Returns recordtype id.

isAvailable() :-Returns true if this record type is available to the current user, false otherwise

isDefaultRecordTypeMapping() :-Returns true if this is the default record type mapping, false otherwise.

Here Contact is the standard object and Service Contact is the recordtype name.

Schema.DescribeSObjectResult contactDescribe = Schema.SObjectType.Contact;  
        Map<String,Schema.RecordTypeInfo> rtMapByName = contactDescribe.getRecordTypeInfosByName();  
        Schema.RecordTypeInfo rtName = rtMapByName.get('Service Contact');
        system.debug('hiiiii>>>>'+rtName.getRecordTypeId());--- It prints recordtype Id
system.debug('hiiiiihelllooo>>>>'+rtName.getName());--It prints recordtype name.


Wednesday, 22 October 2014

Displaying a picklist in Mulit Select Checkbox format in Salesforce

Hi All,

Generally we provide flexibility to user so that user can select multiple value form a picklist at a time. This post is only for displaying a pick-list in multi select check-box format.  

Here is the page:-

<apex:page controller="multiselectCheckboxController ">
    <style>
    input[type='checkbox'] {
        border: 1px solid #aaa;
        display: block;
    }
    </style>
   <apex:form> 
        <apex:pageBlock>
        <apex:pageBlockSection columns="1">
            <apex:pageblocksectionitem >          
                <apex:outputlabel value="Industory" />
                <apex:selectcheckboxes layout="pageDirection" value="{!Industoryname}">                   
                    <apex:selectoptions value="{!Industorynames}" />          
                </apex:selectcheckboxes> 
            </apex:pageblocksectionitem>
     </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>

</apex:page>

Controller :--

public class multiselectCheckboxController {

    public List<string> Industoryname{get;set;}

public multiselectCheckboxController () 
    {
        Industoryname =new List<String>();
    }

public List<selectoption> getIndustorynames()
    {           
        list<selectoption> options = new list<selectoption>();            
        try 
        {               
        //Product Name is a MultiSelect Picklist               
        Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();

        list<schema.picklistentry> values = fieldResult.getPickListValues();               
        for (Schema.PicklistEntry a : values) 
        {                  
        options.add(new SelectOption(a.getLabel(), a.getValue()));
        }           
        }  
        catch (Exception e) 
        {             
        ApexPages.addMessages(e);           
        }
        system.debug('## Product Name Options'+ options);          
        return options; 
    }

}

Friday, 26 September 2014

How to get help text in apex class ??

We generally use help text while creating custom field in salesforce . Sometimes we need it in apex controller while development. This post is regarding to get help text of particular field and display in vf page. 

Here is some code snippet to get help text in apex class.

Schema.DescribeFieldResult dfr = Schema.sObjectType.Account.fields.TestField__c;
String helptext = dfr.getSObjectField().getDescribe().getInlineHelpText();

In the visualforce page we can display help text.

{!$ObjectType.Account.fields.TestField__c.inlineHelpText}

Sunday, 14 September 2014

How to check list size in Visualforce page

Hi All,

It seems to very simple by name but not as much simple as you are thinking now.As we all know list itself has a method so called size() to check its size,however we can write list.size() in controller, which will return no. of elements present in the list otherwise return 0 if no elements present .But we can not write list.size method in visual-force page,then how will we check ????

For that I have done a workaround, one visual-force page is there having one field Account Type. When Account Type will be selected with some value ,then list of Accounts records will be displayed whose Account Type is matched with the selected value otherwise a message saying No Accounts Present in this Type.

Here is page:-

<apex:page controller="passingParamActionFuncController">
    <apex:form >
        <apex:pageBlock title="Account Information" id="pb">
            <apex:pageBlockSection >
                <apex:inputField value="{!account.Type}" Onchange="displayAccount();"/>
                <apex:actionFunction name="displayAccount" action="{!displayAccount}" reRender="panel,mess"/>
                <apex:outputPanel id="panel">
                    <apex:pageMessages id="mess"></apex:pageMessages>
                 
                        <apex:pageBlockTable value="{!listOfAccounts}" var="account" rendered="{! IF(ISBLANK(listOfAccounts), false, true) }">
                     
                            <apex:column value="{!account.Name}"/>
                            <apex:column value="{!account.Type}"/>
                        </apex:pageBlockTable>
                     
                    </apex:outputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>

</apex:page>

And Controller
public with sharing class passingParamActionFuncController {

    public Account account { get; set; }
 
    public list<Account> listOfAccounts{get;set;}
 
    public passingParamActionFuncController(){
        account = new Account();
    }
 
    public PageReference displayAccount() {
        System.debug('Printing account-->'+account.Type);
        listOfAccounts = [SELECT id,Name,Type
                          FROM Account
                          WHERE Type =:account.Type];
                       
        if(listOfAccounts.size() == 0){
            Apexpages.addMessage(new ApexPages.message(ApexPages.Severity.Info,'No Accounts Present in this Type'));
        }
        return null;
    }

 
}

Friday, 22 August 2014

How to do DML Operation when a Page loads

Hi All,

Here is a scenario that I have come across, there was a need to do DML operation when a vf page loads.

How will we achieve it ?

As we all know when a page loads, constructor executes first but we can not write DML statement in constructor,however there is another approach for the above requirement. 

Here is the Page. 
<apex:page controller="DMLStatementOnPageloadController" action="{!createAccount}">
</apex:page>
createAccount will be invoked when page loads.

Controller:-
public with sharing class DMLStatementOnPageloadController {

    public PageReference createAccount(){
        Account acc = new Account(name = 'DMLStatementOnPageload');
        insert acc ;
        return null;
    }
}


Thursday, 3 July 2014

How can we check singly email limit ?

We can send emails programmatically in Apex, however  if we're not careful we can hit the measly governor limit of 10 in no time at all. We know, although  outbound email limit is 1000 with Apex, but only a total of 10 sendEmail method calls are allowed in each context.
Obviously the way to avoid this is to gather up all emails we want to send in a list and call the sendEmail method once from your Apex context. When passing an argument to the sendEmail method it must be of type Email. 

In the mean while we need to check how many times we have already called send email method in a transaction and how more are remaining.How will we do that?

Below is the few lines of code.

Integer used = Limits.getEmailInvocations();
Integer emailLimit = Limits.getLimitEmailInvocations();
System.debug('print--used ->'+used );
System.debug('print--emailLimit ->'+emailLimit );

Tuesday, 24 June 2014

How to pass lookup field id to controller?

Lets take an example. Suppose we want pass Accountid(look up field from contact to account) from visual force page to controller. If we choose one account from look up then automatically account industry will be populated.

Here is the page:-

<apex:page controller="passingLookupIdController">
  <script>
    function doSomething(test) {
      
        alert('hi-->'+test);
        PassingParameter1(test);
        // lkfield.value now has the selected ID value
    }
    </script>
 <apex:form >
  <apex:actionFunction name="PassingParameter1" action="{!PassingParameter}" reRender="field1">
  <apex:param value="" name="recordId"/>
  </apex:actionFunction>

   <apex:pageBlock >
          <apex:pageBlockSection id="someArea">

               <apex:inputField value="{!con.AccountId}" id="field">
                  <apex:actionSupport event="onchange" reRender="field"oncomplete="doSomething('{!con.AccountId}');"/>
              </apex:inputField>
               <apex:inputField value="{!account.Industry}" id="field1" />
          </apex:pageBlockSection>
      </apex:pageBlock>
  </apex:form>
</apex:page>


Here is controller:-

public with sharing class passingLookupIdController {
    public Contact con{get;set;}
     public Account account{get;set;}
    public passingLookupIdController (){
        con =  new Contact();       
    }
    public PageReference PassingParameter(){
        Id recordId = ApexPages.currentPage().getParameters().get('recordId');
        System.debug('Print--->'+recordId );
        account = [SELECT ID,Industry FROM Account WHERE id=:recordId ]; 
        return null; 
    }
}

How to use required attribute in picklist as like salesforce standard?

There is an attribute called Required which can be used in almost all visual-force component.If we use that attribute then red color mark will be appended with the field and if we don't enter any value ,try to save,then it shows one error(You must enter some value) just below to that field. 

For example:-
<apex:inputField value="{!account.Industry}" id="field1" required="true"/> 

save image Here Industry is a standard pick-list, if we write required = true, red mark is coming,however if we are making pick-list in controller and displaying using <apex:selectlist> and <apex:selectoptions> then red won't be displayed. 
<apex:selectList label="Picklist" multiselect="false" size="1" required = "true">
               <apex:selectOptions value="{!options }">
                  </apex:selectOptions>

 </apex:selectList>

options = new list<SelectOption>();
        options.add(new SelectOption('-None-','-None-'));
        options.add(new SelectOption('A','A'));
        options.add(new SelectOption('b','b'));
        options.add(new SelectOption('c','c'));
        options.add(new SelectOption('d','d'));


It will display like below image

save image 
How can we display like standard pick-list?
Below is some code for this.
<apex:pageBlockSection id="someArea">
          <apex:pageBlockSectionItem >
               <apex:outputLabel value="picklistLabel"/>
                 <apex:outputPanel layout="block" styleClass="requiredInput">
                     <apex:outputpanel layout="block" styleClass="requiredBlock"/>
                     <apex:selectList label="Picklist" multiselect="false" size="1" >
                            <apex:selectOptions value="{!options }"/>
                   </apex:selectList>
                </apex:outputPanel>
                </apex:pageBlockSectionItem>

</apex:pageBlockSection>
save image

Wednesday, 18 June 2014

How to permanently delete record from data base.

As we all know if we delete records from our org. It will be stored in recycle bin for 15 days. We can go to recycle bin and delete manually. 
Suppose the requirement is when we delete records those records should be deleted from recycle bin.
For this requirement we have to write a trigger on object. 

trigger todelteRecordPermanent on Account (after delete) {
    list<Id> Ids = new list<Id>();
    for(Account  account: Trigger.old){
        Ids.add(account.id);  
    }
    Database.emptyRecycleBin(ids);
}

How to get deleted records from recylebin and restore them to database

We need to use ALL ROWS keyword in soql query.
ALL ROWS keywords need to be used to query all records in an organization, including deleted records( records in your organization's Recycle Bin) and archived activities. 

You cannot use the ALL ROWS keywords with the FOR UPDATE keywords. 


list<Account> listOfAccounts = [SELECT id,Name FROM Account WHERE isDeleted = true ALL ROWS];

undelete listOfAccounts ;


isDeleted:- It is a standard field of account used to differentiate whether account is in Recycle Bin or not. 

undelete:- Its a DML Operation.


FOR UPDATE:Keywords used in SOQL to lock an sobject records and preventing from being updated. 
P.S.:- ORDER BY and FOR UPDATE keywords in any SOQL can not be used together.

Tuesday, 17 June 2014

How to add validation through trigger in salesforce

Hi All,
This post is regarding to add validation and to display error message through trigger. 
Suppose we want to give validation is no account should be created having name as 'asish'
We can do this by validation rule easily,in some case we want through trigger. Keep in mind trigger should be ours last choice.We should use standard functionality as much as possible.

Here is trigger for above validation:-

trigger ValidateAccount on Account (before insert,before update) {
    for(Account account:Trigger.new){
        if(account.Name == 'asish'){
            account.Name.addError('You can not create account having name as Asish');
        }
    }
}


Here is the output showing error message while creating account.

save image