Wednesday, 21 September 2016

Adding or Removing Rows dynamically using wrapper class

Visual force Page Code

<apex:page controller="AddLineItemsController">
     <apex:form >
         <apex:pageBlock title="Add Members" id="out">
             <table>
                 <th>
                     Contact Last Name
                 </th>
                 <th>
                     Phone
                 </th>
                 <apex:repeat value="{!lstWI}" var="w">
                     <tr>
                         <td>
                             <apex:inputfield value="{!w.objC.lastName}" />
                         </td>
                         <td>
                             <apex:inputfield value="{!w.objC.Phone}" />
                         </td>
                         <td>
                             <apex:commandLink action="{!doAdd}" immediate="true" rerender="out">
                                 <apex:image value="{!$Resource.addIcon}" style="height:20px;width:20px;"/>
                             </apex:commandLink>
                         </td>
                         <td>
                             <apex:commandLink action="{!doRemove}" immediate="true" reRender="out">
                                 <apex:image value="{!$Resource.removeIcon}" rendered="{!IF(w.index ==0,false,true)}" style="height:20px;width:20px;"/>
                                  <apex:param name="toDelIdent" value="{!w.index}" assignTo="{!delIndex}"/>
                             </apex:commandLink>
                         </td>
                     </tr>
                 </apex:repeat>
             </table>
         </apex:pageBlock>
         <apex:commandButton value="Save" action="{!doSave}" />
     </apex:form>
</apex:page>



Class Code


public class AddLineItemsController {

    public static Integer delIndex {get; set;}
    public PageReference doRemove() {
        Integer pos = -1;
        for(Integer i=0;i<lstWI.size();i++){
            if(lstWI[i].index == delIndex){
                pos = i;
            }
        }
        if(-1 != pos){
            lstWI.remove(pos);
        }
        return null;
    }
 
    public List<Contact> lstC;
    public pagereference doSave(){
            lstC = new List<Contact>();
            for(wrapInner objWI : lstWI){
                objWI.objC.AccountId = apexPages.currentpage().getparameters().get('id');
                lstC.add(objWI.objC);
            }
            if(lstC.size()>0){
                Insert lstC;
            }
            return (new pagereference('/'+apexPages.currentpage().getparameters().get('id')).setredirect(true));
    }


    public PageReference doAdd() {
        objWI = new wrapInner();
        objWI.objC = new contact();
        objWI.index = ++iCount;
        lstWI.add(objWI);
        return null;
    }

    public Integer iCount = 0;
    public AddLineItemsController(){
        lstWI = new List<wrapInner>();
        objWI = new wrapInner();
        objWI.objC = new contact();
        objWI.index = iCount;
        lstWI.add(objWI);
    }
 
    public wrapInner objWI{get;set;}
    public List<wrapInner> lstWI{get;set;}
 
    public class wrapInner{
        public Integer index{get;set;}
        public Contact objC{get;set;}  
    }
}


How it works
1. Create a button on Account Detail page.


2. When Click on "Add Contacts", opens a visual force page like below. and can add / remove the rows as required.



Thank you!!!

Monday, 11 May 2015

Writing Code coverage to Webservice Classes:-

Steps in Service Org:-

1. Write a webservice class.

global class AccountService{
    webservice static void AccountInsert(String accName,String ph){
        Account objA = new Account();
        objA.Name = accName;
        objA.Phone = ph;
        Insert objA;
    }
}

2. Generate a WSDL

save the file with .wsdl extension (ex: AccountService.wsdl)




Steps in Client Org

1. Generate an apex class for the above WSDL.

Below is the generated apex class:

//Generated by wsdl2apex

