Ads

Showing posts with label VisualForce Pages. Show all posts
Showing posts with label VisualForce Pages. Show all posts

Tuesday 17 September 2013

Using static resource Dynamically in Salesforce?

Let’s suppose we have an archive in static resource with name “Contact” and you want to use this static resource on a page that displays Contact Photos dynamically. Assumption is that the images are stored with same name as product codes.
Code:

//Declare an apex variable which gets the Contact code from an apex property
<apex:variable var="contact_photo" value="{!contactPhoto}.jpg"/>
<img src="{!URLFOR($Resource.Products,contact_photo)}')" alt="" />

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:
Lets do it off Contacts
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>

GROUP BY - Count Method in Apex Controller?

Scenario:

We Need to do Total of Opportunities  Based on Stages. 

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


Solution:
Use Eclipse IDE or SOQL Explorer to create your SOQL Statement.
SELECT StageName, Count(Name) ce FROM Opportunity GROUP BY StageName
Second create  Apex Controller name what you like I named it TTL_Lesson, with your logic
public class TTL_Lesson{
public class OppStageHolder {
    public String OPP {get; set;}
    public Integer TTL_Opp {get; set;}
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>

Thursday 1 August 2013

Using Rerender to Render — One Solution for Headaches?

It's a regular occurrence to have an <apex:outputPanel> or similar element in a Visualforce page, where you want to toggle visibility of said element according to some variable. Something that's caught both myself and fellow teammates out on a few such occasions is finding that it just won't appear again after being removed from the screen, when the page code looks analogous like the following.

<apex:outputPanel id="thePanel" rendered="{!bRenderThePanel}">
    <!-- Content -->
</apex:outputPanel>

<apex:commandButton action="{!DoSomeCalcs}" rerender="thePanel" value="FIRE!"/>

In this example, the action DoSomeCalcs is implemented such that it will toggle the value of the variable bRenderThePanel and so the result should be that the panel is alternately displayed and hidden with each click of the button. Woe is the developer, as this is not the case. Chances are you'll find yourself confused as to why it just won't reappear (or appear in the first place).

Essentially re-rendering a specified panel (or other component) that is not currently displayed will fail, and the solution is to wrap it with a component that is always present, using that as the target for the re-render. Thus our example becomes:

<apex:outputPanel id="thePanelWrapper">
    <apex:outputPanel rendered="{!bRenderThePanel}">
        <!-- Content -->
    </apex:outputPanel>
</apex:outputPanel>

<apex:commandButton action="{!DoSomeCalcs}" rerender="thePanelWrapper" value="FIRE!"/>

What does seem strange to me is that Salesforce have specifically ensured that you can access DOM elements within an <apex:outputPanel> when it's not displayed, as indicated by the documentation for the layout attribute, it seems odd that this functionality does not carry over for the element itself when it's being used as a re-render target.

The layout style for the panel. Possible values include "block" (which generates an HTML div tag), "inline" (which generates an HTML span tag), and "none" (which does not generate an HTML tag). If not specified, this value defaults to "none". However, if layout is set to "none", for each child element with the rendered attribute set to "false", the outputPanel generates a span tag, with the ID of each child, and a style attribute set to "display:none". Thus, while the content is not visible, JavaScript can still access the elements through the DOM ID.

Happy coding!

Tuesday 30 July 2013

AggregateResult in Salesforce?

AggregateResult in Salesforce is used to find Sum, Min, Max and Avg. It is similar to Aggregate function in SQL.

Using Aggregate Result, we cannot fetch data. It is mainly used to find Sum, Min, Max and Avg.

Sample Code:

Visualforce page:

<apex:page controller="Sample" sidebar="false" action="{!show}">
<apex:pagemessages />
<apex:form >
    <apex:pageBlock >
        <apex:pageblockTable value="{!SummaryList}" var="r">          
            <apex:column headerValue="Account Name" value="{!r.AcctName}"/>
            <apex:column headerValue="Number of Contacts" value="{!r.Total}"/>
        </apex:pageblockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Controller:

public with sharing class Sample {
    public List<AggregateResult> Result {get;set;}  
    public List<Summary> SummaryList {get;set;}
    public List<Account> AcctList;
    public Map<Id, Account> IdAccount;
    List<Id> Ids;
   
    public void show() {
        SummaryList = new List<Summary>();
        Result = new List<AggregateResult>();
        Ids = new List<Id>();
        AcctList = new List<Account>();
        IdAccount = new Map<Id, Account>();
       
        Result = [SELECT Count(Id) Total , AccountId FROM Contact GROUP BY AccountId];              
       
        for(AggregateResult a : Result) {  
            Ids.add((Id)a.get('AccountId'));
        }
       
        AcctList = [SELECT Name FROM Account WHERE Id IN : Ids];
       
        System.debug('Account List' + AcctList);
       
        for(Account a : AcctList) {
            IdAccount.put(a.Id, a);          
        }
       
        System.debug('Ids and Accounts are ' + IdAccount);
               
        for(AggregateResult a : Result) {
            Account TempAcct = new Account();          
            TempAcct = IdAccount.get((Id)(a.get('AccountId')));
            system.debug('Account Name is ' + TempAcct.Name);
            SummaryList.add(new Summary(a, TempAcct.Name));              
        }  
    }
   
    public class Summary {
        public Integer Total {get;set;}
        public String AcctName {get;set;}
       
        public Summary(AggregateResult a, String AccountName) {
            Total =  (Integer)a.get('Total');
            AcctName = AccountName;
        }
    }
}
 output:


Sunday 21 July 2013

Javascript to select all checkboxes in visualforce page?

I needed to develop a custom visualForce page which would hold a page block table which would contain a checkbox and details of a custom object based on which user can select and click on buttons to perform some operations.

I wrapped the custom object record and check box in a wrapper class. I needed a simple functionality when the header checkbox is selected or deselected accordingly all the checkbox will get selected or deselected accordingly. So i looked into community and first result community gave is this(controller way). It involved calls to back end and as a result functionality is little slow.

So I went for a Javascript solution which would provide a faster,elegant and much simpler way.Here is the VF code which was used in the page above.
<apex:pageBlockTable value="{!wrapreportsobj }" var="w" id="Selected_PBS">
<apex:column ><apex:facet name="header">
<apex:inputCheckbox onclick="checkAll(this,'checkedone')"/>
</apex:facet>
<apex:inputCheckbox value="{!w.selected}" id="checkedone"/></apex:column>
<apex:column ><apex:facet name="header">Id</apex:facet><apex:outputfield value="{!w.rep.id}"/></apex:column>
<apex:column ><apex:facet name="header">Name</apex:facet><apex:outputfield value="{!w.rep.name}"/></apex:column>
</apex:pageBlockTable>

Note that I have set the id of the checkbox as checkedone and while clicking on header checkbox it calls a javascript function  checkAll. Giving an id will segregate all the checkboxes in the table. Here is the javascript which would handle the selecting and deselecting all of the checkboxes which has id checkedone in it.

<script type="text/javascript">
    function checkAll(cb,cbid)
        {
            var inputElem = document.getElementsByTagName("input");                    
            for(var i=0; i<inputElem.length; i++)
            {            
                 if(inputElem[i].id.indexOf(cbid)!=-1){                                      
                    inputElem[i].checked = cb.checked;
                }
            }
        }
</script>

Tuesday 16 July 2013

Read and Insert records from a CSV file - Using Visualforce?

The Apex Data Loader is always there when you want to insert records into Salesforce from a CSV file. But, just in case if you don't want your users to install the Apex Data Loader and learn how to use it, then here is a simple example which tells you how to do the same using Visualforce.

Click here to view the demo.


Step 1:

Download the template from the DEMO URL above. Save the file in your desktop. Upload the file into Static Resources with the name "AccountUploadTemplate".

Step 2:

Create an Apex Class named "FileUploader". Paste the code below and save it.



public class FileUploader
{
    public string nameFile{get;set;}
    public Blob contentFile{get;set;}
    String[] filelines = new String[]{};
    List<Account> accstoupload;
 
