Sunday, March 15, 2015

Wrapper class usage in apex and visualforce pages.

Wrapper class usage in apex and visualforce pages.

A common use case for Visualforce is to present a list of sObjects, allowing a user to select a number of these, and then choose an action to apply to the selected entries. Marking an sObject entry as selected presents a challenge, as it is associating transient information, the selected status, with a record persisted in the Salesforce database.

The solution is to use a wrapper class to encapsulate or wrap an sObject instance and some additional information associated with the sObject instance.

In the below example i developed a visualforce page with delete functionality based on the selected account records. when ever user select's particular account records to delete then wrapper object holds the selected account with check box value as true, then based on the check box value we can able to delete the particular selected account records.

Controller Class: 
Here i am using custom controller to develop the wrapper functionality, Here AccountRecordCls  is wrapper class to have multiple things like  holding the selected account record with check-box value and individual account record.


public class AccountDeleteWrapperCLs{
public List<AccountRecordCls> accWrapperRecordList {get;set;}


 public AccountDeleteWrapperCLs(){
 List<Account> accList= new List<Account>();
 accWrapperRecordList = new List<AccountRecordCls>();
 accList = [select id,Name,Phone,AccountNumber from Account];
  if(!accList.isEmpty()) {
    for(Account acc: accList){
     AccountRecordCls arcls = new AccountRecordCls();
     arcls.isSelected =  false;
     arcls.accObj = acc;
     accWrapperRecordList.add(arcls);
    
    } //end of for loop.
  
  } //end of if condition.
 }
  
  /*
   Delete Account functionality based on the selected records.
  */
  public PageReference DeleteAccount(){
   List<Account> accToDelete = new List<Account>();
   //To hold the unselected account records.
   List<AccountRecordCls> listUnSelectedRecords  = new List<AccountRecordCls>();  
    if(accWrapperRecordList !=null && accWrapperRecordList.size()>0) {
      for(AccountRecordCls wrapObj :  accWrapperRecordList){
        if(wrapObj.isSelected == true){
          accToDelete.add(wrapObj.accObj);
        }else{
          listUnSelectedRecords.add(wrapObj);
        }
      
      
      }//end of for.
      /*
       checking the delete list size and assign the unselected values to 
       original wrapper list.
      */
      if(accToDelete !=null && accToDelete.size()>0){
       delete accToDelete;
       accWrapperRecordList.clear();
       accWrapperRecordList.addAll(listUnSelectedRecords);
      }
    
    }else{
     ApexPages.Message  myMsg = new ApexPages.Message(ApexPages.Severity.info, 'Records were not there to delete.');
     ApexPages.addMessage(myMsg);
    }
    
    return null;
  }

  

 /* Wrapper class with checkbox and account object. 
  this is also  called as inner class 
  */

 public class AccountRecordCls{
  public boolean isSelected {get;set;}
  public Account accObj {get;set;}

 }

}

Visualforce Page: 


<apex:page controller="AccountDeleteWrapperCLs">

 <!-- This i am using for action status message display with processing records information -->

 <style>
    /* This is for the full screen DIV */
    .popupBackground {
        /* Background color */
        background-color:black;
        opacity: 0.20;
        filter: alpha(opacity = 20);
    
        /* Dimensions */
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 998;
        position: absolute;
        
        /* Mouse */
        cursor:wait;
    }

    /* This is for the message DIV */
    .PopupPanel {
        /* Background color */
        border: solid 2px blue;
        background-color: white;

        /* Dimensions */
        left: 50%;
        width: 300px;
        margin-left: -100px;
        top: 50%;
        height: 50px;
        margin-top: -25px;
        z-index: 999;
        position: fixed;
        
        /* Mouse */
        cursor:pointer;
    }
</style>
<apex:actionStatus id="deleteStatus" stopText="">
    <apex:facet name="start">
        <div>
            <div class="popupBackground" />
            <div class="PopupPanel">
                <table border="0" width="100%" height="100%">
                    <tr>
                        <td align="center"><b>Please Wait</b></td>
                    </tr>
                    <tr>
                        <td align="center"><img src="{!$Resource.AJAXProgressBar}"/></td>
                    </tr>
                </table>
            </div>
        </div>
    </apex:facet>