public class soapSforceComSchemasClassAccountser {
    public class LogInfo {
        public String category;
        public String level;
        private String[] category_type_info = new String[]{'category','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] level_type_info = new String[]{'level','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'category','level'};
    }
    public class AllowFieldTruncationHeader_element {
        public Boolean allowFieldTruncation;
        private String[] allowFieldTruncation_type_info = new String[]{'allowFieldTruncation','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'allowFieldTruncation'};
    }
    public class DebuggingHeader_element {
        public soapSforceComSchemasClassAccountser.LogInfo[] categories;
        public String debugLevel;
        private String[] categories_type_info = new String[]{'categories','http://soap.sforce.com/schemas/class/AccountService',null,'0','-1','false'};
        private String[] debugLevel_type_info = new String[]{'debugLevel','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'categories','debugLevel'};
    }
    public class CallOptions_element {
        public String client;
        private String[] client_type_info = new String[]{'client','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'client'};
    }
    public class AccountInsert_element {
        public String accName;
        public String ph;
        private String[] accName_type_info = new String[]{'accName','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','true'};
        private String[] ph_type_info = new String[]{'ph','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','true'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'accName','ph'};
    }
    public class location {
        public Double latitude;
        public Double longitude;
        private String[] latitude_type_info = new String[]{'latitude','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] longitude_type_info = new String[]{'longitude','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'latitude','longitude'};
    }
    public class address {
        public String city;
        public String country;
        public String countryCode;
        public String postalCode;
        public String state;
        public String stateCode;
        public String street;
        private String[] city_type_info = new String[]{'city','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] country_type_info = new String[]{'country','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] countryCode_type_info = new String[]{'countryCode','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] postalCode_type_info = new String[]{'postalCode','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] state_type_info = new String[]{'state','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] stateCode_type_info = new String[]{'stateCode','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] street_type_info = new String[]{'street','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'city','country','countryCode','postalCode','state','stateCode','street'};
    }
    public class SessionHeader_element {
        public String sessionId;
        private String[] sessionId_type_info = new String[]{'sessionId','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'sessionId'};
    }
    public class AccountInsertResponse_element {
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{};
    }
    public class DebuggingInfo_element {
        public String debugLog;
        private String[] debugLog_type_info = new String[]{'debugLog','http://soap.sforce.com/schemas/class/AccountService',null,'1','1','false'};
        private String[] apex_schema_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService','true','false'};
        private String[] field_order_type_info = new String[]{'debugLog'};
    }
    public class AccountService {
        public String endpoint_x = 'https://ap2.salesforce.com/services/Soap/class/AccountService';
        public Map<String,String> inputHttpHeaders_x;
        public Map<String,String> outputHttpHeaders_x;
        public String clientCertName_x;
        public String clientCert_x;
        public String clientCertPasswd_x;
        public Integer timeout_x;
        public soapSforceComSchemasClassAccountser.DebuggingInfo_element DebuggingInfo;
        public soapSforceComSchemasClassAccountser.AllowFieldTruncationHeader_element AllowFieldTruncationHeader;
        public soapSforceComSchemasClassAccountser.DebuggingHeader_element DebuggingHeader;
        public soapSforceComSchemasClassAccountser.CallOptions_element CallOptions;
        public soapSforceComSchemasClassAccountser.SessionHeader_element SessionHeader;
        private String DebuggingInfo_hns = 'DebuggingInfo=http://soap.sforce.com/schemas/class/AccountService';
        private String AllowFieldTruncationHeader_hns = 'AllowFieldTruncationHeader=http://soap.sforce.com/schemas/class/AccountService';
        private String DebuggingHeader_hns = 'DebuggingHeader=http://soap.sforce.com/schemas/class/AccountService';
        private String CallOptions_hns = 'CallOptions=http://soap.sforce.com/schemas/class/AccountService';
        private String SessionHeader_hns = 'SessionHeader=http://soap.sforce.com/schemas/class/AccountService';
        private String[] ns_map_type_info = new String[]{'http://soap.sforce.com/schemas/class/AccountService', 'soapSforceComSchemasClassAccountser'};
        public void AccountInsert(String accName,String ph) {
            soapSforceComSchemasClassAccountser.AccountInsert_element request_x = new soapSforceComSchemasClassAccountser.AccountInsert_element();
            request_x.accName = accName;
            request_x.ph = ph;
            soapSforceComSchemasClassAccountser.AccountInsertResponse_element response_x;
            Map<String, soapSforceComSchemasClassAccountser.AccountInsertResponse_element> response_map_x = new Map<String, soapSforceComSchemasClassAccountser.AccountInsertResponse_element>();
            response_map_x.put('response_x', response_x);
            WebServiceCallout.invoke(
              this,
              request_x,
              response_map_x,
              new String[]{endpoint_x,
              '',
              'http://soap.sforce.com/schemas/class/AccountService',
              'AccountInsert',
              'http://soap.sforce.com/schemas/class/AccountService',
              'AccountInsertResponse',
              'soapSforceComSchemasClassAccountser.AccountInsertResponse_element'}
            );
            response_x = response_map_x.get('response_x');
        }
    }
}


Write a WebServiceMock Class


global with sharing class MockClass implements WebServiceMock { 
   global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
        
        soapSforceComSchemasClassAccountser.AccountInsertResponse_element objAC = new  soapSforceComSchemasClassAccountser.AccountInsertResponse_element();
        response.put('response_x',objAC); 
   } 
}


Test Class:

@isTest
private class soapSforceComSchemasClassAccountserTest {

