Tuesday, December 26, 2017

Getting Picklist Values of an object's field Dynamically using schema Class

This is very simple. I am sharing some code ,please go through this

Here is My Controller 
public class testclass {
    public Job__c job{get;set;}
    public List<SelectOption> options{get;set;}
    public testclass(){
        options = new List<SelectOption>();
        Schema.DescribeFieldResult fieldResult = Job__c.Status__c.getDescribe();
        List<Schema.PicklistEntry> ple = fieldResult.getPicklistValues();
        for( Schema.PicklistEntry f : ple){       
          options.add(new SelectOption(f.getLabel(), f.getValue()));
        } 
    }
 }

My Page 

<apex:page controller="testclass ">
  <apex:form>
      <apex:pageBlock>          
          Order Status:<apex:selectList id="countries" value="{!job.Status__c}" size="1" required="true" >
              <apex:selectOptions value="{!options}"/>
          </apex:selectList>
      </apex:pageBlock>      
  </apex:form>  
</apex:page>

Creating Email template in Apex to send Custom object Data

Sometimes we try to send some custom object information in mail. For sending mail Sales-force has provided 4 types of email template. We can design the template as per our requirement. We can use simple text template and use merge field to send custom object information. But that template will work perfectly only If we use in the workflow. 
If we send mail from apex code then that merge field value will not be displayed, except we can display Lead ,Contact and User object information.

Instead using the Sales-force Email template, design an template in apex code (using some HTMLtags depending according to your design).
Just make a query which information you want to send and then pass these value as parameter to a method.

List<CustomObject__c> listofCustomObjects = [SELECT id, Name,.Expiration__c ,Account_Name__c
FROM CustomObject__c]
for(CustomObject__c license:listofCustomObjects ) {

Integer numberDaysDue = System.Today().daysBetween(license.Expiration__c);
String name = license.Account_Name__c;
if(numberDaysDue == 30){

sendingmail(numberDaysDue ,name );
}
}

public void sendingmail( Integer noOfdays, String accountName){

Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage() ;
String[] toAddresses = new String[] {'jewell@test.com','neha.v@test.com','sexyRadha@test.com'};
mail.setToAddresses(toAddresses) ;
mail.setSubject('LMO:'+' '+accountName+' '+'licency expiry in'+' '+noOfdays+' '+'days');

String body = '<html lang="ja"><body>'+
'<br><br>'+'This email alert is to bring to your notice that the licence of the client :'+' '+'<b>'+accountName+'</b>'+' '+'is going to expiry within'+'<b>'+' '+noOfdays+' '+'</b>'+
'<br><br>'+'From LMO Alert Service'+'</body></html>';
mail.setHtmlBody(body);
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });


}

How to use Date Time Variable in Dynamic Query Salesforce

In some scenario you might have come across to fetch record with in some date time range. 
Here I am sharing some code for this. Suppose I am querying records from Minutes Object. There is two field Start_Time and End_Time present  in Minutes Object.
This is my page 

 <apex:inputField value="{!minute.Start_Time__c}" required="true" label="From Date"/>
 <apex:inputField value="{!minuteObj.End_Time__c}" required="true" label="To Date"/>
<apex:commandButton action="{!convertValidMinutesToUsage}" value="Process Minute's"/>

This is my controller 
public with sharing class ControllerValidMinutesToUsage {
     public Minute__c minute{get;set;}
     DateTime startDate;
     DateTime endDate;
     string query;

     public ControllerValidMinutesToUsage(){
            minute =  new Minute__c();
    }

    public void convertValidMinutesToUsage(){
       String sStartdate;
       String sEndDate;
       startDate = minute.Start_Time__c;
       sStartdate = startDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
       endDate = minuteObj.End_Time__c+1;
       sEndDate = endDate.format('yyyy-MM-dd\'T\'HH:mm:ss\'Z\'');
       query = 'SELECT Start_Time__c ,End_Time__c, Is_Valid__c WHERE Is_Valid__c = false';
       query += ' AND Start_Time__c >='+sStartdate+' '+'AND Start_Time__c <='+sEndDate
       list<Minute__c> =  DateBase.query(query );
    }
}

