Thursday, 6 December 2012

Initiate approval process via VF button

Initiate approval process via VF button

In VF
<apex:commandButton value="Submit for Approval" action="{!sumbitForApproval}">

In class


public PageReference sumbitForApproval(){
      PageReference submitPageRef;
      if(sportDeal.Id!=null)
      {
      sportDeal.Submit_for_Approval__c=true;
      sportDeal.Is_Approved__c = false;
      sportDeal.Is_Rejected__c=false;
      upsert sportDeal;
      }
     
     
     // submitPageRef = save();
               try{
                   Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
                   req.setComments('Submitting request for approval');
                   req.setObjectId(sportDeal.Id);
                   Approval.ProcessResult result = Approval.process(req);
              }catch (Exception ex){
                  System.debug('Exception caught');
              }
         //return submitPageRef;
         return null;
  }

Tuesday, 4 December 2012

Hierarchy in VisualForce


Hierarchy in VisualForce

This is an example of how to build a hierarchy Lists in VF page with select checkboxes. It will have a checkbox at parent level with which you can select all the child automatically. It has a neat link with which you can show or hide children under a parent row. It uses jquery libraries for achieving this. It has a list of accounts with each accounts displaying all its contacts in a hierarchy view.

Apex Class

public class accconhierarchy {
    Private list<account> acc;
    
    public List<accountWrap> accountList { get; set; }
    public accconhierarchy (){
        List<contactWrap> cw;
        accountList = new List<accountWrap>();
        acc = [select id,name,industry,billingcountry,createdbyid,(select id,name,email,phone from contacts) from account limit 20];
        for(account a:acc){
            cw = new list<contactWrap>();
            For(contact co : a.contacts){
               cw.add(new contactWrap(co));
            }
            accountList.add(new accountWrap(a,false,cw));
        }
    }
    
    public class accountWrap{
        public account oAccount{get;set;}
        public boolean isSelected{get;set;}
        public List<contactWrap> contactset{get;set;}
        public accountWrap(account a,boolean b, List<contactWrap> c){
            oAccount=a;
            isSelected=b;
            contactset =c;            
        }
    }
    
    public class contactWrap{
        public contact oContact{get;set;}
        public boolean isSelected{get;set;}        
        public contactWrap(contact a){
            oContact=a;
            isSelected=false;                       
        }
    }
    
}


Visualforce Page 

<apex:page controller="accconhierarchy">
  <apex:form >
      <apex:pageBlock >
      <style type="text/css">
        .showContacts {
            background: transparent url('/img/alohaSkin/twisty_sprite.png') 0 0 no-repeat;
        }
        .hideContacts {
            background: transparent url('/img/alohaSkin/twisty_sprite.png') 0 -11px no-repeat;
        }
    </style>
                  <apex:outputPanel layout="none"
                        rendered="{!accountList.size!=0}">
                        <table id="tableAccount" class="list" border="0" cellpadding="0" cellspacing="0">
                            <thead>
                                <tr class="headerRow">
                                    <th class="actionColumn">Action</th>
                                    <th>Account Name</th>
                                    <th>Industry</th>
                                    <th>Billing Country</th>
                                    <th>Createdby</th>
                                </tr>
                            </thead>
                            <tbody>
                            <apex:repeat id="repeatAccount"
                                value="{!accountList}"
                                var="item">
                                <apex:variable var="acc" value="{!item.oAccount}" />   
                                <tr id="{!$Component.repeatAccount}:account" class="dataRow">
                                    <td class="actionColumn">
                                        <apex:inputCheckbox id="selectAccountRow"
                                            value="{!item.IsSelected}"
                                            onclick="javascript:toggleSelectAll(this, '{!$Component.repeatAccount}');"/>
                                    </td>
                                    <td class="dataCell">
                                        <apex:outputLink id="linkShowHide" value="javascript:toggleContactRow('{!$Component.repeatAccount}')">
                                            <img id="{!$Component.repeatAccount}:Img" src="/s.gif" class="showContacts" border="0" height="11px" width="11px" style="padding-right: 4px;"/>
                                            <apex:outputField value="{!acc.Name}" />
                                        </apex:outputLink>
                                    </td>
                                    <td class="dataCell"><apex:outputField value="{!acc.Industry}" /></td>
                                    <td class="dataCell"><apex:outputField value="{!acc.billingcountry}" /></td>
                                    <td class="dataCell"><apex:outputField value="{!acc.CreatedById}" /></td>
                                </tr>

                                <tr id="{!$Component.repeatAccount}:Contact" class="dataRow" style="display:none;">
                                    <td colspan="100" style="padding:10px; padding-left: 45px;">
                                        <h3>Contacts</h3>
                                        <br/>                                        
                                        <apex:outputPanel layout="none">                                            
                                            <table id="tableAccountContacts" class="list" border="0" cellpadding="0" cellspacing="0">
                                                <thead>
                                                    <tr class="headerRow">
                                                        <th class="actionColumn">Action</th>
                                                        <th>Name</th>
                                                        <th>Email</th>
                                                        <th>Phone</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                <apex:repeat id="repeatAccountContacts"
                                                    value="{!item.contactSet}"
                                                    var="subitem">
                                                    <apex:variable value="{!subitem.oContact}" var="con" />
                                                    <tr class="dataRow">
                                                        <td class="actionColumn"><apex:inputCheckbox id="selectContactRow" styleclass="ContactCheckbox" value="{!subitem.IsSelected}"/></td>
                                                        <td class="dataCell"><apex:outputField value="{!con.Name}" /></td>
                                                        <td class="dataCell"><apex:outputField value="{!con.email}"/></td>
                                                        <td class="dataCell"><apex:outputField value="{!con.phone}" /></td>                                                        
                                                    </tr>
                                                </apex:repeat>
                                                </tbody>
                                            </table>
                                        </apex:outputPanel>
                                    </td>
                                </tr>
                            </apex:repeat>
                            </tbody>
                        </table>
                    </apex:outputPanel>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
 <script>
        jQuery.noConflict();
        function toggleContactRow(rowId) {
            try {
                var AccountImg = jQuery(document.getElementById(rowId + ":Img"));
                var ContactsRow = jQuery(document.getElementById(rowId + ":Contact"));
                if (AccountImg.hasClass("hideContacts")) {
                    AccountImg.attr("class", "showContacts");
                    ContactsRow.hide();
                }
                else {
                    AccountImg.attr("class", "hideContacts");
                    ContactsRow.show();
                }
            }
            catch (e) { alert(e); }
        }  

        function toggleSelectAll(elCheckbox, rowId) {
            try {
                var SelectAll = jQuery(elCheckbox);
                var ContactsRow = jQuery(document.getElementById(rowId + ":Contact"));
                ContactsRow.find(".ContactCheckbox").each(function() {
                    jQuery(this).prop("checked", SelectAll.is(":checked"));
                });
            }
            catch (e) { alert(e); }
        }

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