    public Pagereference ReadFile()
    {
        nameFile=contentFile.toString();
        filelines = nameFile.split('\n');
        accstoupload = new List<Account>();
        for (Integer i=1;i<filelines.size();i++)
        {
            String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
         
            Account a = new Account();
            a.Name = inputvalues[0];
            a.ShippingStreet = inputvalues[1];    
            a.ShippingCity = inputvalues[2];
            a.ShippingState = inputvalues[3];
            a.ShippingPostalCode = inputvalues[4];
            a.ShippingCountry = inputvalues[5];

            accstoupload.add(a);
        }
        try{
        insert accstoupload;
        }
        catch (Exception e)
        {
            ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured. Please check the template or try again later');
            ApexPages.addMessage(errormsg);
        }  
        return null;
    }
 
    public List<Account> getuploadedAccounts()
    {
        if (accstoupload!= NULL)
            if (accstoupload.size() > 0)
                return accstoupload;
            else
                return null;                  
        else
            return null;
    }          
}

Step 3:

Create a Visualforce Page named "UploadAccounts". Paste the code below and save it.



<apex:page sidebar="false" controller="FileUploader">
   <apex:form >
      <apex:sectionHeader title="Upload data from CSV file"/>
      <apex:pagemessages />
      <apex:pageBlock >
             <center>
              <apex:inputFile value="{!contentFile}" filename="{!nameFile}" /> <apex:commandButton action="{!ReadFile}" value="Upload File" id="theButton" style="width:70px;"/>
              <br/> <br/> <font color="red"> <b>Note: Please use the standard template to upload Accounts. <a href="{!URLFOR($Resource.AccountUploadTemplate)}" target="_blank"> Click here </a> to download the template. </b> </font>
             </center>
   
   
      <apex:pageblocktable value="{!uploadedAccounts}" var="acc" rendered="{!NOT(ISNULL(uploadedAccounts))}">
          <apex:column headerValue="Account Name">
              <apex:outputField value="{!acc.Name}"/>
          </apex:column>
          <apex:column headerValue="Shipping Street">
              <apex:outputField value="{!acc.ShippingStreet}"/>
          </apex:column>
          <apex:column headerValue="Shipping City">
              <apex:outputField value="{!acc.ShippingCity}"/>
          </apex:column>
          <apex:column headerValue="Shipping State">
              <apex:outputField value="{!acc.ShippingState}"/>
          </apex:column>
          <apex:column headerValue="Shipping Postal Code">
              <apex:outputField value="{!acc.ShippingPostalCode}"/>
          </apex:column>
          <apex:column headerValue="Shipping Country">
              <apex:outputField value="{!acc.ShippingCountry}"/>
          </apex:column>
      </apex:pageblocktable>
   