NOT IN Keyword in Soql in Salesforce.( Fetching all accounts record which don't have any contacts )

Suppose there is a requirement to fetch all accounts record which don't have any contacts,
how will we do it?

We can fetch account with their corresponding contact record in a in line query.
for example
list<Account> listOfAccounts = [SELECT id, Name,
                                                 (SELECT id,name FROM Contacts)
                                                  FROM Accounts];
list<Account> accountListwithoutContact = new list<Account>();

for(Account act :listOfAccounts ){
      if(act .Contacts !=null && act .Contacts.size() !=0){
              accountListwithoutContact.add(act)   ;
      }

}

accountListwithoutContact list will contain all account which dont have any contacts.

Second approach would be using NOT IN keyword.
list<Account> listOfAccounts = [SELECT id, Name
                                                  FROM Account
                                                  WHERE id NOT IN (SELECT AccountId FROM Contact)];
Now this is the final list which contains all accounts which don't have any contact.

Fetching Unique Record in Salesforce

lIST<AggregateResult> listofAccountsAggregateResult = [SELECT Name FROM Account GROUP BY Name];

It will return unique record of Accounts

Visualforce Adding CheckBox as header to Select all the records in Pageblock Table

I have faced some requirement in my development work . User must be able to select all the record in the page block table in one click . So I added header check-box  in page block table . 
Here is the code how I achieved this. Only Java Script code I have used .

Page


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

        } 
     </script>
    
    <apex:pageMessages />
    <apex:form >
       <apex:pageBlock Title="ALL CONTACTS" >
            <apex:commandButton value="mass delete" action="{!massdelete}"  id="massdelete" onclick="return confirmDelete()"/>
            <apex:pageBlockTable value="{!Contacts}" width="100%" var="c" cellpadding="2" border="1"  rowClasses="odd,even" styleClass="tableClass" id="opp_table">
                <apex:column >
                    <apex:facet name="header"> 
                        <apex:inputCheckbox >
                            <apex:actionSupport event="onclick" action="{!GetSelected}" onsubmit="checkAll(this)" rerender="opp_table" status="newStatus"/>
                         </apex:inputCheckbox>
                     </apex:facet>
                    <apex:inputCheckbox value="{!c.selected}" id="checkedone">
                        <apex:actionSupport event="onclick" action="{!GetSelected}" rerender="opp_table"/>
                    </apex:inputCheckbox>
                </apex:column>
                <apex:column headervalue="AccountName" styleClass="showline">
                    <apex:outputField value="{!c.con.AccountId}" />
                </apex:column> 
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

My Controller..


public with sharing class ControllerforheaderCheckboxinPBT {
     public Contact contact{get;set;}
     public Id contactId{get;set;}
     List<ContactWrapper> contactList = new List<ContactWrapper>();
     List<Contact> selectedContacts = new List<Contact>();
     public ControllerforheaderCheckboxinPBT() {
        Contact contact = new Contact();
     }    
    public  List<ContactWrapper> getContacts() {
       for(Contact c: [SELECT Id,Name,Accountid,loginURL__c,Account.Name,MobilePhone,Email FROM Contact ORDER BY createdDate DESC]){
           contactList.add(new ContactWrapper(c));
        }   
       return contactList;
    }
     public PageReference getSelected() {
         System.debug('======Inside the Get Function======');
         selectedContacts.clear();
      
         //adding contacts in list 
         for(ContactWrapper conWrapper: contactList) {
            if(conWrapper.selected == true) {
                conWrapper.isChanged = true;
                selectedContacts.add(conWrapper.con);  
            }                    
          }      
          return null;
      }
      
      public PageReference massDelete() {
          //deleting that list 
  if(selectedContacts.size()>0){
  delete selectedContacts;
  }
              
  //showing an message to select one contact
  else{
  ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Please select at least one Contact.'));
  return null;
  }
  PageReference headerCheckboxPage = new PageReference('/apex/headerCheckboxinPBT');
  headerCheckboxPage .setRedirect(true);
  return headerCheckboxPage ;
  }
     public class ContactWrapper {
         public Contact con{get; set;}
         public Boolean selected{get; set;}
          
         public ContactWrapper(Contact c) {
            con = c;
            selected = false;
              
         }
      }    
}

Salesforce Adding Custom Clone Button In Account

This is a very simple post. We all have seen clone button is present in Standard and Custom Object record except Account. User may expect clone button in Account object also. For them I have done little work around.
When we will create custom button we will find three content source.

  • URL
  • OnCick JavaScript
  • Visulforce page
By using all there we can do clone functionality. But the best choice will be my favorite URL.

Process

  • Go to Customize,  Account ,Buttons, Links, and Actions 
  • Click on New Button or Link
  • Enter Label as Clone
  • Choose Display Type as Detail Page Button
  • Choose Behavior as Display in existing window without header and side bar.
  • Content Source as URL
  • Enter this URL--https://ap1.salesforce.com/{!Account.id}/e?clone=1&retURL=%2F{!Account.Id}
  • Click on Save
  • Now add Clone button in layout.
Let's disccuss something about this URL 
https://ap1.salesforce.com/{!Account.id}/e?clone=1&retURL=%2F{!Account.Id}

Red color text represent your instance name-
e- Edit mode-Record will open in edit mode

Visualforce Displaying Image in Pdf

