Monday, July 3, 2017

Adding custom styles to dependent picklist fields in Visualforce pages.

Hi,

In this article i am trying to give small example of applying custom styles for dependent pick-list. Usually for dependent pick-list custom styles will not apply, So you have to do it forcefully.In this i am using bootstrap to apply the style for input elements.


You have to add the below script items in the vf page with the id's
 

Ex: 

<!-- https://salesforcedevil.wordpress.com/2015/07/16/me/ -->
<apex:page standardController="Account" standardStylesheets="false"  showHeader="false">
<apex:includeScript value="https://code.jquery.com/jquery-1.9.1.js"/>
     <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"/>
     <apex:includeScript value="https://ajax.microsoft.com/ajax/jquery.validate/1.6/jquery.validate.min.js"/>   
    <apex:includeScript value="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"/>   
    <apex:stylesheet value="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
   
   <apex:form >
    
            
 <apex:inputfield value="{!Account.Country__c}" styleClass="form-control"  />
  <div id="dependentlst1">  
 <apex:inputfield value="{!account.State__c}" styleClass="form-control" />
 
 </div>
 <div id="dependentlst2">
 <apex:inputfield value="{!account.City__c}" styleClass="form-control"/>
 </div>
 <script>
// MutationObserver detect changes in the document
var MutationObserver = window.WebKitMutationObserver || window.MutationObserver || window.MozMutationObserver;
var observer = new MutationObserver(function(mutations) {
// If the form-control was removed from the list – re-assign it
if(!$('#dependentlst1 select').first().hasClass('form-control')){
$('#dependentlst1 select').first().addClass('form-control');
}
if(!$('#dependentlst2 select').first().hasClass('form-control')){
$('#dependentlst2 select').first().addClass('form-control');
}
});

var dependentlst1 = document.querySelector('#dependentlst1');
var dependentlst2 = document.querySelector('#dependentlst2');
observer.observe(dependentlst1, {
childList: true,
subtree: true,
attributes: true
});
observer.observe(dependentlst2, {
childList: true,
subtree: true,
attributes: true
});
</script> 
   </apex:form>

</apex:page>




Sources :

Thanks for giving the help .
https://salesforcedevil.wordpress.com/2015/07/16/me/

Using Test.loadData to import records with relationship from static resouces

Using Test.loadData to import records with relationship

Its good idea to store master data (aka Seed, Reference data) in static resource and load it in Test classes using “Test.loadData” method. It will save lots of code around creating test records and at the same time easy to maintain. We can store records of Custom settings, standard or custom object which can be used frequently in our code. One of the best functionality to make writing Test classes more easier, As we don’t need to concentrate on writing code for creating data, time can be used to assert actual functionality.

Simply, add the data in a .csv file, create a static resource for this file, and then call Test.loadData within your test method by passing it the sObject type token and the static resource name. For example, for Account records and a static resource name of myResource, make the following call:

Syn : 
List<sObject> ls = Test.loadData(Account.sObjectType, 'myResource');

The Test.loadData method returns a list of sObjects that correspond to each record inserted.

You must create the static resource prior to calling this method.The static resource is a comma-delimited file ending with a .csv extension.
The file contains field names and values for the test records. The first line of the file must contain the field names and subsequent
lines are the field values. To learn more about static resources,see “Defining Static Resources” in the Salesforce online help.