      </apex:pageBlock>    
   </apex:form>
</apex:page>



Screenshot:


Some pointers:
You can use only the standard template. Because, that's how we have done the mapping to the columns in excel and the fields in Salesforce. You can modify the mapping and use your own template.
Allowing the user to choose his own mapping is possible i believe, but may be a bit complex.
Also, we use a CSV file. So, you may have to use additional criteria if your data values itself have a comma in them (For ex: Billing Street = 'Mumbai, India ') . This would cause problems because Mumbai and India would be considered as seperate values because of the comma in between them.

Thursday 20 June 2013

Adding Rows Dynamically to Page block Table ?

Apex:

public class MemberPopup
{
    public List<Account> memberList {get;set;}
    public List<Account> memberAddList {get;set;}
    public String memberName {get;set;}      
    public MemberPopup()
    {
        String sql = 'SELECT Name,Company__c FROM Account';
        memberList = Database.Query(sql);
        memberAddList = new List<Account>();
        memberAddList.add(new Account());
    }  
    public void AddRow()
    {
        memberAddList.add(new Account());
    }
}



VF Page:

<apex:page controller="MemberPopup" >
<apex:form >
    <apex:pageBlock id="membAdd" >                
        <apex:pageblockSection >
            <apex:pageBlockTable value="{!memberAddList}" var="m" >
                <apex:column headerValue="Member Name">
                    <apex:inputField value="{!m.Name}"/>
                </apex:column>
                <apex:column headerValue="Mobile Number">
                    <apex:inputField value="{!m.Company__c}"/>
                </apex:column>
                <apex:column headerValue="eMail Id">
                    <apex:inputField value="{!m.Account_Status__c}"/>
                </apex:column>
            </apex:pageBlockTable>
            <br/><apex:commandLink value="Add Row" action="{!addRow}" reRender="membAdd"/>      
        </apex:pageblockSection>      
        <apex:pageblockSection columns="1" >
            <apex:pageblockSectionItem >
                <apex:commandButton value="Save" />
                <apex:commandButton value="Cancel" />
            </apex:pageblockSectionItem>       
        </apex:pageblockSection>
    </apex:pageBlock>
</apex:form>
</apex:page>



how to get a picklist values in apex controller?

Apex:
public class PicklistController{

