Showing posts with label Visualforce Pages. Show all posts
Showing posts with label Visualforce Pages. Show all posts

Saturday, April 2, 2016

What is Visualforce Remote Objects.?

What is Visualforce Remote Objects.?


One of the exciting feature of Spring14 release is introduction of “Visualforce Remote Objects”. You can say its actually replacement of JavaScript Remoting.

Why do we need “Visualforce Remote Objects” when we already have “JavaScript Remoting” ?
Well, here are few advantages of “Visualforce Remote Objects” :
    1.    No need to write Controllers, Everything can be done in Visualforce only.
   2.    As @RemoteAction annotated methods needs to be static so you had to take special precaution as it didn’t supported Viewstate. This hurdle is completely removed now.
   3.    No need to write Test Class now, as no Controller is involved.
   4.    Not counted against API call

How to start with this ?
At time of writing this article, This feature is under Pilot release. So, you have to contact Salesforce support to enable it in your Organization.
Visualforce code Sample :

<!-- This Demo will assume Querying Account Object -->
<apex:remoteObjects>
<apex:remoteObjectModel name="Account" jsShorthand="getActs" fields="Name,Id">
 <apex:remoteObjectField name="ClientType__c" jsShorthand="cType">
</apex:remoteObjectModel>
</apex:remoteObjects>



you can see in above code, few new Visualforce tags are introduced like “remoteObjectModel” and “remoteObjectField“.
jsShorthand attribute defines shortcut that can be used inside your JavaScript code. Now, we don’t have to write annoying object or field name ending with “__c” or namespace name. This will keep our code tidy.
Javascript code Sample :

//Create new Remote Object Reference
var src = new SObjectModel.getActs();
 
//Use Remote Object to query 5 records
src.retrieve({
                        limit : 10,
                        where : {
                             cType :{
                                          eq : 'Banking'
                                                                            }
                                        }
                               } ,
                          function(err,records){
                               if(err == null)
                                  {
                                      //Process returned "records" to display in Visualforce code.
                                  }
} );


In above code, we are calling retrieve() method of Javascript object SObjectModel. Once you get records, you can process it in your javascript. Other than retrieve() , you can perform all CRUD operations on object.
You can see below articles also on same topic.


Let test this features quickly on our own, by designing a visualforce page.  Here I have designed a page that pulls up ten accounts from Salesforce solely by using JavaScript Remote Objects (see picture below)

Just copy-paste the code in your org to test this by yourself. I am querying Accounts (standard object) and using bootstrap CDN (check what is bootstrap and cdn go to bootstrap site to style the page. At the moment, I wrote retrieve() operation that pulls ten records, soon ill update the code will perform all sort of DML operation mentioned in the documentation.


Test on Salesforce 1 :  this works like charm on Salesforce 1







<apex:page sidebar="false" showHeader="false" standardStylesheets="false">
   <apex:includeScript value="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"/>
   <link href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" rel="stylesheet" media="screen"/>
   <style>
      .wrapper
      {
      text-align : center;
      }
   </style>
   <!-- lets query Salesforce Contact using remoting objects -->
   <!--Lets add up Amount field on Contact objects here using shorthand amt-->
   <apex:remoteObjects >
      <!--Name the field you like to query-->
      <apex:remoteObjectModel name="Account" jsShorthand="acc" fields="Id,Name,BillingState, Phone"/>
   </apex:remoteObjects>
   <!-- now address you field with shorthand -->
   <script>
      function clearList()
      {
          if(!$('#cList').empty())
          {
              //if non-empty then clear list before every call
              $('#cList').empty();
          }
      }
     
      var DML = function(){
          //clear old list beforehand
          clearList();
          //Instantiate a reference
          var data = new SObjectModel.acc();
          //process the data received in return
          data.retrieve({ limit: 10 } ,function(err, records){
              //if failure
              if(err) alert(err.message);
              else {
                  populate(records);      
              }
          });
         
          //Method to Pouplate Records
          function populate(records)
          {
              var ul = document.getElementById("cList");
              records.forEach(function(record) {
                  // Build the text for a warehouse line item
                  var toAdd = record.get("Name");
                  // Add the line item to the warehouses list
                  var rule = document.createElement("br");
                  var li = document.createElement("li");
                  li.appendChild(document.createTextNode(toAdd));
                  ul.appendChild(li);
                  ul.appendChild(rule);
              });
          }
      }
     
   </script>
   <div class="jumbotron">
      <h1>Retrieve Contacts via Remote Objects</h1>
      <p>via Remote Objects</p>
      <a href="#" class="list-group-item active">
         <h4 class="list-group-item-heading">What is Remote Object?</h4>
         <p class="list-group-item-text">Visualforce Remote Objects are proxy objects that allow basic DML operations on sObjects directly from JavaScript. Remote Objects take some of the complexity out of JavaScript remoting, by reducing the need for @RemoteAction methods in an Apex controller or extension. Like JavaScript remoting, <br/> Remote Objects calls don’t count towards API request limits.</p>
      </a>
      <br/>
      <div class="wrapper">
         <p> <button  class="btn btn-success btn-lg" onclick="DML()"> <span class="glyphicon glyphicon-star"></span>Pull
            Accounts</button>
         </p>
      </div>
   </div>
   <a href="#" class="list-group-item active">
   <span class="glyphicon glyphicon-list"></span> Accounts:
   </a>
   <div class="wrapper">
      <ul class="list-inline" id="cList">
      </ul>
   </div>
</apex:page>




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........

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


 
| ,