Sunday 21 September 2014

Change background color in visualforce page.

Now we create a color picker in visualforce page.Which is help to change the background color of visualforce page.

<apex:page showHeader="false">

  <script>
      function changeColor(inputID){
              var inputValue = document.getElementById(inputID).value;
              return ( document.body.style.backgroundColor =[document.getElementById(inputID).value]);
      }
      function focus(){
              j$("[id$=loading-curtain-div]").css("background-color", "blue").css("opacity", 0.35);
      }
  </script>

      <style>
             .ash_gray{ background-color:#666362; color:white;  }
      </style>

     <apex:sectionHeader title="Color codes" subtitle="Pick Color">
         </apex:sectionHeader>      
       
           <apex:pageBlock >
               <apex:form id="myform" >
                  <div id="loading-curtain-div"/>
                     <apex:pageBlockSection columns="2" id="mypageblockSection">
                         <apex:outputText value="Ash Gray:" style="font-size:15px;"/>
                              <apex:commandButton id="cmd1" onclick="changeColor('{!$Component.cmd1}')" onmouseout="focus();"  reRender="myform" value="#666362" style="background:#666362;width:80px" />
                         <apex:outputText value="Slate Bliue:" style="font-size:15px;"/>
                              <apex:commandButton id="cmd2" onclick="changeColor('{!$Component.cmd2}')" reRender="myform" value="#737CA1" style="background:#737CA1;width:80px" />
                         <apex:outputText value="Blue Jay:" style="font-size:15px;"/>
                              <apex:commandButton id="cmd3" onclick="changeColor('{!$Component.cmd3}')" reRender="myform" value="#2B547E" style="background:#2B547E;width:80px"/>
                         <apex:outputText value="Blue Hosta:" style="font-size:15px"/>
                              <apex:commandButton id="cmd4" onclick="changeColor('{!$Component.cmd4}')" reRender="myform" value="#77BFC7" style="background:#77BFC7;width:80px"/>      
                         <apex:outputText value="Light Sea Green:" style="font-size:15px "/>
                              <apex:commandButton id="cmd5" onclick="changeColor('{!$Component.cmd5}')" reRender="myform" value="#3EA99F" style="background:#3EA99F; width:80px"/>
                         <apex:outputText value="Dark Turquoise:" style="font-size:15px"/>
                              <apex:commandButton id="cmd6" onclick="changeColor('{!$Component.cmd6}')" reRender="myform" value="#3B9C9C" style="background:#3B9C9C;width:80px"/>
                         <apex:outputText value="Sea Turtle Green:" style="font-size:15px"/>
                              <apex:commandButton id="cmd7" onclick="changeColor('{!$Component.cmd7}')" reRender="myform" value="#438D80" style="background:#438D80;width:80px"/>
                         <apex:outputText value="Coffee:" style="font-size:15px;"/>
                              <apex:commandButton id="cmd8" onclick="changeColor('{!$Component.cmd8}')" reRender="myform" value="#827B60" style="background:#827B60;width:80px"/>
                         <apex:outputText value="Plum Purple:" style="font-size:15px"/>
                              <apex:commandButton id="cmd9" onclick="changeColor('{!$Component.cmd9}')" reRender="myform" value="#6F4E37" style="background:#6F4E37;width:80px"/>
                         <apex:outputText value="Plum Velvet:" style="font-size:15px"/>
                              <apex:commandButton id="cmd10" onclick="changeColor('{!$Component.cmd10}')" reRender="myform" value="#7D0552" style="background:#7D0552;width:80px"/>
                         <apex:outputText value="Army Brown:" style="font-size:15px"/>
                               <apex:commandButton id="cmd11" onclick="changeColor('{!$Component.cmd11}')" reRender="myform" value="#5E5A80" style="background:#5E5A80;width:80px"/>
                         <apex:outputText value="Plum Purple:" style="font-size:15px"/>
                               <apex:commandButton id="cmd12" onclick="changeColor('{!$Component.cmd12}')" reRender="myform" value="#583759" style="background:#583759;width:80px"/>
             </apex:pageBlockSection>
         </apex:form>
    </apex:pageBlock>
 
</apex:page>

How to Print The Current Visualforec Page with the help of JavaScript.

There is a method name is Window.print() in JavaScript.
The print() method opens the Print Dialog Box, which lets the user to select preferred printing options.

So, In visualforce page we use this method in commandButton's onclick attribute.


<apex:commandButton onclick="window.print()" value="Print"/>


Simple and after clicking on Print button the print method prints the contents of the current Visualforce page.

Custom Exception in Salesforce

public class CustomExceptionClass {
   
// define custom exception with extend the built-in Exception class
// And make sure your class name ends with the word Exception,
// else you get Compile Error: Invalid type

class MyException extends Exception{

    //Override the getMessage method of Exception class to show you custom Error
  override public String getMessage(){
  return 'The Show is HouseFull, No more Tickets are available';
  }

}

// declare custom exception variable
        MyException myExceptionVar = null;
   
 //Constractor of OuterClass
        public CustomExceptionClass(){
            // create object of Custom Exception class
            myExceptionVar = new MyException();

        }

        Integer TotalTickets = 5; // define some custom limit for error condition
 // Define some person name who booked ticket
        List<String> PersonName = new String[]{'Harry','Ron','Hermione'};  

        public Boolean addPerson(String newPersonName){ // Add another person
            Boolean TicketBooked = false;
         
            //use try Catch for Exception
            try{  
                    //Check the List
            if(PersonName.size() >= TotalTickets) // If return True then throw Exception
           throw myExceptionVar;
                    // Throw Exception it'll show the error which we written in getMessage
               
                else //Else Add the Person name
                PersonName.add(newPersonName);

                TicketBooked = true;

            }
            //Catch block
            catch(Exception e){
                TicketBooked = false;
                System.debug('we are in catch block');
                System.debug(e.getMessage());
            }
            finally{
             
                if(TicketBooked)
                System.debug('Ticket Booked successfully');
                else
                System.debug('Booking failed');
               }
               return TicketBooked ;

        }
}


// Execute Following

CustomExceptionClass a = new CustomExceptionClass();
//Current list size is 3  ('Harry','Ron','Hermione') and limit is 5 so we can add two more

a.addPerson('Viru'); // Ticket Booked Successfully
a.addPerson('Emma'); // Ticket booked Successfully

//current list size id 5  and limit is 5 so we are not good
a.addPerson('Draco');  //Booking failed 

Tuesday 16 September 2014

BODMAS Rule

B → Brackets first (parentheses)

→ Of (orders i.e. Powers and Square Roots, Cube Roots, etc.)

DM  Division and Multiplication (start from left to right)

AS → Addition and Subtraction (start from left to right)

Note:

(i) Start Divide/Multiply from left side to right side since they perform equally.

(ii) Start Add/Subtract from left side to right side since they perform equally.

Steps to simplify the order of operation using BODMAS rule:

First part of an equation is start solving inside the 'Brackets'.

For Example; (6 + 4) × 5
First solve inside ‘brackets’ 6 + 4 = 10, then 10 × 5 = 50.


Next solve the mathematical 'Of'.

For Example; 3 of 4 + 9
First solve ‘of’ 3 × 4 = 12, then 12 + 9 = 21.


Next, the part of the equation is to calculate 'Division' and 'Multiplication'.
We know that, when division and multiplication follow one another, then their order in that part of the equation is solved from left side to right side.

For Example; 15 ÷ 3 × 1 ÷ 5

Multiplication’ and ‘Division’ perform equally, so calculate from left to right side. First solve 15 ÷ 3 = 5, then 5 × 1 = 5, then 5 ÷ 5 = 1.


In the last part of the equation is to calculate 'Addition' and 'Subtraction'. We know that, when addition and subtraction follow one another, then their order in that part of the equation is solved from left side to right side.

For Example; 7 + 19 - 11 + 13

Addition’ and ‘Subtraction’ perform equally, so calculate from left to right side. First solve 7 + 19 = 26, then 26 - 11 = 15 and then 15 + 13 = 28.

These are simple rules need to be followed forsimplifying or calculating using BODMAS rule.


In brief, after we perform "B" and "O", start from left side to right side by solving any "D"or "M" as we find them. Then start from left side to right side solving any "A" or "S" as we find them.

How to use BODMAS rule

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        String orgString = "(3+4)*(7/2)";
        System.out.println(findValueInBraces(orgString));

    }

    public static String findValueInBraces(String finalStr) {

       while (finalStr.contains("(") && finalStr.contains(")")) {

            int fIndex = finalStr.indexOf("(");
            int nIndex = finalStr.indexOf(")");
            String subString = finalStr.substring(fIndex + 1, nIndex);
            

            finalStr = finalStr.substring(0, fIndex) + calculate(subString) + finalStr.substring(nIndex +1, finalStr.length());
        }
        return calculate(finalStr);

    }

    public static String calculate(String finalString) {

        while (finalString.contains("(") && finalString.contains(")")) {
            findValueInBraces(finalString);
        }
        while (!isNum(finalString)) {
            List<Integer> positions = getOperandPosition(finalString);
            int pos = positions.get(0);
            if (positions.size() >= 2 && positions.get(1) != null) {
                int nxtPos = positions.get(1);
                finalString = getValue(finalString.substring(0, nxtPos), pos)
                        + finalString.substring(nxtPos, finalString.length());
            } else {
                finalString = getValue(
                        finalString.substring(0, finalString.length()), pos);
            }
        }
        return finalString;

    }

    public static boolean isNum(String str) {
        if (str.contains("+") || str.contains("-") || str.contains("*")
                || str.contains("/")) {
            return false;
        }
        return true;
    }

    public static List<Integer> getOperandPosition(String str) {

        List<Integer> integers = new ArrayList<Integer>();

        if (str.contains("+")) {
            integers.add(str.indexOf("+"));
        }

        if (str.contains("-")) {
            integers.add(str.indexOf("-"));
        }

        if (str.contains("*")) {
            integers.add(str.indexOf("*"));
        }

        if (str.contains("/")) {
            integers.add(str.indexOf("/"));
        }

        Collections.sort(integers);
        return integers;
    }

    public static String getValue(String str, int pos) {
        double finalVal = 0;
        double a = Double.parseDouble(str.substring(0, pos));
        double b = Double.parseDouble(str.substring(pos + 1, str.length()));
        char c = str.charAt(pos);

        if (c == '*') {
            finalVal = a * b;
        } else if (c == '/') {
            finalVal = a / b;
        } else if (c == '+') {
            finalVal = a + b;
        } else if (c == '-') {
            finalVal = a - b;
        }
        return String.valueOf(finalVal);
    }
}

