Tuesday, June 14, 2016

Writing test classes for external object in salesforce

Main class example


public without sharing class MyOrderHistoryController {
    @TestVisible private static list<SoldToSet__x> mockedcustlist = new List<SoldToSet__x>();

    @AuraEnabled
    //filter values for the report based on logged in customer
    public static list<SoldSet__x> getCustomers( string soldtono){

        list<SoldSet__x> custlist=new list<SoldSet__x>();
        //query Sold To account details
        if(!Test.isRunningTest()){
                for(SoldSet__x oh: [SELECT Flag__c,City__c,Name__c,SoldToNr__c FROM SoldSet__x                                                  WHERE SoldToNr__c IN:soldtono]){
                                custlist.add(oh);
                }
       }else{
                custlist.addAll(mockedcustlist);
        }
        return custlist;

    }








Test class  

@isTest
public without sharing class MyOrderHistoryControllertest {
     static testMethod void myTest() {     
                SoldSet__x mockedCust1 = new SoldSet__x(
                  SoldToNr__c='600459',
                  Name__c='abcLtd',
                  City__c='test1',
                  Flag__c='YES'
                );

                SoldSet__x mockedCust2 = new SoldSet__x(
                  SoldToNr__c='600459',
                  Name__c='xyzLtd',
                  City__c='test2',
                  Flag__c='NO'
                );

                MyOrderHistoryController.mockedcustlist.add(mockedCust1);
                MyOrderHistoryController.mockedcustlist.add(mockedCust2);

                //run as portal user
                system.runas(u){
                         list<SoldSet__x> accs=new list<SoldSet__x>();
                         accs = MyOrderHistoryController.getCustomers();
                         System.assert(accs != null);
                }
        }
}              

Monday, January 28, 2013

Display multi-select picklist as multi-select checkboxes

Use Case :- To improve user experience, we can implement multi-select picklist as multi-select checkboxes on a page.


Steps to accomplish this :-
1.     Create a Page and a extensions for the page. Can't use custom controller assuming that we need to override new button of the custom object.
2.     Extensions Code as below:-

public class newcustomobjectextension {
    public CustomObject pr{get; set;}
     //initialize
    public newproductrequestcontroller(ApexPages.StandardController controller){
      pr=new CustomObject();
    }
   
    //get the multi-select pick list values
    public List<SelectOption> MPOptions {
     get {
       List<SelectOption> options = new List<SelectOption>();
       for( Schema.PicklistEntry f : CustomObject.CustomMultiSelectPicklist.getDescribe().getPicklistValues()) {
         options.add(new SelectOption(f.getValue(), f.getLabel()));
        } 
       return options;
     }  
     set;
    }
    
    //get and set the multi-select pick list as checkboxes
    public String[] MPItems { 
     get {
        String[] selected = new List<String>();
        List<SelectOption> sos = this.MPOptions;
        for(SelectOption s : sos) {
        if (this.pr.CustomMultiSelectPicklist!=null && this.pr.CustomMultiSelectPicklist.contains(s.getValue()))
           selected.add(s.getValue());
        }
        return selected;
     }public set {
        String selectedConcat = '';
        for(String s : value) {
         if (selectedConcat == '') 
           selectedConcat += s;
         else selectedConcat += ';' + s;
        }
        pr.CustomMultiSelectPicklist= selectedConcat;
     }
   } 
   
   //create record
   public PageReference savepr() {
        insert pr;
        return (new PageReference('/'+pr.id));
   }
}

3.Page code as below:-

<apex:page standardController="CustomObject" extensions="newcustomobjectextension" id="prpage">
 <apex:form id="prform">
 <apex:pageBlock id="prblock">
   <apex:pageBlockSection title="Purpose of Request" id="prmain"><br/><br/><br/>
    <font color="red"><b><i>How will this software be used (select the most relevant)?</i></b></font><br/>
    <center>
     <apex:selectCheckboxes value="{!MPItems}" layout="pageDirection" required="true" id="prodreq">
       <apex:selectOptions value="{!MPOptions}"/>
     </apex:selectCheckboxes>
    </center>
   </apex:pageBlockSection>
   <apex:pageblockButtons location="bottom">
    <apex:commandButton action="{!savepr}" value="Create Request"/>
    <apex:commandButton action="{!cancel}" value="Cancel"/>
   </apex:pageblockButtons>
  </apex:pageBlock>
 </apex:form>  
</apex:page> 

4.Now override the new button of the custom object with this page.













Conditional iFrames


Use Case :- Let's say we need to show different visualforce pages as iframes based on the URL. For example on sidebar, it shows account specific details on account page layout, for opportunity, it shows opportunity details

Steps to accomplish this :-
1.     Create a html area type component on home page. Name it like welcome page.
2.     Keep the component position as Narrow Left column and in the body click on show html.
3.     Put the below content in the body and save the component. 


<iframe id="pwelcomesidebar"></iframe>
<script type="text/javascript">
 if (document.getElementById) { 
   var URL = window.location.href; 
   if (URL.indexOf('/001')>=0) {  
    document.getElementById('pwelcomesidebar').src = '/apex/welcomepage_account?core.apexpages.devmode.url=1'; 
   } else {  
    document.getElementById('pwelcomesidebar').src = '/apex/welcomepage_opportunity?core.apexpages.devmode.url=1'; 
   }
 }
</script>


4. Now add this component to home page layouts.

Wednesday, January 2, 2013

Hide/Show button based on field value on Page Layout


Use Case :- Let's say we need to hide the "Submit For Approval" button on Account Page Layout when the field "Status" has "Approved" value.

Steps to acomplish this :-
1.     Create a html area type component on home page. Name it like admin toolbox.
2.     Keep the component position as Narrow Left column and in the body click on show html.
3.     Put the below Javascript in the body and save the component. To find the name of button, you can use firebug on firefox or console on any other browser. In this example it is "submit".


<!--------Wait for the loading of the page---------> 
<script type="text/javascript">   
  function addLoadEvent(func) {    
    var oldonload = window.onload;    
if (typeof window.onload != 'function') {    
    window.onload = func;    
    }else {     
    window.onload = function() {      
 if (oldonload) {       
   oldonload();      
 }      func();     
}    
}   
  }   
  addLoadEvent(function() { 
    findandremovebuttons();
    }
  ); 
</script> 
<!--------/Wait for the loading of the page--------->

<!--------Button Removal---------> 
<script type="text/javascript">   
  
  function findandremovebuttons(){   
    var currentURL = window.location.href; 
      
if(currentURL.indexOf('/001') != -1 ) {  
 var tds = document.getElementsByTagName("td");
 var trColLabels = document.querySelectorAll('.labelCol');
 for(var i=0; i<trColLabels.length; i++){
var singleCol = trColLabels[i].innerHTML;
if(singleCol == 'Status') {
   var myTd = trColLabels[i];
for(var i = 0; i < tds.length;i++){
  if(tds[i] == myTd){
var next = tds[i + 1];
if(next.getElementsByTagName("div").length > 0){
var innerDiv = next.getElementsByTagName("div")[0];
if(innerDiv.innerHTML == 'Approved'){
  if (document.getElementsByName("submit")[0] != null)            
document.getElementsByName("submit")[0].style.display = 'none';        
  if (document.getElementsByName("submit")[1] != null)            
document.getElementsByName("submit")[1].style.display = 'none';
}
}
  }
}
}
 }
}
  }  
  
</script> 
<!--------/Button Removal--------->





4.     Now make this component available on all home page layouts to get this going.

Sunday, December 23, 2012

Hiding a standard button on page layout


In this below example, let's say we want to hide the "save & new" button on case edit page layout.

Steps to accomplish this :-

  1. Create a html area type component on home page. Name it like admin toolbox.
  2. Keep the component position as Narrow Left column and in the body click on show html.
  3. Put the below Javascript in the body and save the component.To find the name of button, you can use firebug on firefox or console on any other browser.In this example it is "save_new".


< !--------Wait for the loading of the page--------->
<script type = "text/javascript" > 
  function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
 }
 addLoadEvent(function() {checkCasePage();}); 