Once you create a static resource for your .csv file, the static resource will be
assigned a MIME type. Supported MIME types are: 
  • text/csv
  • application/vnd.ms-excel
  • application/octet-stream
  • text/plain
                                           Account CSV file for Static resource to use in Test.loadData method
    Contact CSV file for Static resource to use in Test.loadData method
    As we can see in above image, dummy Salesforce Id is provided in Account CSV and same ID is used in Contact CSV file in column “AccountId”. Below code snippet proves that it is working. @isTest public class StaticResourceTest { static testmethod void staticResourceLoad(){ //Load CSV file saved in static resource List<SObject> lstAcc = Test.loadData(Account.sObjectType,'AccountLoad_Test'); List<SObject> lstCon = Test.loadData(Contact.sObjectType,'ContactLoad_Test'); //Confirm that total number of accounts created are 5 System.assertEquals(lstAcc.size(), 5); for(Account a : [SELECT Id, Name, (SELECT FirstName,LastName FROM Contacts) FROM Account where Id IN :lstAcc]){ //confirm that every Account has associated child contact System.assertNotEquals(null, a.contacts); //confirm that every Account has exactly 2 contacts System.assertEquals(a.contacts.size(), 2); } } }
    Reference:

Visualforce basic JavaScript examples.?

Visualforce basic JavaScript examples.?


Example 1: 

In this example i am simply telling that how you can reference your VF variables in javascript.

Here in the first text once you entered the values and come's out from the text it will show alert message and displaying the text values in alert message.


<apex:page id="pg">
    <apex:form id="fm">
      <apex:inputtext id="Name" onchange="Show()"/>
      <script>
        function Show(){
          alert('test');
          var myname = document.getElementById('{!$Component.Name}').value;
          alert("my Name is==>"+ myname );
          
        }
        
        function demo(){
          alert('demo is calling');
          var myage = document.getElementById('pg:fm:pb2:age').value;
           alert('My age is==>'+myage );
        }
      </script>
      <br/>
      <br/>
      
      <apex:pageblock id="pb2">
      
      <apex:inputtext id="age" onchange="demo()"/>
      </apex:pageblock>
      
    </apex:form> 
 </apex:page>





Example 2:

In the below example i am populating first text field value into second text field. for that i am using simple javavascrpt functions.


<apex:page id="pg">
    <apex:form id="fm">
      <apex:inputtext id="Name" onchange="Show()"/>
      <script>
        function Show(){
          alert('test');
          var myname = document.getElementById('{!$Component.Name}').value;
          alert("my Name is==>"+ myname );
          
        }
        
        function demo(){
          alert('demo is calling');
          var myage = document.getElementById('pg:fm:pb2:age').value;
           alert('My age is==>'+myage );
        }
      </script>
      <br/>
      <br/>
      
      <apex:pageblock id="pb2">
      
      <apex:inputtext id="age" onchange="demo()"/>
      </apex:pageblock>
      
    </apex:form> 
 </apex:page>





That's it. these are the simple javascript basic examples.

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>



Jquery Data tables in Visualforce pages.

Jquery Data tables in Visualforce pages.


Examples 1:

Hi, In this post i am giving basic example of Jquery Data tables using in visualforce. It will give you the pagination ans search functionality in visualforce page.


Controller Class:

public class DataTableExampleController {
    public List<Contact> contactList {
        get {
            if (contactList == null) {
                contactList = [SELECT Account.Name, FirstName, LastName, Phone FROM Contact limit 10000];
            }
            return contactList;
        }
        set;
    }

}


Visualforce Page:

<apex:page Controller="DataTableExampleController" readOnly="true">
    <head>
        <apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js" / >
        <apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js" />
        <apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" />
        <script>
            j$ = jQuery.noConflict();
            j$(document).ready( function () {
                var contactTable = j$('[id$="contacttable"]').DataTable({
                    
                });
            });
        </script>
    </head>
    <body>
        <table id="contacttable" class="display">
            <thead>
                <tr>
                    <th>Account</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone</th>
                </tr>
            </thead>
            <tbody>
                <apex:repeat value="{!contactList}" var="contact">
                    <tr>
                        <td>{!contact.Account.Name}</td>
                        <td>{!contact.FirstName}</td>
                        <td>{!contact.LastName}</td>
                        <td>{!contact.Phone}</td>
                    </tr>
                </apex:repeat>
            </tbody>
        </table>
    </body>

</apex:page>






Example 2:



<apex:page >
    
 <head>

    <apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js" / >
    <apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js" />
    <apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" />

    <!-- I have a static resource called famfamfam which is the zip file from http://www.famfamfam.com/lab/icons/silk/famfamfam_silk_icons_v013.zip -->
    <style>
    td.details-control {
        background: url('{!URLFOR($Resource.famfamfam_silk_icons,'icons/add.png')}') no-repeat center center;
        cursor: pointer;
    }
    tr.shown td.details-control {
        background: url('{!URLFOR($Resource.famfamfam_silk_icons,'icons/delete.png')}') no-repeat center center;
    }
    </style>

    <!-- No need for a controller here! We can use Remote Objects. -->
    <apex:remoteObjects >
        <apex:remoteObjectModel name="Account" fields="Name,Phone" />
        <apex:remoteObjectModel name="Contact" fields="Name,LastName,Phone,AccountId" />
    </apex:remoteObjects>

    <script>
        j$ = jQuery.noConflict();
        j$(document).ready( function () {
            var acctTable = j$('[id$="accounttable"]').DataTable( {
                // Use the Remote Object retrieve method to get a list of accounts
                "ajax": function(data, callback, settings) {
                    var acct = new SObjectModel.Account();
                    acct.retrieve({orderby: [{Name: 'ASC'}], limit: 100}, function(err, records){
                        if(err) alert(err.message);
                        else {
                            callback({'data': records});
                        };
                    });
                },
                // Specify our columns. The first column is used to control expanding and collapsing to see contacts.
                "columns": [
                    { "class": 'details-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": '',
                        width: "8%" },
                    { "data": "_props.Name",
                        "defaultContent": '' },
                    { "data": "_props.Phone",
                        "defaultContent": '' }
                ],
                order: [[1, 'asc']],
            } );

            // This is used to watch for clicks to expand and collapse the rows.
            j$('#accounttable tbody').on('click', 'td.details-control', function () {
                var tr = j$(this).closest('tr');
                var row = acctTable.row( tr );
         
                if ( row.child.isShown() ) {
                    // This row is already open - close it
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    // Open this row
                    formatContacts(row.data(), function(childData) {
                        row.child( childData ).show();
                        tr.addClass('shown');
                    });
                }
            } );

            // Each time a row is clicked to expand, we need to query for a list of contacts for that account and 
            // build a table that will display as a child to the row
            function formatContacts(d, callback) {
                var contact = new SObjectModel.Contact();
                contact.retrieve({ where: {AccountId: {eq: d.get('Id')}}, orderby: [{LastName: 'ASC'}], limit: 100}, function(err, records){
                    if(err) alert(err.message);
                    else {
                        var table = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
                                        '<thead><tr><th>Name</th><th>Phone</th></tr></thead><tbody>';
                        records.forEach(function (record){
                            table = table + '<tr><td>' + record.get('Name') + '</td><td>' + record.get('Phone') + '</td></tr>';
                        });
                        table = table + '</tbody></table>';
                        callback(table);
                    };
                });
            }

        } );
    </script>
    </head>
    
    <body>
    <table id="accounttable" class="display" cellspacing="0" width="100%">
        <thead>
            <tr>
                <th/>
                <th>Name</th>
                <th>Phone</th>
            </tr>
        </thead>
     </table>
     </body>
</apex:page>