    public Lead lead{get;set;}
    public List<SelectOption> statusOptions {get;set;}
   
    // Constructor called when page is accessed.
    public PicklistController() {   
        lead = new Lead();       
        statusOptions = new List<SelectOption>();

        // Use DescribeFieldResult object to retrieve status field.
        Schema.DescribeFieldResult statusFieldDescription =  Lead. Status.getDescribe();
        // For each picklist value, create a new select option
        for (Schema.Picklistentry  picklistEntry: statusFieldDescription.getPicklistValues())
{
            statusOptions.add(new SelectOption( pickListEntry.getValue(),pickListEntry.getLabel()));
            // obtain and assign default value
         
        }    
    }
}

VF Page:
<apex:page controller="PicklistController">
    Please selectValue:
    <apex:form >
        <apex:selectList size="1" value="{!led.Status}">
            <apex:selectOptions value="{!statusOptions}"/>
        </apex:selectList>
    </apex:form>  
</apex:page>

Screen Shot:





Sunday 26 May 2013

To display all the fields of sObject using Apex & VF?

<apex:page showHeader="false" Controller="FieldsClass">
        <apex:DataTable value="{!data}" var="d">
             <apex:column headerValue="Field Name">
                 {!d}
             </apex:column>         
         </apex:DataTable>
</apex:page>
*******************************
public class  FieldsClass {

     public map<string,Schema.SObjectField> data {get;set;}
  
     public  FieldsClass (){
         data = Schema.SObjectType.Book__c.fields.getMap();
        }
    }

We have three country buttons, if we click any button that country information should only display?

Apex:
public class coun {

    public Boolean hide = false;
    public Boolean hide1 = false;
    public Boolean hide2 = false;
    
    public void setMhide(Boolean b) {
    this.hide = b;
    }
    
    public Boolean getMhide() {
    return this.hide;
    }//Passing input dynamically through another method
    
    
    public Boolean getM1hide() {
        return this.hide2;
    }
    
    public void setM1hide(Boolean b) {
      this.hide2 = b;  
    }
    
    
    public Boolean getM2hide() {
        return this.hide1;
    }
    
    public void setM2hide(Boolean b) {
        this.hide1 = b;
    }
    
    
    public PageReference india() {
        setMhide(true);
        setM2hide(false);
        setM1hide(false);     
        return null;
    }//displaying only india information and hiding other information
    
     public PageReference us() {
        setM1hide(true);
        setM2hide(false);
        setMhide(false);
        return null;
    }
    
