Wednesday, October 6, 2010

GROUP BY - Count Method in Apex Controller

Scenario:
Need to do Totals of Stages in Opportunity for the entire org.

Thought Process:
  1. What are the columns involved? Answer: StageName and Count or Total
  2. What methods will we utilize to achieve these results? Answer: Group By SOQL Statement with Count.
  3. What UI to built this neat logic? Answer: Apex Controller and VisualForce Page
  4. Need to achieve this type of reporting for the user:

    Solution:
    1. Use Eclipse IDE or SOQL Explorer to create your SOQL Statement.
    2. SELECT StageName, Count(Name) ce 
      FROM Opportunity GROUP BY StageName
    3. Second create  Apex Controller name what you like I named it TTL_Lesson, with your logic
    public class TTL_Lesson{
    //Define your variables
    public class OppStageHolder {
        public String OPP {get; set;}
        public Integer TTL_Opp {get; set;}
    //Empty Array    
    public OppStageHolder (){}
    }
    //Results will be placed within this List
    public List queryResults{ get; set; }
    
    //Your Page
    public PageReference TTL() {
    
    AggregateResult[] groupedResults = [SELECT StageName, 
         Count(Name) ce FROM Opportunity 
         GROUP BY StageName];  
    System.Debug('zzavg ' + groupedResults.size());
    //Define your List
    queryResults = new List();
    
    for (AggregateResult ard : groupedResults)  {    
        OppStageHolder myObject = new OppStageHolder();    
        myObject.OPP = String.valueOf(ard.get('StageName'));    
        myObject.TTL_Opp = (Integer) ard.get('ce');         
        queryResults.add(myObject);    
    }
    return Page.TTL;
    }

    }

    Now create your VF Page to call this and display it whenever the user clicks on this page:

    <apex:page controller="TTL_Lesson" action="{!TTL}" showHeader="false" sidebar="false">
        <apex:dataTable value="{!queryResults}" var="a" id="theTable" border="2" cellpadding="1" cellspacing="1" bgcolor="#A9D0F5" >
                    <apex:column >
                            <apex:facet name="header">Stage</apex:facet>
                            <apex:outputText value="{!a.OPP}"/>
                    </apex:column>               
                    <apex:column >
                            <apex:facet name="header">&nbsp;&nbsp;&nbsp;Count</apex:facet>
                            <apex:outputText value="{!a.TTL_Opp}"/>
                    </apex:column>
        </apex:dataTable>
    </apex:page>

    End result is the image on top

    Friday, August 6, 2010

    Opportunity Wizard Controller - TestMethod

    Hi all:
       So, I was looking all over for the opportunity wizard controller test method. There is none, not even salesforce wrote a test wizard for it.
    They wrote the controller wizard. Which can be found here:
    Opportunity Wizard Controller

    I decided to write a test class for it:
    Place this within the controller before it ends.

    Here it is:

    private static testmethod void testnewOpportunityController(){
     
    newOpportunityController controller 
    = new newOpportunityController();          
    
    Account acct = controller.getAccount();
    acct.Name='Unit Test Name';
    
    Contact cont = controller.getContact();
    cont.LastName = 'Testlast';
    cont.Accountid = acct.id;
    cont.Email = 'choosepros@gmail.com';
    cont.phone = '5551211234';
    
    Opportunity opp = controller.getOpportunity();
    opp.Name = 'oppor name';
    opp.StageName = 'Prospect';
    opp.CloseDate = Date.newInstance(2010,12,31);
    
    OpportunityContactRole oppconrole = controller.getRole();
    oppconrole.opportunityid = opp.id;
    oppconrole.contactid = cont.id;
    controller.cancel();
    controller.step1();
    controller.step2();
    controller.step3();
    controller.save();
    }
     
    Thanks
    
    Check out my Other Salesforce.com Blogs
    
    Salesforce Made Easy 
    
    Salesforce Data Migration Made Easy
    
    eTechCareers.com Coming Soon 

    Friday, April 30, 2010

    How to use rowClasses in a dataTable or PageBlockTable in VisualForce

    Scenario:
     To have a table that would shade each alternative row.

    Solution:
    In your css file or even in the visualforce page place in the following:
    1. In CSS:
      1. .odd {
        background-color: #FCF7F7;
        }
        .even {
        background-color: #E3DCDB;
        }
    2. Inside the VF Page:
    So the Apex Visualforce page would look like this:
                    <apex:page standardcontroller="Contact">
                    <apex:form id="reportform"> <!-- Start of ReportForm-->
                    <apex:dataTable value="{!queryResult}" var="r" id="       ttable" border="0" rowClasses="even,odd">
                     <!--yourcode here-->
                     </apex:dataTable>
                     </apex:form>
                     </apex:page>

    Now you have each other row shaded gray/white.
    Thanks
    Check out my Other Salesforce.com Blogs
    Salesforce Made Easy
    Salesforce Data Migration Made Easy
    eTechCareers.com Coming Soon

    How to use apex variable for total records in Visualforce

    Scenario:
      I came across a issue where visualforce does not allow one to Count or Sum records in a page.
    One solution would be to add more code to the controller to do a count of the records. Which is ok.
    A simple solution is to use the apex variable function in Visualforce.

    Solution:
    1. Lets do it off Contacts
    2. In your Apex Controller : Create a SOQL query as is:
    public class countcontroller{

                public List<Contact> queryResult {get;private set;}

                public String qryString {get;set;}

                public PageReference query(){

                qryString =  'SELECT Name, Email, Phone from Contact';

                queryResult = Database.query(qryString);
                 return null;

           }

    } 

    Pretty Simple and Straight Forward.
    Now for the VF Page and Magic:
    You will see I use the apex variable function to do a couple of things:


    • create a variable
      run the query inside that variable counting all the records by 1 within a repeat tag
      calling the variable with the total 
      Kind of like a for Loop but in Visualforce instead of controller. 
    <apex:page standardcontroller="Contact" extensions="countcontroller">

    <table width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr height="5">
        <td width="35%" class="outsideround_head" align="right">
            Total Contacts Returned:&nbsp;
        </td>
        <td width="8%" class="outside_round_head_value">
            <apex:variable var="call" value="{!0}" />
            <apex:repeat var="countitall" value="{!queryResult}" >
            <apex:variable var="call" value="{!call+1}"/>
            </apex:repeat>
            <apex:outputText value="{!call}"/>
        </td>

    </tr>

    </table>

    </apex:page>

     
    Wallah you have count.
    Thanks please give me feedback!!! 
    Thanks
    Check out my Other Salesforce.com Blogs
    Salesforce Made Easy

    Salesforce Data Migration Made Easy
    eTechCareers.com Coming Soon
     
    
    

    Wednesday, January 27, 2010

    IF THEN STATEMENT IN VF plus Format of Dates in Force.com

    Hi:
       Scenario:
            I had to do an IF THEN STATEMENT off from a date to place a date range into a VF Page.
    Issue I had was the date Formating, because when you place a formula to do a Date it comes out as YYYY-MM-DD
    I needed DD-MM-YYYY
    So this is what I did:
    I created a table that has columns and the resulted row:
    So two tags here being used are :
    apex:column
    apex:outputLabel

    First the Column:
                apex:column headerValue="Date Range          
               apex:outputLabel value="{!IF(DAY(TODAY())>15,
                RIGHT(TEXT(TODAY()), 2) & "/" &
                MID(TEXT(TODAY()), 6, 2) & "/" &
                LEFT(TEXT(TODAY()), 4)& " to " &
                RIGHT(TEXT(item.Last_Day_of_Month__c), 2) & "/" &
                MID(TEXT(item.Last_Day_of_Month__c), 6, 2) & "/" &
                LEFT(TEXT(item.Last_Day_of_Month__c), 4)
                ,
                IF(DAY(TODAY())<15,
                MID(TEXT(TODAY()), 6, 2) & "/" &
                RIGHT(TEXT(TODAY()), 2) & "/" &
                LEFT(TEXT(TODAY()), 4) & " to " &
                RIGHT(TEXT(item.Last_Day_of_Next_Month__c), 2) & "/" &
                MID(TEXT(item.Last_Day_of_Next_Month__c), 6, 2) & "/" &
                LEFT(TEXT(item.Last_Day_of_Next_Month__c), 4),
                'FALSE'))
                }"/>
               
    Now the thing is Last_Day_of_month__c and Last_Day_of_Next_Month are formulas Date Fields I created...
    You can find the formulas on
    http://mysalesforcecode.blogspot.com/2010/01/determine-end-of-month-date-or-days.html
    Thanks
    Check out my Other Salesforce.com Blogs
    Salesforce Made Easy

    Salesforce Data Migration Made Easy
    eTechCareers.com Coming Soon

    Wednesday, December 30, 2009

    Override URL and Button through Apex And Visual Force

    Hi Welcome back...
    I have been soo busy but promise to put up some new and neat things in 2010.
    So lets start:
    As you may know S-Controls are going away in the year 2010. It was very simple to override an URL and button using S-Controls.
    But I have figured out a neat and simple way to do it using Apex and VisualForce.

    Scenario:
    Override the New Button for Opportunity, from contact and pre-populating the field in the URL pushing it forward to Opportunity ContactName field.

    Beginner's Steps:
    1. Get the field ID of the contact Lookup Field in Opportunity. Click on: Setup==>Customize==>Opportunities==>Fields.
    2. Look for the lookup Relationship field to Contact (basically in the


      Opportunity Custom Fields & Relationships Lookup for DataType which would state Lookup(Contact)).




    3. Click on it and get the ID from the URL. It would be something like this:https://tapp0.salesforce.com/00N70000002RFSE The last part of the URL is the salesforce ID that is needed for the Controller and URL we need.
    4. Also we need to know the prefixes for the New Opportunity URL and existing Contact URL. By default the New Opportunity will start with /006/e? and the existing or new Contact will start with /003/e?.
    5. Now we shall place all of this in the controller.
    6. Then the page in which we will call the controller
    7. Override the New Button in the Opportunity Button and Links section.
    Lets Start with the Apex Controller:

    // The Name of the class
    public class OverrideOppButton{

    // Create a variable to get the Contact and set the variable
    Contact c {get; set;}

    //Use a boolean to determine if there are contact records available and set it to false initially
    boolean gotcontactrecords = false;

    //Open up the constructor to get the contact records from the current URL
    public OverrideOppButton(ApexPages.StandardController stdController){

    // Create a variable to return the current Contact URL;
    string ret;
    ret = ApexPages.currentPage().getParameters().get('RetURL');
    //This will pick up the URL on the current contact record
    //For example: https://tapp0.salesforce.com/003T000000MFRcS
    //We need to separate the 003 which is the contact record and the T000000MFRcS which is the ID of //the contact record

    ret = ret.substring(1,ret.length());

    if(ret.startswith('003')) {
    //if the substring of the URL starts with '003' which it does '003T000000MFRcS'
    //Then query the database for that record from the contact

        c = [Select name, lastname, firstname, id from Contact where id =: ret];

    //if they are records then set the gotcontactrecords to true
        gotcontactrecords = true;
     }
    } // end constructor


    /*
    Here we start the PageReference Class which will tell the URL of what to
    place into it
    */
    public PageReference init(){

    /*
    We need to specify where the URL will redirect after the New
    Button is clicked
    */

    //Define the variable first
    string redirectURL = '';
    /*
    Place in if then logic if there is a contact record then place in the url parameters and
    redirect the user to the new Opportunity Page
    if not then redirect them to a new Opportunity Page
    with no parameter in the URL
    */
    if (gotcontactrecords ) {
        redirectURL = '/006/e?CF003T000000MFRcS =
         ' + EncodingUtil.urlEncode(c.name, 'UTF-8') + '
        &CF003T000000MFRcS_lkid=' + c.id + '
        &nooverride=1';
    }
    /*
    Explanation of the RedirectURL:
    /006/ <== Creating New Opportunity Record
    e?      <== What parameters need to be inputed.
    CFT000000MFRcS <== 'CF' is the custom field which is the lookup Contact field in
                                                   the Opportunity Object. field id is T000000MFRcS.
    EncodingUtil.urlEncode(c.name, 'UTF-8')<== Takes in symbols associated with the name
                                                                                 For example: Haaris & Benny
    nooverride=1 <== Need when one overrides the new button.
    */
    else {
        redirectURL = '/006/e?nooverride=1';
    }

    /*
    Set the Page Reference of what URL will it take if it passes the criteria mentioned above
    */
    PageReference createnewOpp = new PageReference(redirectURL);
    return createnewOpp;
    }

    } //end class
    *************************************************************************
    Create the VisualForce Page:
    This page is very simple.
    • Give the page a new which will be used when you override the New Button on the Opportunity
    • Place the initiative in the first tag of Visual Force
    • standardController = "Opportunity" which takes the Look & feel of the Opportunity Page
    • extensions = "OverrideOppButton" which places in the class/controller we just created.
    • action = "{!init}" which calls the PageReference and tells what the URL should be for the user.

    apex:page standardController="Opportunity" extensions="OverrideOppButton" action="{!init}"
    Do not forget the "<" and "/>" in this statement and your closing apex:page tag

    *************************************************************************
    Now go to Setup==> Customize ==> Opportunities ==> Button and Links
    Click on Override next to the New Button
    Click on the radio button which states Visualforce Page for Content Type selection
    Drop down the Content Name and you should see the name of your Visualforce Page
    which you just created.

    That is it, your done.
    Please leave your comments below.
    Thanks



    Friday, March 20, 2009

    Embed VisualForce Page on Home Page

    Scenario:
    Create a Google Graph via VF and then embed it to the
    Home Page. So when an user logs in they see the graph of there sales information Year over year.

    Task at hand:
    For this blog, I will walk through the steps of placing in any
    component onto the Home Page.

    Lets Get Started:
    Go to Setup | Customize | Home | Home Page Components


    Click New
    Choose HTML Area and
    Input the Name for your component.
    Click Next

    Here Choose either Wide (right) Column or Narrow (Left) Column.
    Wide means some where on the Home page in the middle.

    Narrow means somewhere on the Menu Column on the
    Left where the search bar is.
    Select show HTML on the right upper hand side and place in the following:
    <iframe
    src="/apex/yourpagename?core.apexpages.devmode.url=1"
    width="100%" frameborder="0" height="100">
    </iframe>
    
    Then Click save.
    
    Now go into Setup | Customize | Home |
    Home Page Layouts |
    Click Edit next to
    the Layout you would like to conifgure
    Select the component from there
    Click Next and order it where you want it to show.
    Click Save.
    Now go to your Home Page and it should be there.
    As you can see I have a Graph and Summary Side Bar as well.
    Both are VisualForce Pages.
    
    I hope this helped...
    
    Great Materials:
    
    Thanks
    Check out my Other Salesforce.com Blogs
    Salesforce Made Easy

    Salesforce Data Migration Made Easy
    eTechCareers.com Coming Soon