Monday, September 30, 2013

Submit a Form with the Enter Key


Problem

You've created a form in Visualforce. When pushing enter while using the form, the page refreshes instead of submitting your form. It's an easy fix with a small bit of JavaScript, which does wonders for your app's user experience.

Solution

In your Visualforce page, define this JavaScript function. It intercepts key presses on your form elements.

01<script type='text/javascript'>
02    function noenter(ev)  {
03        if (window.event && window.event.keyCode == 13 || ev.which == 13) {
04            doSearchAF();
05            return false;
06         } else {
07              return true;
08         }
09     }
10</script>           

Also, define this ActionFunction and tie it to your submit method in your controller.

1<apex:actionFunction name='doSearchAF' action='{!doSearch}' />

Lastly, this 'onkeypress' event should be added to every textual form element that should intercept a press of the enter key.

1<apex:inputtext value='{!settings.searchStr}' id='searchStr' styleclass='searchStr' onkeypress='return noenter(event);' />

Discussion

Make sure the ActionFunction name matches up with the JavaScript function you're calling from noEnter(). When someone hits Enter, the noEnter() JavaScript function will get called, which in turn will call the doSearchAF ActionFunction, which invokes your forms submit action, in this case doSearch().

How to Hide the Current Date Link on an Inputfield

Problem

The standard apex:inputfield component for a date field generates a link next to the input field, taking a lot of space. The link allows someone to easily enter the current date. However, when you use multiple date fields within a table component, it can be confusing for the user to have these extra links (see Screenshots). This recipe solves this by creating a Visualforce component that uses CSS to remove the link.

Screenshots

Default Behavior: Current date link is rendered

Note the extra links next to each and every date field.
 Modified Behavior: Using a Visualforce component to remove the current date link

As you can see, this is a much more compact view.

Visualforce Component Code

Here's the code for the Visualforce component. It wraps the component body in an HTML div tag, and adds styling to hide a part of that wrapped component.

 <apex:component access="global">  
   <style>  
     div.hideCurrDate span.dateInput span.dateFormat{  
     display:none;  
     }  
   </style>  
   <div class="hideCurrDate">  
   <apex:componentBody />  
    </div>  
 </apex:component>  

How to use the component

Here's a simple Visualforce page to demonstrate component usage:

 <apex:page standardController="Opportunity">  
    <apex:form>  
    <apex:pageBlock>  
     <apex:pageBlockSection>  
     <c:noDateLink>  
      <apex:inputField value="{!Opportunity.CloseDate}"/>  
     <c:noDateLink>  
     </apex:pageBlockSection>  
    </apex:pageBlock>  
    </apex:form>  
  </apex:page>  

Discussion
This code is dependent on the standard salesforce look and feel - and in particular dependent on it not changing. By examining the standard CSS, we know that the current date link is in a span.dateInput span.dateFormat CSS element. So this may be a little fickle depending on UI changes - but it should be easy to change if the standard UI CSS does ever change.

Enjoy.....!!

Friday, September 27, 2013

Most Important OnLine Tool for Coding and Decoding(i.e.,For Conversion)

Coder's Tool Box:

The Coder’s Toolbox contains all the little tools you never know where to find.
  • Time conversion – convert between Unix timestamp, ISO8601 and RFC 2822 formats
  • String conversion – encode/decode Base64-encoding; escape XML, URL's and ECMAScript; translate to UTF-8
  • Number conversion – convert between decimal, hexadecimal, octal and binary numbers
  • Network – calculate netmasks, broadcast addresses and do DNS lookups
  • Bandwidth – calculate the duration of file transfer
  • XPath debugger – test your XPath expressions
For more information please visit the below link

http://coderstoolbox.net/string/#!encoding=base64&action=encode&charset=iso_8859_1

Displaying Selected Records Below With Help of Action Support Function

Scenario:
       I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.


VisualForce Page:

<apex:page controller="wrapperClassController">
  <apex:form >
    <apex:pageBlock >
      <!-- In our table we are displaying the cContact records -->
      <apex:pageBlockTable value="{!contacts}" var="c" >
         <apex:column >
            <apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
              <!-- This is our selected Boolean property in our wrapper class -->
                <apex:inputCheckbox value="{!c.selected}" />
            </apex:actionSupport>
         </apex:column>
         <!-- This is how we access the contact values within our cContact container/wrapper -->
         <apex:column value="{!c.con.Name}" />
         <apex:column value="{!c.con.Email}" />
         <apex:column value="{!c.con.Phone}" />
       </apex:pageBlockTable>

    </apex:pageBlock>
      <apex:pageBlock id="test">
        <apex:outputPanel id="pbt2">
          Total No of Selected Records :<apex:outputText value="{!value }"/>
          <apex:pageBlockTable value="{!SelectedContacts}" var="c" >
             <apex:column value="{!c.Name}" />
             <apex:column value="{!c.Email}" />
             <apex:column value="{!c.Phone}" />
          </apex:pageBlockTable>
        </apex:outputPanel>
      </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Class:

public class wrapperClassController
{
 //Our collection of the class/wrapper objects cContact
 public List<cContact> contactList {get; set;}
 public List<Contact> selectedContacts{get;set;}
 public Integer value {get;set;}

 public List<cContact> getContacts()

 {
  if(contactList == null) {
   contactList = new List<cContact>();
   for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
   {
     //As each contact is processed we create a new cContact object and add it to the contactList
     contactList.add(new cContact(c));
   }
  }
  return contactList;
 } 

 public PageReference processSelected()
 {
   //We create a new list of Contacts that we be populated only with Contacts if they are selected
   selectedContacts = new List<Contact>();

   //We will cycle through our list of cContacts and will check to see if the selected
   //property is set to true, if it is we add the Contact to the selectedContacts list


   for(cContact cCon : getContacts())
    {
      if(cCon.selected == true)
      {
       selectedContacts.add(cCon.con);
      }
    }
   value = selectedContacts.size();
   System.debug('printing listcontc'+selectedContacts.size());

   // Now we have our list of selected contacts and can perform any type of logic we want,
   // sending emails, updating a field on the Contact, etc

   return null;
 }
   
 //This is our wrapper/container class. A container class is a class,a data structure,or an
 //abstract data type whose instances are collections of other objects. In this example a
 //wrapper class contains both the standard salesforce object Contact and a Boolean value


 public class cContact
 {
  public Contact con {get; set;}
  public Boolean selected {get; set;}

  //This is the contructor method. When we create a new cContact object we pass a Contact
  //that is set to the con property. We also set the selected value to false

  public cContact(Contact c)
      {
            con = c;
            selected = false;
        }
    }
}

ScreenShot:



Displaying Selected Records Below With Help of Action Support Function

Scenario:
       I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Action Support Function.


VisualForce Page:

<apex:page controller="wrapperClassController">
  <apex:form >
    <apex:pageBlock >
      <!-- In our table we are displaying the cContact records -->
      <apex:pageBlockTable value="{!contacts}" var="c" >
         <apex:column >
            <apex:actionSupport event="onclick" action="{!processSelected}" reRender="pbt2">
              <!-- This is our selected Boolean property in our wrapper class -->
                <apex:inputCheckbox value="{!c.selected}" />
            </apex:actionSupport>
         </apex:column>
         <!-- This is how we access the contact values within our cContact container/wrapper -->
         <apex:column value="{!c.con.Name}" />
         <apex:column value="{!c.con.Email}" />
         <apex:column value="{!c.con.Phone}" />
       </apex:pageBlockTable>

    </apex:pageBlock>
      <apex:pageBlock id="test">
        <apex:outputPanel id="pbt2">
          Total No of Selected Records :<apex:outputText value="{!value }"/>
          <apex:pageBlockTable value="{!SelectedContacts}" var="c" >
             <apex:column value="{!c.Name}" />
             <apex:column value="{!c.Email}" />
             <apex:column value="{!c.Phone}" />
          </apex:pageBlockTable>
        </apex:outputPanel>
      </apex:pageBlock>
    </apex:form>
</apex:page>

Controller Class:

public class wrapperClassController
{
 //Our collection of the class/wrapper objects cContact
 public List<cContact> contactList {get; set;}
 public List<Contact> selectedContacts{get;set;}
 public Integer value {get;set;}

 public List<cContact> getContacts()

 {
  if(contactList == null) {
   contactList = new List<cContact>();
   for(Contact c : [select Id, Name, Email, Phone from Contact limit 10])
   {
     //As each contact is processed we create a new cContact object and add it to the contactList
     contactList.add(new cContact(c));
   }
  }
  return contactList;
 } 

 public PageReference processSelected()
 {
   //We create a new list of Contacts that we be populated only with Contacts if they are selected
   selectedContacts = new List<Contact>();

   //We will cycle through our list of cContacts and will check to see if the selected
   //property is set to true, if it is we add the Contact to the selectedContacts list


   for(cContact cCon : getContacts())
    {
      if(cCon.selected == true)
      {
       selectedContacts.add(cCon.con);
      }
    }
   value = selectedContacts.size();
   System.debug('printing listcontc'+selectedContacts.size());

   // Now we have our list of selected contacts and can perform any type of logic we want,
   // sending emails, updating a field on the Contact, etc

   return null;
 }
   