</apex:actionStatus>

 <!-- end of Action Status --> 
<apex:pagemessages id="Msg"> </apex:pagemessages>
<apex:pagemessage summary="Your are doing Mass Delete On Account Object" Severity="Info" Strength="2"></apex:pagemessage>


 <apex:form id="theForm">
  <apex:commandButton value="Delete Account" action="{!DeleteAccount}" reRender="thePb,Msg" status="deleteStatus"/>
  <apex:pageblock id="thePb">
   <apex:pageblockTable value="{!accWrapperRecordList}" var="record">
   <apex:column headerValue="Select">
     <apex:inputCheckbox value="{!record.isSelected}"/>
    </apex:column> 
    <apex:column value="{!record.accObj.Name}"/>
     <apex:column value="{!record.accObj.Phone}"/>
      <apex:column value="{!record.accObj.AccountNumber}"/>
   </apex:pageblockTable>  
  </apex:pageblock> 
 </apex:form>

</apex:page>



Example of using Wrapper class:

1). http://sfdcsrini.blogspot.com/2014/12/adding-and-deleting-rows-dynamically-in.html

2). http://sfdcsrini.blogspot.com/2014/08/displaying-records-in-visualforce-page.html


That's it
Hope you enjoy........

Friday, March 13, 2015

Visualforce Action Status with background loading image.

Visualforce Action Status with background loading image.


When a user carries out an action that results in a Visualforce form submission, for example,clicking a button, it can be useful to render a visual indication that the submit is in progress.Without this a user may click on the button again, or assume there is a problem and navigate away from the page. The standard Visualforce <apex:actionStatus /> component can display messages when starting and stopping a request, but these messages are easily missed, especially if the user is looking at a different part of the page.

In the below example, we will create a Visualforce page that allows a user to create a case sObject record utilizing the case standard controller. When the user clicks on the button to create the new record, a spinner GIF will be displayed. In order to ensure that we have the user's full attention, the page will be grayed out while the submit takes place.


Visualforce :

<apex:page standardController="Case">
  <style>
    #spinner{
        display: none;
        width:200px;
        height: 50px;
        position: fixed;
        top: 50%;
        left: 50%;
        text-align:center;
        padding:10px;
        font:normal 16px Tahoma, Geneva, sans-serif;
        margin-left: -100px;
        margin-top: -100px;
        z-index:2;
        overflow: auto;
        border:1px solid #CCC;
        background-color:white;
        z-index:100;
        padding:5px;
        line-height:20px;
     }
     #opaque {
         position: fixed;
         top: 0px;
         left: 0px;
         width: 100%;
         height: 100%;
         z-index: 1;
         display: none;
         background-color: gray;
         filter: alpha(opacity=30);
         opacity: 0.3;
         -moz-opacity:0.3;
         -khtml-opacity:0.3
     }
     * html #opaque {
         position: absolute;
     }
  </style>

  <apex:form >
  
    <apex:pageMessages id="msgs" />
    <apex:pageBlock mode="mainDetail" title="Create Case">
     
      <apex:pageBlockButtons >
        <apex:commandButton value="Save" action="{!save}" onclick="showSpinner()" />
        <apex:commandButton value="Cancel" action="{!cancel}" onclick="showSpinner()" />
      </apex:pageBlockButtons>
      
      <apex:pageBlockSection title="Details" columns="1">
        <apex:inputField value="{!Case.Subject}" />
        <apex:inputField style="width:80%" value="{!Case.Description}" />
      </apex:pageBlockSection>
      
      <apex:pageBlockSection >
        <apex:inputField value="{!Case.AccountId}" />
        <apex:inputField value="{!Case.Type}" />
        <apex:inputField value="{!Case.Priority}" />
        <apex:inputField value="{!Case.Status}" />
        <apex:inputField value="{!Case.Origin}" />
        <apex:inputField value="{!Case.Reason}" />
      </apex:pageBlockSection>
      
    </apex:pageBlock>    
  </apex:form> 
   <div id="opaque"/>
   <div id="spinner">
        <p align="center" style='{font-family:"Arial", Helvetica, sans-serif; font-size:20px;}'><apex:image value="/img/loading.gif"/>&nbsp;Please wait</p>
   </div>
   
   <script>
    function showSpinner()
    {
       document.getElementById('opaque').style.display='block';
       var popUp = document.getElementById('spinner');
      
       popUp.style.display = 'block';
    } 
   </script>