    public PageReference uk() {
        setM2hide(true);
        setM1hide(false);
        setMhide(false);
        return null;
    }   
    
}
Vf Page:
<apex:page controller="coun">
<apex:form >

<apex:commandButton value="India" action="{!india}" reRender="India,Us,Uk"/>
<apex:commandButton value="Us" action="{!us}" reRender="India,Us,Uk"/>
<apex:commandButton value="Uk" action="{!uk}" reRender="India,Us,Uk"/>

<apex:pageBlock >

<apex:outputPanel id="India">
<apex:pageBlockSection title="India" rendered="{!mhide}">
</apex:pageBlockSection>
</apex:outputPanel>
<apex:outputpanel id="Us">
<apex:pageBlockSection title="US" rendered="{!m1hide}">
</apex:pageBlockSection>
</apex:outputpanel>

<apex:outputpanel id="Uk">
<apex:pageBlockSection title="UK" rendered="{!m2hide}">
</apex:pageBlockSection>
</apex:outputpanel>

</apex:pageBlock>

</apex:form>
</apex:page>



Dispaly particular field based on the selection of the particular field?

<apex:page standardController="Book__c">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockTable id="mytable" value="{!Book__c}" var="item">
  <apex:column headerValue="Delivery">
    <apex:actionRegion >        
      <apex:inputField value="{!item.City__c}">
        <apex:actionSupport event="onchange" reRender="mytable"/>
      </apex:inputField>
    </apex:actionRegion>
  </apex:column>
  <apex:column headerValue="Delivery Type">
    <apex:inputField rendered="{!item.City__c = 'Chennai'}" value="{!item.Chennai__c}"/>
    <apex:inputField value="{!item.Banglore__c}"/>
  </apex:column>
</apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>


Thursday 16 May 2013

Custom Multi-Select picklist field in Visualforce?


There are several scenarios, where in we might have used input field for getting multi-select picklist field. What if you can’t really use an input field, here is the example code which will solve these type of problems.
Mutli-Select
VFPage Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<apex:page controller="multiselect">
    <apex:form >
        <apex:panelGrid columns="3" id="abcd">
            <apex:selectList id="sel1" value="{!leftselected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!unselectedvalues}" />
            </apex:selectList>
                <apex:panelGroup >
                    <br/>
                    <apex:image value="{!$Resource.multiselected}">
                        <apex:actionSupport event="onclick" action="{!selectclick}" reRender="abcd"/>
                    </apex:image>
                    <br/><br/>
                    <apex:image value="{!$Resource.multiunselected}">
                        <apex:actionSupport event="onclick" action="{!unselectclick}" reRender="abcd"/>
                    </apex:image>
                </apex:panelGroup>
            <apex:selectList id="sel2" value="{!rightselected}" multiselect="true" style="width:100px" size="5">
                <apex:selectOptions value="{!SelectedValues}" />
            </apex:selectList>
        </apex:panelGrid>
    </apex:form>
</apex:page>
Controller Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public class multiselect {
    Set<String> originalvalues = new Set<String>{'A','B','C','D','E','F','G'};
    Public List<string> leftselected{get;set;}
    Public List<string> rightselected{get;set;}
    Set<string> leftvalues = new Set<string>();
    Set<string> rightvalues = new Set<string>();
     
    public multiselect(){
        leftselected = new List<String>();
        rightselected = new List<String>();
        leftvalues.addAll(originalValues);
    }
     
    public PageReference selectclick(){
        rightselected.clear();
        for(String s : leftselected){
            leftvalues.remove(s);
            rightvalues.add(s);
        }
        return null;
    }
     
    public PageReference unselectclick(){
        leftselected.clear();
        for(String s : rightselected){
            rightvalues.remove(s);
            leftvalues.add(s);
        }
        return null;
    }
    public List<SelectOption> getunSelectedValues(){
        List<SelectOption> options = new List<SelectOption>();
        List<string> tempList = new List<String>();
        tempList.addAll(leftvalues);
        tempList.sort();
        for(string s : tempList)
            options.add(new SelectOption(s,s));
        return options;
    }
    public List<SelectOption> getSelectedValues(){
        List<SelectOption> options1 = new List<SelectOption>();
        List<string> tempList = new List<String>();
        tempList.addAll(rightvalues);
        tempList.sort();
        for(String s : tempList)
            options1.add(new SelectOption(s,s));
        return options1;
    }
}