 public List<Contact> getSelectedContacts()
 {
  System.debug('printing listcontc inside get'+selectedContacts.size());
  if(selectedContacts.size()>0)
     return selectedContacts;
  else return null;
 }

 //This is our wrapper/container class. A container class is a class,a data structure,or an
 //abstract data type whose instances are collections of other objects. In this example a
 //wrapper class contains both the standard salesforce object Contact and a Boolean value


 public class cContact
 {
  public Contact con {get; set;}
  public Boolean selected {get; set;}

  //This is the contructor method. When we create a new cContact object we pass a Contact
  //that is set to the con property. We also set the selected value to false

  public cContact(Contact c)
      {
            con = c;
            selected = false;
        }
    }
}

ScreenShot:



Thursday, September 26, 2013

Displaying Selected Records Below Using Command Button

Scenario:

    I want to retrieve few records from a particular object and to display them in a Page Block Table along with checkbox for each row in a Table .Now,I will select few records from that table and I will display them in below PageBlock Table with the help of Command Button.

VisualForce Page :

 
<apex:page controller="wrapperClassController">
    <apex:form >
         <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="test"/>
            </apex:pageBlockButtons>
        <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" >
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!c.selected}"/>
                </apex:column>
            <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>


        </apex:pageBlock>
        <apex:pageBlock id="test">
        Total No of Selected Records :<apex:outputText value="{!value }"/>
            <apex:pageBlockTable value="{!SelectedContacts}" var="c" >
                <apex:column value="{!c.Name}" />
                <apex:column value="{!c.Email}" />
                <apex:column value="{!c.Phone}" />
            </apex:pageBlockTable>
            
        </apex:pageBlock>
    </apex:form>
</apex:page> 
 
 
 
Apex Class: 

public class wrapperClassController 
{
 //Our collection of the class/wrapper objects cContact 
 public List<cContact> contactList {get; set;}
 public List<Contact> selectedContacts{get;set;}
 public Integer value {get;set;} 
 public List<cContact> getContacts() 
 {
  if(contactList == null) {
   contactList = new List<cContact>();
   for(Contact c : [select Id, Name, Email, Phone from Contact limit 10]) 
   {
   //As each contact is processed we create a new cContact object and add it to the contactList
   contactList.add(new cContact(c));
   }
  }
  return contactList;
 }  
public PageReference processSelected()
 {
  //We create a new list of Contacts that we be populated only with Contacts if they are selected 
   selectedContacts = new List<Contact>();

  //We will cycle through our list of cContacts and will check to see if the selected 
  //property is set to true, if it is we add the Contact to the selectedContacts list 
   for(cContact cCon : getContacts()) {
    if(cCon.selected == true) {
       selectedContacts.add(cCon.con);
        }
    }
   value = selectedContacts.size();
   System.debug('printing listcontc'+selectedContacts.size());
   // Now we have our list of selected contacts and can perform any type of logic we want,
   // sending emails, updating a field on the Contact, etc 
   return null;
 }
    
public List<Contact> getSelectedContacts()
{
 System.debug('printing listcontc inside get'+selectedContacts.size());
 if(selectedContacts.size()>0)
     return selectedContacts;
 else return null;
}
 //This is our wrapper/container class. A container class is a class,a data structure,or an
 //abstract data type whose instances are collections of other objects. In this example a 
 //wrapper class contains both the standard salesforce object Contact and a Boolean value 
public class cContact 
{
 public Contact con {get; set;}
 public Boolean selected {get; set;}
 //This is the contructor method. When we create a new cContact object we pass a Contact 
 //that is set to the con property. We also set the selected value to false 
 
 public cContact(Contact c) {
            con = c;
            selected = false;
        }
    }
}

Monday, September 23, 2013

XML NameSpaces in SalesForce

XML NameSpaces:
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />
  In the following example, the XML element has two attributes:
  • The first attribute has a key of dimension; the value is 2.
  • The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

 For more information regarding XML Namespaces Please visit the below link
 http://www.xmlmaster.org/en/article/d01/c10/

Friday, September 20, 2013

Document Class in Salesforce

Document Class:


Use the Document class to process XML content. One common application is to use it to create the body of a request for HttpRequest or to parse a response accessed by HttpResponse.


Methods

