Showing posts with label Force.com Platform. Show all posts
Showing posts with label Force.com Platform. Show all posts

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
     
    
    

    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
      
      

      How to add and delete row in a datatable through visualforce

      Scenario:
      Through a VisualForce custom Page the user must have the
      ability to add and delete row.

      BrainStorming:
      For each record display the record should have a link for deletion.
      So that it will delete that row only.

      For all the records, it will have a button call Add to add an
      additional line to the records.

      Tools needed:
      1. An Force.com Account, if you do not have one
      2. get a free developer account Here
      3. Apex Controller
      4. VisualForce Page
      Lets Get Started:
      1. Create your Apex Controller.
      This will have the PageRefernce to:
      • Add()
      • Delete()
      • Save()
      2. Create your Visual Force Page.

      First thing:
      I will create a simple Apex Controller.
      Go to Setup | Develop | Apex Classes
      Click New

      The Apex Class I created is off the Account Object and
      Case Object.

      It will show, all the Cases for the Account
      associated with it.

      Here the User can Add or Delete the case
      one by one or even close it.

      Below if the code for it:
      /*Start off by placing a name for the controller,
      When I build a controller I always place
      controller at the end of the name*/
      public class AccountsController {
      
      /* I set the Account and Case Objects
      here for use through out the code*/
      public Account acct { get; private set;}
      public Case[] caseItems { get; private set; }
      private ApexPages.StandardController controller;
      
      // constructor, loads the Account and
      // any cases associated with it
      
      void caseItems(id id) {
      acct = [SELECT Id, Name, Type, AccountNumber, Site,
            (SELECT Id, CaseNumber, Status, Reason,Origin,
            Subject FROM Cases) FROM Account
            where id = :id limit 1];
      //Hook caseItems to the query above
       caseItems = acct.Cases;
      }
      
      //Define the id
      id accountid;
      
      /* A List Method to delete the Cases assigned*/
      public list todelete = new list();
      
      public AccountsController (ApexPages.StandardController c)
      {
      /* this will kickoff you main page */
      controller = c;
      /* to get this current Account Id*/
      accountid = c.getRecord().id;
      /*kick off the init() function*/
      init();
      }
      public AccountsController () {
      accountid =
      ApexPages.CurrentPage().getParameters().get('id');
      
      init();
      
      }
      
      void init() {
      /* load up Cases
      basically we defined caseitems up on top, so
      when the page loads then caseItems(accountId)
      will go through the query and list out the
      Items assoicated with it */
      caseItems(accountid);  
      }
      
      public PageReference save() {
      try {
      upsert caseItems;
      if ( todelete.size() > 0 ) {           
      delete todelete;   
      }
      caseItems(acct.id);
      }
      catch ( DmlException exc) {
            ApexPages.addMessages(exc);
            return null;
      }
      return null;
      }
      
      
      /* your Delete functionality*/
      public PageReference del() {
      
      string delnumber =
      ApexPages.CurrentPage().getParameters().get('delnumber');
      
      system.assert( delnumber != null );
      integer gone = -1;
      integer i = 0;
        
      for ( i=0; i< casenumber ="="" gone =" i;">= 0) {
      todelete.add(caseItems.remove(gone) );
      }
      return null;
      }
      public PageReference add() {
      // insert a new line, after user clicks Add
      Case cs =  new Case(
      AccountId = acct.id,
      Subject = 'hello', Status = 'Low',
      Reason = 'Other',Origin='Low'
      );
      caseItems.add ( cs );
      return null;
       }
      }
      
      Second, Now for the Visual Force Page:
      Setup | Develop | Pages
      Click New
      Name it editCases
      Paste this in:
      
      <apex:page standardController="Account"
      extensions="AccountsController"
      sidebar="false" tabStyle="Account" >
      
      <style>
      .dataCell input {
      width:100px;
      }
      </style>
      
      <apex:form >
      
      <apex:actionFunction status="outStatus"
      name="yacks" rerender="table" />
      
      <apex:pageBlock title="Edit Cases"
      mode="edit" id="table">
      
      <apex:pageBlockButtons >
      
      
      
      <apex:commandButton action="{!save}"
      value=" Save " />
      <apex:commandButton action="{!add}" value="Add" rerender="table" /> </apex:pageBlockButtons> <apex:pageMessages /> <apex:pageBlockSection title="Account Name : {!Account.name} " columns="1"> <apex:pageBlockTable value="{!caseItems}" var="item" > <apex:column headerValue="Action"> <apex:commandLink value="Del" action="{!del}" rerender="table" > <apex:param name="delname" value="{!item.CaseNumber}" /> </apex:commandLink> </apex:column> <apex:column headerValue="Case Number"> <a href="/{!item.CaseNumber}"> {!item.CaseNumber}</a> <apex:outputPanel rendered="{!isnull(item.CaseNumber)}" > <apex:inputField required="true" value="{!item.CaseNumber}" onchange="yacks();" /> </apex:outputPanel> </apex:column> <apex:column headerValue="Subject"> <apex:inputField required="true" value="{!item.Subject}" onchange="yacks();"/> </apex:column> <apex:column headerValue="Reason" > <apex:inputField required="true" value="{!item.Reason}" onchange="yacks();" /> </apex:column> <apex:column headerValue="Origin" > <apex:inputField value="{!item.Origin}" onchange="yacks();"/> </apex:column> </apex:pageBlockTable> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> Some Definitions for the Apex Controller and VF Page: 1. Public Reference whtever() : These are used for action methods for the controller. Like Save, Add, Reset, Delete,Cancel 2. return Method : This contains the value from either a query or action. Within the save(), I return null; at the end to stay on that same page. If I wanted to redirect back to the account page I would return functionredirect(); And functionredirect() would be a custom function to go back to the account page. 3. <apex:pageBlockButtons > : Creates a button, that have the same style as regular Salesforce.com buttons. The Attributes for the pageBlockButtons Tag are: Note** This came from the VisualForce Online Guide. Great Materials for VisualForce Tutorials:
      Thanks
      Check out my Other Salesforce.com Blogs
      Salesforce Made Easy

      Salesforce Data Migration Made Easy
      eTechCareers.com Coming Soon

        Wednesday, March 18, 2009

        Blend a table within the environment using VisualForce

        Scenario:
        Within a PDF create a table that would blend into the environment off the data QuoteLineItem. The borders and colors should be the same style as the Quote Tab.

        What is needed for this assignment:
        1. Developer Account if you do not already have one.
        2. Apex Controller write a simple one that gets all account or just one account.
        3. Login into your org, go to Setup | Develop | Pages
        4. Click New, Enter in Label and Name. Note** the Name column may not have a space in between and will not prefill after the label column. You will get an error such as:

        Error: The page name can only contain alphanumeric characters, must begin with a letter,
        and must be unique.


        Understand Tags and Build out:

        TabStyle

        Using this tag will get you the colors of the Quote Tab. Plus it
        will open up the VisualForce Page in the Quote Tab.
        Now if the tabstyle was set to Account then it will inherit the
        colors and open up under the Account tab.

        Facts about TabStyle:
        1. "the tabStyle attribute of an tag allows you to mimic
        the look and feel of the associated Salesforce page"..
        From Force.com Online tutorial guide

        2. The tabstyle is always equal to the object API Name.

        3. It is a String within the <apex:page> tag.


        We will add to the first tag, the tabstyle reference.

        Within the <apex:Page> tag place in tabStyle="ObjectName"

        **Note: Object Name can be a Standard Object or a Custom Object
        Make sure if a Custom Object to use the API Object Name
        "XXXX__c".

        <apex:page tabStyle="SFDC_520_Quote__c">
        and click save.
        To view this page go to the URL and at the of the last
        slash after your
        instance URL. type in /apex/tabtest




        RenderAs="PDF"
        Since the Scenario asked for PDF Page. Then within the
        <apex:Page tag place in renderAs="PDF"

        This would convert the page as a PDF.
        So tag should look like so:

        <apex:page tabStyle="
        SFDC_520_Quote__c" renderAs="PDF">

        Remeber to always close your Tags
        So to close the <apex:page> tag, at the end of the code place in
        </apex:page>

        PageBlock and PageBlockSection
        These two tags go hand in hand. The main tag(PageBlock)
        is the one that encompasses many tags within it. The
        PageBlock tag gives it that border with the same color
        as your tabstyle. Now PageBlockSection gives it the
        header shaded in the same color as the style.

        So lets do it:
        the second line should read as follows:

        Use pageBlock Tag Line #2
        <apex:pageblock></apex:pageblock>

        This will get you the upper border, right side border
        and bottom border.

        As you can see the green borders
        are created from the pageblock tag.
        Now to add the PageBlockSection. This would give as our
        Header or Title.Underneath the pageBlock line and within
        the closing pageblock tag place in the following:

        <
        apex:pageBlockSection title="Congrats">

        </apex:pageblockSection>
        See Below:

        As you can see the header now in green.

        Your code should look like this now:

        <apex:page tabStyle="SFDC_520_Quote__c">

        <apex:pageBlock>
        <apex:pageBlockSection title="Congrats Header"
        collapsible="false" columns="1">


        </apex:pageBlockSection>

        </apex:pageBlock>

        </apex:page>

        Notice:
        ***collapsible within the tag is used to open or close the
        header information below it. I set it to false because
        I would like the user to see the information at all
        times and never have to hide it.


        Create The Table:

        We will utilize pageblockTable ... This blends into
        the environment.
        Let me post the code up and then explain the tags:

        <apex:page
        tabStyle="SFDC_520_Quote__c">

        <apex:pageBlock>

        <apex:pageBlockSection
        title="Congrats Header"
        collapsible="false"
        columns="1">

        <apex:pageBlockTable
        value="{!SFDC_520_Quote__c.quote_lines__r}"
        var="item" border="1"
        cellspacing="0"
        cellpadding="0">

        <apex:column headerValue="Item #">
        {!item.name}
        </apex:column>

        <apex:column headerValue="SKU">
        {!item.Product2__r.ProductCode}
        </apex:column>

        <apex:column headerValue="Description">
        {!item.Product2__r.Name}
        </apex:column>

        <apex:column headerValue="Qty">
        <apex:outputField value="{!item.Qty_Ordered__c}"/>
        </apex:column>

        </apex:pageBlockTable>

        </apex:pageBlockSection>

        </apex:pageBlock>


        </apex:page>
        Alright, now for an explanation:

        • We using the child object QuoteLineItems related to Quotes.

        • Utilizing the child object for information on line items.

        • We set the variable to be item.

        • We gave the table a border = 1, higher you go the
          thicker the border.

        • We now need an Apex Controller to place in the items we need.
        Good Reference Materials:



        Monday, March 2, 2009

        Google Graphs using VisualForce...

        Hi:
        Welcome back,
        Scenario:
        • Had to created a real time graph(TimeLine) on salesforce.com, year over year to show sales data for the account.
        • Place this on the Account page layout when viewing the record.
        • Had to use Google graph.
        Not so easy, but with my help and visual aid I'll walk you through it step by step.

        What you will need:
        • As always developer force.com edition
        • data in the account record
        • sales data table
        • internet :)
        So Stay tuned...
        Thanks
        Check out my Other Salesforce.com Blogs
        Salesforce Made Easy

        Salesforce Data Migration Made Easy
        eTechCareers.com Coming Soon

        Wednesday, February 25, 2009

        Insufficient Privileges??? Users can not see VisualForce Page??

        Hi.. Welcome back:
        I ran into a scenario where there was a VisualForce page created with a controller and added onto the Page Layout.
        Now I as an admin I can view the VF page on the page layout I placed in on...
        But when I logged into as an User I could not view the page...
        The Answer to this
        page level security access on their profile to this VFpage

        To accomplish this do the following:
        1. Go to the Setup | Develop | Pages

        You will see The Following:

        Notice you have a Link that states Security... Click on it.. It will take you to the Page Level Security Page.

        Select the Profile from the Left side and click the Add button and click save.
        Now you have given Page Level Security to The Profile Added.
        ***Note: This gives the Access to this VF Page only, each VF Page is independent.. So if you like to give access to more VF Pages then you must repeat the steps for that Page.. ***
        Hope this helps
        Thanks
        Check out my Other Salesforce.com Blogs
        Salesforce Made Easy

        Salesforce Data Migration Made Easy
        eTechCareers.com Coming Soon

        Tuesday, February 24, 2009

        How do I add VF Page to Account Page Layout??

        Hi:
        Welcome back...
        Let say you created a Visual Force Page and Apex Controller... Now you want to add the VF page to the Page Layout on for example Account. So when an user goes into an Account; he/she will see the Visual Force Page created.
        But, there is no option there on the account Page Layout to add VF pages...
        Now what?
        Well very easy, The solution is:
        VF pages will show up in the Page Layout editor if there is at least one VF Page using the standard controller for Account (in your scenario).
        The VF page you want to add to the Account page layout must use the Account standard controller.
        For example in your Visual Force Page First line should have the standard Controller connected to the object:


        Make sure you create the apex method in your Apex class....
        Thanks
        Check out my Other Salesforce.com Blogs
        Salesforce Made Easy

        Salesforce Data Migration Made Easy
        eTechCareers.com Coming Soon
        
        
        

        Wednesday, December 17, 2008

        Visual Force - Own Mean Engine...

        Hi all:
        Welcome to Visual Force Made Easy for Force.com Platform. Wow. This runs on Force.com main concept of Model View Component.
        See Picture Below:

        From Salesforce.com WIKI Page...
        What one can do in Visual Force or as I like to call it is VF.
        1. Change a layout of a screen
        2. Place in many screens into one
        3. Create your own custom screen
        4. Use the VF component reference...
        ***Sadly, it is not supported by Salesforce.com Premier Support for any of there editions.
        But it is supported through there Salesforce.com Professional Services ... (They charge a lot) better to get a consultant like me to do your Pages if you do not have the techy available.

        Stay tuned for more on VF, the Big Mean Engine...
        Thanks
        Check out my Other Salesforce.com Blogs
        Salesforce Made Easy

        Salesforce Data Migration Made Easy
        eTechCareers.com Coming Soon