JS function toggleContactRow is used to show or hide contacts and toggleSelectAll is for header level checkbox at the parent Level.

Wednesday, 14 November 2012

Loading Test Data from Static Resources


Loading Test Data from Static Resources

Using the new Test.loadData method, you can populate data in your test methods without having to write many lines of code. 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:
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.

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


Test.loadData Example

The following are steps for creating a sample .csv file and a static resource, and calling Test.loadData to insert the test records.
1.       Create a .csv file that has the data for the test records. This is a sample .csv file with three account records. You can use this sample content to create your .csv file.

Name,Website,Phone,BillingStreet,BillingCity,BillingState,BillingPostalCode,BillingCountry
sForceTest1,http://www.sforcetest1.com,(415) 901-7000,The Landmark @ One Market,San
Francisco,CA,94105,US

sForceTest2,http://www.sforcetest2.com,(415) 901-7000,The Landmark @ One Market Suite
300,San Francisco,CA,94105,US
sForceTest3,http://www.sforcetest3.com,(415) 901-7000,1 Market St,San Francisco,CA,94105,US

2.       Create a static resource for the .csv file:
a.       Click Your Name > Setup > Develop > Static Resources, and then New Static Resource.
b.      Name your static resource testAccounts.
c.       Choose the file you just created.
d.      Click Save.
3.       Call Test.loadData in a test method to populate the test accounts.

@isTest
private class DataUtil {
                static testmethod void testLoadData() {
// Load the test accounts from the static resource
List<sObject> ls = Test.loadData(Account.sObjectType, 'testAccounts');
// Verify that all 3 test accounts were created
System.assert(ls.size() == 3);

// Get first test account
Account a1 = (Account)ls[0];
String acctName = a1.Name;
System.debug(acctName);

// perform some testing using the test records
         }
}

Tuesday, 13 November 2012

What's the date format for the Apex Data Loader?


What's the date format for the Apex Data Loader?

The Apex data loader allows you SOQL statements to pull data - therefore you have to use date formats that SOQL statements will use.

here's a quick example, but there are so many options, you should really check out the guide.  I included a link under my example:

FormatFormat SyntaxExample
Date onlyYYYY-MM-DD1999-01-01
Date, time, and time zone offset
  • YYYY-MM-DDThh:mm:ss+hh:mm
  • YYYY-MM-DDThh:mm:ss-hh:mm
  • YYYY-MM-DDThh:mm:ssZ
  • 1999-01-01T23:01:01+01:00
  • 1999-01-01T23:01:01-08:00
  • 1999-01-01T23:01:01Z

Why to use Database.Stateful()?

Database Stateful is interface. It is used in batch classes to maintain the state of the class across transactions i.e. if you want to use ...