I have come across a scenario image is not appearing in pdf  sometimes.For this I have shared some tricks.
It is very easy to display an image in Visulaforce page.
Process
  • Crate a static resource and store that image
  • Click in View file link 
  • Copy the url
  • Add apex:image tag in vf page.
 <apex:image url = "https://ap1.salesforce.com/resource/logo"  width="180" height="60" />
Image will be displayed. When you render that page as pdf then sometimes image will not be appear.
To appear image every time, I have done some work around and I would love to share it. 

Lets talk about the image url --- "https://ap1.salesforce.com/resource/1380178695000/logo".
All must be familiar with each term except this 1380178695000. What is that value?
This is nothing but the lastmodifiedtime of static resource.1380178695000 must be dynamic. To get dynamic value I have used some function SystemModStamp.

Here is my page and Controller.
<apex:page controller="ImageController" renderAs="pdf" >
  <table>
        <tr>
            <td>
              <div>
                 <apex:image value="{!sLogo}"  width="180" height="60" />
                 <!--<apex:image url="https://ap1.salesforce.com/resource/logo" width="180" height="60" />-->
              </div>
            </td>
        </tr>
    </table>

</apex:page>

Controller is 
public with sharing class ImageController {
    public String sLogo {get;set;}
    public ImageController(){
        list<StaticResource> listOfStaticResources = [SELECT Id,SystemModStamp
                                                      FROM StaticResource
                                                      WHERE Name = 'logo'];
                              
        if(!listOfStaticResources.isEmpty()) {
          sLogo = '/resource/'+listOfStaticResources[0].SystemModStamp.getTime()+'/logo';
        
           System.debug('Printing after slogo'+sLogo ); 
        } else {
            //sLogo = (invoiceit_s__Configuration__c.getValues('COMPANY_LOGO').invoiceit_s__String_Value__c);
        }
    }
}
Now image will appear in pdf all time.

VisualForce Charting in Salesforce

As salesforce has given us the functionality of report and dashboard to create chart then what is the use of visualforce charting?.
In some situations existing functionality of salesforce can not meet our requirement properly . Suppose there is a requirement to compose custom pages that combine charts and data tables in ways that are more useful to our organization.In that case visual force charting is useful.There are also other way to meet this requirement. We can use Google chart Api for this.In my previous post I have explained.
Visualforce charting gives you an easy way to create customized business charts, based on data sets you create directly from SOQL queries, or by building the data set in your own Apexcode. By combining and configuring individual data series, you can compose charts that display your data in ways meaningful to your organization.
Visualforce charts are rendered client-side using JavaScript. This allows charts to be animated and visually exciting, and chart data can load and reload asynchronously, which can make the page feel more responsive.
This is the my page and controller. 
<apex:page controller="OppsControllernew" tabStyle="Account">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection title="Chart With Table">
                <apex:outputPanel style="float:left;">
                    <apex:chart data="{!Opportunities}" width="500" height="250">
                        <apex:axis type="Numeric" position="left" fields="Amount" title="Amount"/>
                        <apex:axis type="Category" position="bottom" fields="Name" title="Name"/>
                            
                        <apex:barSeries orientation="horizontal" axis="left" xField="Amount" yField="Name"/>
                        <!--<apex:pieSeries dataField="amount" labelField="name"/>-->
                        <apex:legend position="right"/>
                    </apex:chart>
                
                    <apex:chart data="{!Opportunities}" width="500" height="250">
                        <apex:axis type="Category" position="bottom" fields="Name" title="Name" />
                        <apex:axis type="Numeric" position="left" fields="Amount" title="Amount" grid="true"/>
                        <apex:lineSeries axis="left" fill="true"  xField="Name" yField="Amount"  markerType="cross" markerSize="4" markerFill="#FF0000"/>
                  </apex:chart>
                </apex:outputPanel>
              
               <apex:outputPanel style="float:right;margin-right:4cm;height:600px;width:400px;" >
                 <p><b> Opportunity Table</b></p><br/>
                 <apex:pageBlockTable value="{!Opportunities}" var="opp">
                    <apex:column headerValue="Opportunity" value="{!opp.Name}"/>
                    <apex:column headerValue="Amount" value="{!opp.amount}"/>
                    <apex:column headerValue="Created Date" value="{!opp.createddate}" style="width:80px"/>
                </apex:pageBlockTable>
            </apex:outputPanel>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>
My controller is 

public class OppsControllernew {

    
    // Get a set of Opportunities 
    
    public ApexPages.StandardSetController setCon {
        get {
            if(setCon == null) {
                setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
                      [SELECT Name, Type,createddate, Amount, Closedate FROM Opportunity]));
                setCon.setPageSize(5);
            }
            return setCon;
        }
        set;
    }
    
    public List<Opportunity> getOpportunities() {
         return (List<Opportunity>) setCon.getRecords();
    }

}