    static testMethod void myUnitTest() {
        test.startTest();
            soapSforceComSchemasClassAccountser.LogInfo  objS1 = new soapSforceComSchemasClassAccountser.LogInfo();
            soapSforceComSchemasClassAccountser.AllowFieldTruncationHeader_element  objS2  = new soapSforceComSchemasClassAccountser.AllowFieldTruncationHeader_element();
            soapSforceComSchemasClassAccountser.DebuggingHeader_element objS3 = new soapSforceComSchemasClassAccountser.DebuggingHeader_element();
            soapSforceComSchemasClassAccountser.CallOptions_element objS4 = new soapSforceComSchemasClassAccountser.CallOptions_element();
            soapSforceComSchemasClassAccountser.AccountInsert_element  objS5 = new soapSforceComSchemasClassAccountser.AccountInsert_element();
            soapSforceComSchemasClassAccountser.location objS6 = new soapSforceComSchemasClassAccountser.location();
            soapSforceComSchemasClassAccountser.address objS7 = new soapSforceComSchemasClassAccountser.address();
            soapSforceComSchemasClassAccountser.SessionHeader_element  objS8 = new soapSforceComSchemasClassAccountser.SessionHeader_element();
            soapSforceComSchemasClassAccountser.AccountInsertResponse_element objS9 = new soapSforceComSchemasClassAccountser.AccountInsertResponse_element();
            soapSforceComSchemasClassAccountser.DebuggingInfo_element objS10 = new soapSforceComSchemasClassAccountser.DebuggingInfo_element();
           
            Test.setMock(WebServiceMock.class, new MockClass());
            soapSforceComSchemasClassAccountser.AccountService  objS11 = new soapSforceComSchemasClassAccountser.AccountService ();
            objS11.AccountInsert('test', '1234567890');
           
        test.stopTest();
    }
}

click on "Run Test" and check the code coverage of "soapSforceComSchemasClassAccountser".





Monday, 30 March 2015

XML Parsing in Salesforce using DOM

Hi,

Below is a sample XML String and code to parse the same.

Sample XML: 

1. Just create a new text file and paste the below xml string in that.
2. Upload the file to document object with name "xml".



<Company>
<Department>
<Employee>
<Name>Venkat V</Name>
<City>London - XYZ</City>
<Country>UK</Country>
</Employee>
<Employee>
<Name>Kalyan</Name>
<City>Hyderabad</City>
<Country>IND</Country>
</Employee>
<Employee>
<Name>Teja</Name>
<City>Chennai</City>
<Country>India</Country>
</Employee>
</Department>
</Company>


Apex Code:


public with sharing class xmlParserClassNew {
    public String resp{get;set;}
    public PageReference doParse() {
        Document objD = [select id,name,body from Document where name ='xml'];
        blob response = objD.body;
        String strResponse = response.toString();
        System.debug('---strResponse--->'+strResponse);
        DOM.Document objDoc = new DOM.Document();
        objDOC.load(strResponse);
     
        List<Employee__c> empData = new List<Employee__c>();
     
        for(DOM.XMLNode dept : objDOC.getRootElement().getChildElements()){
            for(DOM.XMLNode emps : dept.getChildElements()){
                Employee__c objE = new Employee__c();
                for(DOM.XMLNode child : emps.getChildElements()){
                 
                    if(child.getName() == 'Name'){
                        objE.Name = child.getText();
                    }
                    if(child.getName() == 'City'){
                        objE.city__c = child.getText();
                    }
                    if(child.getName() == 'Country'){
                        objE.Country__c = child.getText();
                    }
                }
                empData.add(objE);

            }
        }
if(empData.size()>0)
Insert empData;
     
        return null;
    }
    public xmlParserClassNew(){
    }
}



Tuesday, 18 February 2014

JSON Parser in Salesforce

We hear the term JSON when we are dealing with Integration Projects. Now a days in most of the Integration projects we are using JSON requests or responses.

So it is one of the major area to learn, to become good with Integrations in salesforce.

Salesforce introduces many JSONParser methods to dealing with JSON string in our applications.

Below are few methods mostly used.

JSON.serialize()
Method converts the list of records / string of data to JSON format.

Ex:

List<Account> lstA = [select id,name,phone from Account limit 5];
String strReq = JSON.serialize(lstA);

JSON.deserialize()
Method converts the JSON string to normal format (either stirng / list)

Ex:
List<Account> accountsDeserialized = (List<Account>) JSON.deserialize(strReq, List<Account>.class);

Some times when JSON response are having multi object information we have to use wrapper class to collect the list of data.

Below Sample helps you to understand the use of wrapper class when dealing with JSON.

public with sharing class JSONSerializeCls {
  public List<Account> lstA{get;set;}
  public List<wrapAccCls> lstWA{get;set;}
  public wrapAccCls objWA{get;set;}

         public void JSONserialize(){
            lstA = new List<Account>();
            lstA = [select id,name,phone from Account limit 5];
            String strReq = JSON.serialize(lstA);   // (Or) Response from any callout which is in JSON format
            lstWA = new List<wrapAccCls>();
            objWA = new wrapAccCls();
        
            lstWA = (List<wrapAccCls>)JSON.deserialize(strReq, List<wrapAccCls>.class);
        
            // Convert Wrapper list to Sobject LIst.....

            List<Account> lstA = new List<Account>();
            for(wrapAccCls objWA : lstWA){
                Account objA = new Account();
                objA.Name = objWA.Name;
                 objA.Phone = objWA.Phone;
                 lstA.add(objA);
         }

           if(lstA.size()> 0){
              Insert lstA;
           }
        }
      
        public class wrapAccCls{
           public String ID{get;set;}
           public String Name{get;set;}
           public String phone{get;set;}
   }
}