</script> 
<!--------/Wait for the loading of the page---------> 

<!--------Case Button hide--------->
 <script type = "text/javascript" > 
  function checkCasePage() {
    var currentURL = window.location.href;
    
    if (currentURL.indexOf('/500') != -1) {
        if (document.getElementsByName("save_new")[0] != null)
            document.getElementsByName("save_new")[0].style.display = 'none';
        if (document.getElementsByName("save_new")[1] != null)
            document.getElementsByName("save_new")[1].style.display = 'none';
    }
 }
</script> 
<!--------/Case Button hide--------->

Now we can add this component to all our home page layouts and see the magic !

chatter community landing page


The challenge is to have our custom login page for customers/partner on chatter community to maintain our company branding.

Steps to accomplish this:-


  1. We should have force.com site enabled for chatter community. 
  2. Then we need to do few changes in "communitieslandingcontroller" method as below to get our custom visualforce page as default landing page.Here "communitieslandingcontroller" is added to our org when we enable community. "Welcome" is our custom visualforce page with login form to community.We need to enable "welcome" page for the site as well.
         public PageReference forwardToStartPage() { 
                 Pagereference pa=new Pagereference('/welcome');
                 if(UserInfo.getUserType()=='Guest'){
                    return pa; 
                 }else{ 
                    return Network.communitiesLanding(); 
                 } 
            } 

So now when we enter <base url>/community name, we get our custom visualforce page instead of standard login page and from here we can login to communities.