Visualforce chart binds to the source of its data through the data attribute on the <apex:chart> component.

Here data source is sObjects that is Opportunity.
Data can be 

  • Name of java script function
  •  Non-Salesforce data sources by building a JavaScript array
  • Apex wrapper objects
The object field names used as data attributes are case-sensitive in JavaScript while field names in Apex and Visualforce are case-insensitive. Be careful to use the precise field name in the fields, xField, and yField attributes of axes and data series components, or your chart will silently fail.Make sure all the name perfectly equal between fields , xFields and yFields.
Limitations Of Visualforce Charting 
  • Visualforce charts only render in browsers which support scalable vector graphics (SVG).
  • Visualforce charts won’t display in pages rendered as PDFs
  • Dynamic (Apex-generated) charting components are not supported at this time
Now the final out put will be like this 

Creating charst in Visualforce page by using JavaScript Remoting & Google Charts API.

This post is all about how to draw a chart in Visual force page by using JavaScript Remoting & Google Charts API.
I had faced some requirement to draw a different types of chart in a visualforce page and also to display number of  distinct record for further reference. I had done some work around and finally I had reached to the final destination. Here I have created one object ChartObject__c and two field Name and Amount.
Here I am sharing some code snippet for your reference. 

Page:

<apex:page controller="GoogleChartsController" sidebar="false">

    <!-- Google API inclusion -->
    <apex:includeScript id="a" value="https://www.google.com/jsapi" />
    <apex:sectionHeader title="Google Charts + Javascript Remoting" subtitle="Demoing - Opportunities by Exepected Revenue"/> 
    
    <!-- Google Charts will be drawn in this DIV -->
    <div id="chartBlock"/>
    <div id="chartBlockpie"/>
    <div id="chartBlockline"/>
    <div id="chartBlockbar" />
    <div id="chartBlockgauge" />
     
    <script type="text/javascript">
     
  // Load the Visualization API and the piechart package.
  google.load('visualization', '1.0', {'packages':['corechart']});

   // Set a callback to run when the Google Visualization API is loaded.
  google.setOnLoadCallback(initCharts);

  function initCharts() {   
  
   // Following the usual Remoting syntax
   // [<namespace>.]<controller>.<method>([params...,] 
   //<callbackFunction>(result, event) {...}
   // namespace : 
   // controller : GoogleChartsController
  // method : loadOpps
   
  GoogleChartsController.loadOpps(
    function(result, event){ 
    
     // load Column chart
     var visualization = new google.visualization.ColumnChart(document.getElementById('chartBlock'));
    
     // Prepare table model for chart with columns
     var data = new google.visualization.DataTable();
     data.addColumn('string', 'Name');
     data.addColumn('number', 'Amount');  
      
     // add rows from the remoting results
     for(var i =0; i<result.length;i++){
      var r = result[i];
      data.addRow([r.Name, r.Amount]);
     }
     var chart = new google.visualization.PieChart(document.getElementById('chartBlockpie'));
     chart.draw(data, result);
      
     var chart = new google.visualization.LineChart(document.getElementById('chartBlockline'));
     chart.draw(data, result);
    
     var chart = new google.visualization.BarChart(document.getElementById('chartBlockbar'));
     chart.draw(data, result);
     
     /*var chart = new google.visualization.ScatterChart(document.getElementById('chartBlockscater'));
     chart.draw(data, result);*/
     
     var chart = new google.visualization.GaugeChart(document.getElementById('chartBlockgauge'));
     chart.draw(data, result);
      
     // all done, lets draw the chart with some options to make it look nice.
     visualization.draw(data, {legend : {position: 'top', textStyle: {color: 'blue', fontSize: 10}}, width:window.innerWidth,vAxis:
             {textStyle:{fontSize: 10}},hAxis:{textStyle:{fontSize: 10},showTextEvery:1,slantedText:false}});
         },{escape:true});
      }
       </script>
    <p>Total Different Kind Of Production:<apex:outputText value="{!totalvalue}"/></p>
</apex:page>

Controller:

global with sharing class GoogleChartsController {
    public Integer totalvalue{get;set;}
    public GoogleChartsController() {        
        // Integer totalvalue;
        list<AggregateResult>  Namecount=new List<AggregateResult>();
        Namecount= [select  COUNT_DISTINCT(Amount) ctr from Opportunity];
        for(AggregateResult sobj:Namecount){
            
            totalvalue=Integer.valueOf(sobj.get('ctr'));
        }
        System.debug('################asish####################'+totalvalue);
    } 
    
    /**
Loads most recent 10 Opportunities
*/
    @RemoteAction   
    global static Opportunity[] loadOpps() {        
        return  [select Id, Name, Amount from Opportunity  order by CreatedDate DESC limit 10];        
    }  
}

Here I am sharing some image regarding chart.