</apex:page>


once you enter all the details click on the save button the visualforce page status message is going to display with loading image background with in the div.





More about visualforce example and tags

http://sfdcsrini.blogspot.com/2014/06/visualforce-form-tags-with-examples.html




Saturday, March 7, 2015

Standard Controller Extension,Custom Controller Extensions and Uploading the image and displaying in contact details page.

Standard Controller Extension,Custom Controller Extensions and Uploading the image and displaying in contact details page.


Hi,
In this post i am trying to give a small example on Standard Controller Extension. so the usage of Standard Controller Extension (or) Controller Extension is to extend the functionality.

Here the requirement is create a visualforce page using standard controller and extend the upload image functionality in VF page and display the image in Contact detail page. for this i created two fields in Contact object.

1).  Created a Text field with Name "Srinivas__Images_Path__c" length of 255  to store the url of the image.
2). Created a Formula Field with the name of "Srinivas__Picture__c" return type as Text like this.




Extension Class:

Here i created a class and used Standard Controller in constructor. once the user upload the image that image details is stored as attachment and put the attachment record url in contact object text field to populate with formula field.

public class ContactPhotoExtension {

public Contact cont;
public blob picture {get;set;}

 public ContactPhotoExtension(ApexPages.StandardController st){
  this.cont = (Contact) st.getRecord();
 
 }
 public PageReference save() {
 PageReference pr ;
  try{
     insert cont;
     if(picture !=null) {
      Attachment attachment = new Attachment();
        attachment.body = picture;
        attachment.name = 'Contact_' + cont.id + '.jpg';
        attachment.parentid = cont.id;
        attachment.ContentType = 'application/jpg';
        insert attachment;
     cont.Srinivas__Images_Path__c = '/servlet/servlet.FileDownload?file='+ attachment.id;
                update cont;
       Pr = new PageReference('/'+cont.id);
       pr.setRedirect(true);
    }
   
  
  } catch(Exception  e){
   system.debug('Error Message==>'+e);
  }
 
  return pr;
 } 

}


Visualforce Page:


<apex:page standardController="Contact" extensions="ContactPhotoExtension">
<apex:form >
 <apex:pageblock title="Contact With Image">
  <apex:pageblockButtons >
   <apex:commandButton action="{!Save}" value="Save with Image"/>
    </apex:pageblockButtons>
    
    <apex:pageblockSection title="Contact Information">    
     <apex:inputField value="{!Contact.FirstName}"/>
     <apex:inputField value="{!Contact.LastName}"/>
     <apex:inputField value="{!Contact.Email}"/>
     <apex:inputField value="{!Contact.Phone}"/>
    </apex:pageblockSection>
     <apex:pageBlockSection title="Upload Image Here">
      <apex:inputFile value="{!picture}" accept="image/*" />
     
     </apex:pageBlockSection>
 </apex:pageblock>
</apex:form>
</apex:page>

once you develop these things try to create a record with image and click on "Save with Image" button.




Finally the record detail page is like this.



like this you can extend the functionality of standard or custom with out building the all the things.

Custom Controller With Extension:

Here i created two simple classes to demonstrate simple custom controller extension.

Class 1 :

in this class i am querying account records and stored those in list.

Public class AccountDisplatRecCls{
  public List<Account> getAccounts(){
   List<Account> accList = [select id,Name,AccountNumber from Account];
   return accList;
  
  } 
 }

Class 2:
in this class i am querying contact records and stored those in list and displaying in vf page. 

public class AccountDisplatRecClsExtn{
 
 public List<Contact> contList {get;set;}
 
  public AccountDisplatRecClsExtn(AccountDisplatRecCls act){
    contList = [select id,FirstName,LastName,Email from Contact];
  }
   
 }



Visualforce Page:

in this page i am using booth custom controller and extension controller.


<apex:page controller="AccountDisplatRecCls" extensions="AccountDisplatRecClsExtn">
<apex:pageBlock title="Account Records">
  <apex:pageblockTable value="{!Accounts}" var="acc">
   <apex:column value="{!acc.Name}"/>
   <apex:column value="{!acc.accountNumber}"/>
  </apex:pageblockTable>