The Document class has the following methods:
NameArgumentsReturn TypeDescription
createRootElementString name
String namespace
String prefix
Dom.XmlNodeCreates the top-level root element for a document.
The name argument can't have a null value.
If the namespace argument has a non-null value and the prefix argument is null, the namespace is set as the default namespace.
If the prefix argument is nullSalesforce automatically assigns a prefix for the element. The format of the automatic prefix is nsi, where i is a number.
If the prefix argument is '', the namespace is set as the default namespace.
For more information about namespaces, see XML Namespaces.
Calling this method more than once on a document generates an error as a document can have only one root element.
getRootElementDom.XmlNodeReturns the top-level root element node in the document. If this method returns null, the root element has not been created yet.
loadString xmlVoidParse the XML representation of the document specified in the xml argument and load it into a document. For example:
Dom.Document doc = new Dom.Document();
doc.load(xml);
toXmlStringStringReturns the XML representation of the document as a String.



Example:

For the purposes of the sample below, assume that the url argument passed into the parseResponseDom method returns this XML response:

<address>
    <name>Kirk Stevens</name>
    <street1>808 State St</street1>
    <street2>Apt. 2</street2>
    <city>Palookaville</city>
    <state>PA</state>
    <country>USA</country>
</address>

The following example illustrates how to use DOM classes to parse the XML response returned in the body of a GET request:
public class DomDocument {
 
    // Pass in the URL for the request
    // For the purposes of this sample,assume that the URL
    // returns the XML shown above in the response body
    public void parseResponseDom(String url){
        Http h = new Http();
        HttpRequest req = new HttpRequest();
        // url that returns the XML in the response body
        req.setEndpoint(url);
        req.setMethod('GET');
        HttpResponse res = h.send(req);
        Dom.Document doc = res.getBodyDocument();
        
        //Retrieve the root element for this document.
        Dom.XMLNode address = doc.getRootElement();
        //getChildElement() method is present in XML Node Class
        String name = address.getChildElement('name', null).getText();
        String state = address.getChildElement('state', null).getText();
        // print out specific elements
        System.debug('Name: ' + name);
        System.debug('State: ' + state);
        
        // Alternatively, loop through the child elements.
        // This prints out all the elements of the address
        for(Dom.XMLNode child : address.getChildElements()) {
           System.debug(child.getText());
        }
    }
}
XML NameSpaces:
An XML namespace is a collection of names identified by a URI reference and used in XML documents to uniquely identify element types and attribute names. Names in XML namespaces may appear as qualified names, which contain a single colon, separating the name into a namespace prefix and a local part. The prefix, which is mapped to a URI reference, selects a namespace. The combination of the universally managed URI namespace and the document's own namespace produces identifiers that are universally unique.
The following XML element has a namespace of http://my.name.space and a prefix of myprefix.
<sampleElement xmlns:myprefix="http://my.name.space" />
  In the following example, the XML element has two attributes:
  • The first attribute has a key of dimension; the value is 2.
  • The second attribute has a key namespace of http://ns1; the value namespace is http://ns2; the key is foo; the value is bar.
<square dimension="2" ns1:foo="ns2:bar" xmlns:ns1="http://ns1" xmlns:ns2="http://ns2" />

 For more information regarding XML Namespaces Please visit the below link
 http://www.xmlmaster.org/en/article/d01/c10/

XML Node Class in Salesforce



XmlNode Class:

Use the XmlNode class to work with a node in an XML document. The DOM represents an XML document as a hierarchy
of nodes. Some nodes may be branch nodes and have child nodes, while others are leaf nodes with no children.

Node Types:
There are different types of DOM nodes available in Apex. XmlNodeType is an enum of these different types. The values
are:
• COMMENT
• ELEMENT
• TEXT

It is important to distinguish between elements and nodes in an XML document. The following is a simple XML example:

<name>
<firstName>Suvain</firstName>
<lastName>Singh</lastName>
</name>

This example contains three XML elements: name, firstName, and lastName. It contains five nodes: the three name,
firstName, and lastName element nodes, as well as two text nodes—Suvain and Singh. Note that the text within an
element node is considered to be a separate text node.

Methods:

The XmlNode class has the following methods:






XmlNode Example:

This example shows how to use XmlNode methods and namespaces to create an XML request.