Wednesday 10 September 2014

Pagination in Visualforce Page (Add Next, Previous button on Visualforce page )

Here is some code snippet for the Pagination in Visualforce page.
We have to use StandardSetController for that.

Here we go-
Visualforce page: 

<apex:page controller="Pagination_min">
<apex:form >
    <apex:pageBlock >
        <apex:pageBlockSection columns="1" >
            <apex:pageBlockTable value="{!accounts}" var="a">
               <apex:column value="{!a.Name}"/>
                <apex:column value="{!a.Type}"/>
                <apex:column value="{!a.BillingCity}"/>
                <apex:column value="{!a.BillingState}"/>
                <apex:column value="{!a.BillingCountry}"/>
            </apex:pageBlockTable>
            <apex:panelGrid columns="7">
            <apex:commandButton value="|<" action="{!setcon.first}" disabled="{!!setcon.hasPrevious}" title="First page"/>
            <apex:commandButton value="<" action="{!setcon.previous}" disabled="{!!setcon.hasPrevious}" title="Previous page"/>
            <apex:commandButton value=">" action="{!setcon.next}" disabled="{!!setcon.hasNext}" title="Next page"/>
            <apex:commandButton value=">|" action="{!setcon.last}" disabled="{!!setcon.hasNext}" title="Last page"/>
           
             <apex:outputText >{!(setCon.pageNumber * size)+1-size}   -    {!IF((setCon.pageNumber * size)>noOfRecords, noOfRecords,(setCon.pageNumber * size))} of {!noOfRecords}</apex:outputText>
                <apex:commandButton value="Refresh" action="{!refresh}" title="Refresh Page"/>
             
            </apex:panelGrid>
        </apex:pageBlockSection>
    </apex:pageBlock>
</apex:form>
 

</apex:page>



Custom Controller-

public class Pagination_min {

    Public Integer noofRecords {get; set;}
    public integer size {get; set;}
   
    public Apexpages.standardsetController setcon{
        get{
            if(setCon == null){
                size = 10;
                String queryString = 'Select Name, Type, BillingCity, BillingState, BillingCountry from Account order by Name';
                setcon = new apexpages.standardsetController(Database.getquerylocator(queryString));
                setcon.setpagesize(size);
                noofRecords = setcon.getResultsize();
            }
            return setcon;
        }
         set;
    }
    Public list<Account> getAccounts(){
        list<Account> acclist = new list<Account>();
         for(Account ac : (list<Account>)setcon.getrecords()){
             acclist.add(ac);
         }
        return accList;
       
     
    }
   
    Public PageReference Refresh(){
       
        setcon=null;
        getAccounts();
        setcon.setpageNumber(1);
       
        return null;
    }
}


Just copy and paste this code and BOOM First, Next, Previous and Last buttons are start doing there work.