</apex:pageBlock>

 <apex:pageblock title="Contacts Details">
  <apex:pageblockTable value="{!contList }" var="con">
    <apex:column value="{!con.FirstName}"/>
     <apex:column value="{!con.LastName}"/>
         <apex:column value="{!con.Email}"/>
  </apex:pageblockTable>
 </apex:pageblock>
  
</apex:page>

Output:



Further reference :

http://www.salesforce.com/docs/developer/pages/Content/pages_controller_extension.htm


Thanks

Monday, February 2, 2015

How to Use Apex:actionSupport tag in Visualforce Page.

How to Use Apex:actionSupport tag in Visualforce Page.

 <apex:actionSupport>

A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the server when a particular event occurs, such as a button click or mouseover.

actionSupport component adds AJAX support to other components in visualforce. It allows components to be refreshed asynchronously by calling the controller’s method when any event occurs (like click on button). It allows us to do partial page refresh asynchronously without refreshing  full page.
In the example below, initially count value is set to 0. But when we will click on ‘Click here to increment! ‘, then controller action method will be called and count will be incremented. Also outputText component will be rendered without refreshing complete page.
Similarly when we will click on ‘Click here to decrement!’, then controller action method will be called and count will be decremented. Also outputText component will be rendered without refreshing complete page.
apex:actionSupport has following attributes in our example:
  • action: action attribute specifies the controllers action method that will be invoked when event occurs.
  • event: It is DOM event that generates AJAX request
  • reRender: It is comma separated id’s of components that needs to be partially refreshed. In our example, we have given its value as ‘out’. So component with ‘out’ id will be refreshed without refreshing complete page.




Attribute
Description
action
The action method invoked by the AJAX request to the server. Use merge-field syntax to reference the method. For example, action="{!incrementCounter}" references the incrementCounter() method in the controller. If an action is not specified, the page simply refreshes.
disabled
A Boolean value that allows you to disable the component. When set to "true", the action is not invoked when the event is fired.
disableDefault
A Boolean value that specifies whether the default browser processing should be skipped for the associated event. If set to true, this processing is skipped. If not specified, this value defaults to true.
event
The DOM event that generates the AJAX request. Possible values include "onblur", "onchange", "onclick", "ondblclick", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onselect", and so on.
focus
The ID of the component that is in focus after the AJAX request completes.
id
An identifier that allows the component to be referenced by other components in the page.
immediate
A Boolean value that specifies whether the action associated with this component should happen immediately, without processing any validation rules associated with the fields on the page. If set to true, the action happens immediately and validation rules are skipped. If not specified, this value defaults to false.
onbeforedomupdate
The JavaScript invoked when the onbeforedomupdate event occurs--that is, when the AJAX request has been processed, but before the browser's DOM is updated.
oncomplete
The JavaScript invoked when the result of an AJAX update request completes on the client.
onsubmit
The JavaScript invoked before an AJAX update request has been sent to the server.               
rendered
A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.
reRender
The ID of one or more components that are redrawn when the result of an AJAX update request returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs.
status
The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component.
timeout
The amount of time (in milliseconds) before an AJAX update request should time out.
 

 Example 1 :

<apex:page controller="actionSupportController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:outputpanel id="panel1">
                    <apex:outputText value="Click here to increment!"/>
                    <apex:actionSupport event="onclick" action="{!incrementCounter}" rerender="out"/>
                </apex:outputpanel>

                <apex:outputpanel id="panel2">
                    <apex:outputText value="Click here to decrement!"/>
                    <apex:actionSupport event="onclick" action="{!decrementCounter}" rerender="out"/>
                </apex:outputpanel>

                <apex:outputText value="{!count}" id="out" label="Count Is:"/>

            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>


Controller : 

public class actionSupportController {
    Integer count = 0;

    public PageReference incrementCounter() {
            count++;
            return null;
    }

    public PageReference decrementCounter() {
            count--;
            return null;
    }

    public Integer getCount() {
        return count;
    }
}






Example 2:
http://sfdcsrini.blogspot.com/2014/08/simple-ajax-example-using-visualforce.html

Example 3: 
http://sfdcsrini.blogspot.com/2014/09/what-is-action-support-salesforce.html


 
| ,