public class DomNamespaceSample
{
public void sendRequest(String endpoint)
{
// Create the request envelope
DOM.Document doc = new DOM.Document();
String soapNS = 'http://schemas.xmlsoap.org/soap/envelope/';
String xsi = 'http://www.w3.org/2001/XMLSchema-instance';
String serviceNS = 'http://www.myservice.com/services/MyService/';
dom.XmlNode envelope
= doc.createRootElement('Envelope', soapNS, 'soapenv');
envelope.setNamespace('xsi', xsi);
envelope.setAttributeNS('schemaLocation', soapNS, xsi, null);
dom.XmlNode body
= envelope.addChildElement('Body', soapNS, null);
body.addChildElement('echo', serviceNS, 'req').
addChildElement('category', serviceNS, null).
addTextNode('classifieds');
System.debug(doc.toXmlString());
// Send the request
HttpRequest req = new HttpRequest();
req.setMethod('POST');
req.setEndpoint(endpoint);
req.setHeader('Content-Type', 'text/xml');
req.setBodyDocument(doc);
Http http = new Http();
HttpResponse res = http.send(req);
System.assertEquals(200, res.getStatusCode());
dom.Document resDoc = res.getBodyDocument();
envelope = resDoc.getRootElement();
String wsa = 'http://schemas.xmlsoap.org/ws/2004/08/addressing';
dom.XmlNode header = envelope.getChildElement('Header', soapNS);
System.assert(header != null);
String messageId= header.getChildElement('MessageID', wsa).getText();
System.debug(messageId); System.debug(resDoc.toXmlString()); System.debug(resDoc); System.debug(header); System.assertEquals( 'http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous', header.getChildElement( 'ReplyTo', wsa).getChildElement('Address', wsa).getText()); System.assertEquals( envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('something', 'http://something.else'). getChildElement( 'whatever', serviceNS).getAttribute('bb', null), 'cc'); System.assertEquals('classifieds', envelope.getChildElement('Body', soapNS). getChildElement('echo', serviceNS). getChildElement('category', serviceNS).getText()); } }

Wednesday, September 18, 2013

XML Stream Classes in Salesforce

Keep watching, as soon as possible I will update this class.....

HttpResponse Class in Salesforce for Handling HTTP Response returned by HTTP Class

Use the HttpResponse class to handle the HTTP response returned by the Http class.

Use the DOM Classes or JSON Classes  to parse XML or JSON content in the body of a response accessed by HttpResponse.


Methods in HTTPResponse Class: 

The HttpResponse class contains the following public methods:
NameArgumentsReturn TypeDescription
getBodyStringRetrieves the body returned in the response. Limit3 MB.
The HTTP request and response sizes count towards the total heap size.
getBodyAsBlobBlobRetrieves the body returned in the response as a Blob. Limit3 MB.
The HTTP request and response sizes count towards the total heap size.
getBodyDocumentDom.DocumentRetrieves the body returned in the response as a DOM document. Use it as a shortcut for:
String xml = httpResponse.getBody();
Dom.Document domDoc = new Dom.Document(xml);
getHeaderString keyStringRetrieves the contents of the response header.
getHeaderKeysString[]Retrieves an array of header keys returned in the response.
getStatusStringRetrieves the status message returned for the response.
getStatusCodeIntegerRetrieves the value of the status code returned in the response.
getXmlStreamReaderXmlStreamReaderReturns an XmlStreamReader (XmlStreamReader Class) that parses the body of the callout response. Use it as a shortcut for:
String xml = httpResponse.getBody();
XmlStreamReader xsr = new XmlStreamReader(xml);
For a full example, see below Example.
setBodyStringVoidSpecifies the body returned in the response.
setBodyAsBlobBlobVoidSpecifies the body returned in the response using a Blob.
setHeaderString key, String valueVoidSpecifies the contents of the response header.
setStatusStringVoidSpecifies the status message returned in the response.
setStatusCodeIntegerVoidSpecifies the value of the status code returned in the response.
toStringStringReturns the status message and status code returned in the response, for example:
Status=OK, StatusCode=200

Example
public class ReaderFromCalloutSample {

  public void getAndParse() {

    // Get the XML document from the external server
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint('http://www.cheenath.com/tutorial/sample1/build.xml');
    req.setMethod('GET');
    HttpResponse res = http.send(req);

    // Log the XML content
    System.debug(res.getBody());

    // Generate the HTTP response as an XML stream
    XmlStreamReader reader = res.getXmlStreamReader();

    // Read through the XML
    while(reader.hasNext()) {
      System.debug('Event Type:' + reader.getEventType());
      if (reader.getEventType() == XmlTag.START_ELEMENT) {
        System.debug(reader.getLocalName());
      }
      reader.next();
    }
 
  }
}

In the above getXmlStreamReader example, content is retrieved from an external Web server, then the XML is parsed using the XmlStreamReader class.

Enjoy........Keep Smiling.....