Showing posts with label Visualforce Training. Show all posts
Showing posts with label Visualforce Training. Show all posts

Sunday, April 3, 2016

Visualforce basic JavaScript examples.?

Visualforce basic JavaScript examples.?


Example 1: 

In this example i am simply telling that how you can reference your VF variables in javascript.

Here in the first text once you entered the values and come's out from the text it will show alert message and displaying the text values in alert message.


<apex:page id="pg">
    <apex:form id="fm">
      <apex:inputtext id="Name" onchange="Show()"/>
      <script>
        function Show(){
          alert('test');
          var myname = document.getElementById('{!$Component.Name}').value;
          alert("my Name is==>"+ myname );
          
        }
        
        function demo(){
          alert('demo is calling');
          var myage = document.getElementById('pg:fm:pb2:age').value;
           alert('My age is==>'+myage );
        }
      </script>
      <br/>
      <br/>
      
      <apex:pageblock id="pb2">
      
      <apex:inputtext id="age" onchange="demo()"/>
      </apex:pageblock>
      
    </apex:form> 
 </apex:page>





Example 2:

In the below example i am populating first text field value into second text field. for that i am using simple javavascrpt functions.


<apex:page id="pg">
    <apex:form id="fm">
      <apex:inputtext id="Name" onchange="Show()"/>
      <script>
        function Show(){
          alert('test');
          var myname = document.getElementById('{!$Component.Name}').value;
          alert("my Name is==>"+ myname );
          
        }
        
        function demo(){
          alert('demo is calling');
          var myage = document.getElementById('pg:fm:pb2:age').value;
           alert('My age is==>'+myage );
        }
      </script>
      <br/>
      <br/>
      
      <apex:pageblock id="pb2">
      
      <apex:inputtext id="age" onchange="demo()"/>
      </apex:pageblock>
      
    </apex:form> 
 </apex:page>





That's it. these are the simple javascript basic examples.



Sunday, May 24, 2015

Schema Programming in Apex and its usage in Visualforce Page.

Schema Programming in Apex and its usage in Visualforce Page.


Schema give the meta data information about the data (Object, Fields).

Schema Methods :

1). public static Map<String, Schema.SObjectType> getGlobalDescribe()
   
 This method returns a map of all the Sobject names as keys and Sobject val tokens as Values.


Ex:

Display all the list of objects available in the salesforce organization in the Visualfoce page.


Controller Class:

public class SchemaDescribeExample {
    public List<SelectOption> options;
    
    public list<SelectOption> getOptions(){
        return options;
    }
    
    public SchemaDescribeExample(){
        options = new List<SelectOption>();
        Map<String, Schema.SObjectType> schemaMap = schema.getGlobalDescribe();
        Set<String> objectSet = schemaMap.keySet();
        for(String str:objectSet){
            //praparing label and values in selection option.
            SelectOption op =new SelectOption(str,str);
            options.add(op);
        }
    }
    
    

}


VF Page:

<apex:page controller="SchemaDescribeExample">
 <apex:form >
  <Apex:selectList size="1">
    <apex:selectOptions value="{!options}"></apex:selectOptions>
   
  </Apex:selectList>
 </apex:form>
</apex:page>



That's it.. now it will display the list of all the objects in picklist.


More about Dynamic Apex:



Schema Programming in Apex and its usage in Visualforce Page.




Saturday, May 23, 2015

How to Use Select options in Visualforce page?

How to Use Select options in Visualforce page?

Selectoption object specifies one of the possible values for visualforce select checkboxes, select list, select radio component.

It consist of label that is displayed to the end user, and the value that will be written to the controller.

Note:- The SelectOption can be displayed in the disable state.

Constructors:

We have 2 types of constructors in this class

Instantiating 

SelectOption one = bew SelectOpton (value(String), label(String), IsDisabled(true/false));

If isDisabled is true, the option is disabled . We can not select that value.


SelectOption one = new SelectOption(value, label) 
          Value as String
          Label as String


Methods:

             Ex: one.getLabel();
             output: : One
            Ex: one.setDisabled(false);


Example: 

Controller Class: 

public class SelectOptionExample {

    String[] countries = new String[]{};

    public PageReference test() {
        return null;
    }

    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('US','US'));
        options.add(new SelectOption('CANADA','Canada'));
        options.add(new SelectOption('MEXICO','Mexico'));
        return options;
    }

    public String[] getCountries() {
        return countries;
    }

    public void setCountries(String[] countries) {
        this.countries = countries;
    }
    

}


VF Page: 

<apex:page controller="SelectOptionExample">

   <apex:form >
        <apex:selectCheckboxes value="{!countries}">
            <apex:selectOptions value="{!items}"/>
        </apex:selectCheckboxes><br/>
        <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
    </apex:form>
    
    <apex:outputPanel id="out">
        <apex:actionstatus id="status" startText="testing...">
            <apex:facet name="stop">
                <apex:outputPanel >
                    <p>You have selected:</p>
                    <apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
                </apex:outputPanel>
            </apex:facet>
        </apex:actionstatus>
    </apex:outputPanel>
</apex:page>




Once you select the options and click on test it will display the selected checkboxes details.




That's it....



Friday, January 23, 2015

How to use apex:variable in Visualforce Page?

How to use apex:variable in Visualforce Page?


A local variable that can be used as a replacement for a specified expression within the body of the component. Use < apex:variable > to reduce repetitive and verbose expressions within a page.
Note: < apex:variable > does not support reassignment inside of an iteration component, such as < apex:dataTable > or < apex:repeat >. The result of doing so, e.g., incrementing the < apex:variable > as a counter, is unsupported and undefined.
 

This tag supports following attributes:


Attribute
Description
id
An identifier that allows the component to be referenced by other components in the page.
rendered
A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true.
value
The expression that can be represented by the variable within the body of the variable component.
var
The name of the variable that can be used to represent the value expression within the body of the variable component.

Code Example:

<apex:page controller="repeaterCon">
    <apex:variable value="{!1}" var="rowNum"/>
    <apex:repeat value="{!collection}" var="row">
        {!rowNum}-{!row}<br/>
        <apex:variable var="rowNum" value="{!rowNum + 1}"/>
    </apex:repeat>
   
</apex:page>


Class:

public class repeaterCon {
 public List<String> collection {
        get {
            if (collection == null) {
                collection = new List<String>();
                for (Account a : [SELECT ID, Name FROM 

                      Account  LIMIT  10]) {
                    collection.add(a.Name);
                }
            }
            return collection;
        }
        private set;
    }
}





That's it. 

More about VF Tags

http://sfdcsrini.blogspot.com/2014/06/visualforce-form-tags-with-examples.html


Friday, December 5, 2014

Show error message in Visualforce Page

Show error message in Visualforce Page using ApexPages.addmessage


Sometime we need to show  or display error message on Visualforce page with different notations like warning, error, info etc.... We can implement this requirement by creating new instance of ApexPages.message and then adding message to Apexpages using ApexPages.addmessage. Then displaying these messages in visualforce page.

We can display 5 different types of message in Visualforce Page. In the example below, we are showing 5 input fields of account. We have added a button on visualforce page. Different type of message will be shown on visualforce page if we will keep any field blank.

         



Visualforce Page:

<apex:page standardController="Account" extensions="DisplayErrorMessageInVfCls">
 <apex:form >
   <apex:pageblock >
      <apex:pageMessages id="showmsg"></apex:pageMessages>
         <apex:panelGrid columns="2">
           Account Name: <apex:inputText value="{!acc.name}"/>
           Account Number: <apex:inputText value="{!acc.AccountNumber}"/>
           Account Phone: <apex:inputText value="{!acc.phone}"/>
           Account Site: <apex:inputText value="{!acc.site}"/>
           Account Industry: <apex:inputText value="{!acc.industry}"/>
           <apex:commandButton value="Save Details" action="{!save}" style="width:90px" rerender="showmsg"/>
         </apex:panelGrid>
    </apex:pageblock>
 </apex:form>
</apex:page>


Apex Class:

public with sharing class DisplayErrorMessageInVfCls{

    public Account acc{get;set;}
    //extension of Standard controller.
    public DisplayErrorMessageInVfCls(ApexPages.StandardController controller) {
        acc = new Account();
    }
    public void save(){
      if(acc.name == '' || acc.name == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.FATAL,'Please enter Account name'));
      if(acc.AccountNumber == '' || acc.AccountNumber == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Please enter Account number'));
      if(acc.phone == '' || acc.phone == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.WARNING,'Please enter Account phone'));
      if(acc.site == '' || acc.site == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Please enter Account site'));
      if(acc.industry == '' || acc.industry == null)
       ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,'Please enter Account industry'));
    }
}



To Refer visualforce tags :






Friday, November 28, 2014

Creating an Inbound Email Service in Salesforce.

Creating an Inbound Email Service in Salesforce.

Email services are automated processes that use Apex classes to process the contents, headers, and attachments of inbound email.

You can associate each email service with one or more Salesforce-generated email addresses to which users can send messages for processing.

An email services only process its messages it receive one of it’s address

For example you can create email service that automatically create its contact record based on contact information in your email messages.






   



The general template to create the apex class for the email services is:
  














 




Create Email Handler class Shell:-

A class must implements the Messaging.InboundEmailHandler interface and this interface has single method that call handleInboundEmail messages.

The force.com IDE provides a template for creating an inbound email service handler calss.




 


Instructions:
1. Create the Apex email handler class.
   A. In the Force.com IDE, right-click the project folder and select New | Apex Class.
   B. Enter the Name ProcessContactApplicantEmail and click Finish.

 

Apex Class:

/**
 * Email services are automated processes that use Apex classes
 * to process the contents, headers, and attachments of inbound
 * email.
 */
global class ProcessContactApplicantEmail implements Messaging.InboundEmailHandler {

    global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
        Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
       
        Contact contact = new Contact();
        contact.FirstName = email.fromname.substring(0,email.fromname.indexOf(' '));
        contact.LastName = email.fromname.substring(email.fromname.indexOf(' '));
        contact.Email = envelope.fromAddress;
        insert contact;
      
        System.debug('====> Created contact==> '+contact.Id);
      
        if (email.binaryAttachments != null && email.binaryAttachments.size() > 0) {
          for (integer i = 0 ; i < email.binaryAttachments.size() ; i++) {
            Attachment attachment = new Attachment();
            // attach to the newly created contact record
            attachment.ParentId = contact.Id;
            attachment.Name = email.binaryAttachments[i].filename;
            attachment.Body = email.binaryAttachments[i].body;
            insert attachment;
          }
    }
      
   

        return result;
    }
   
   
   
}
  


2. Create the inbound email service.
    A. In the UI, navigate to Setup | Build | Develop | Email Services.
    B. Click New Email Service.
    C. Enter the following information:
        i. Email Service Name: CandidateSubmission
        ii. Apex Class: CandidateEmailHandler
        iii. Accept Attachments: All
        iv. Advanced Email Security Settings: (cleared)
        v. Accept Email From: Enter your email address or leave blank
        vi. Active: (selected)
        vii. Set all Failure Response Settings to: Bounce Message
    D. Click Save and New Email Address.
    E. Enter the following information:
        i. Email Address: CandidateSubmission
        ii. Active: (selected)
        iii. Context User: (your name)
        iv. Accept Email From: (enter your email address or leave blank)
    F. Click Save and notice the resulting Email Address.















One of the difficult thing about email service is debugging them. You can either create a test class for this or simply send the email and check the debug logs. Any debug statements you add to your class will show in the debug logs. Go to Setup -> Administration Setup -> Monitoring -> Debug Logs and add the Context User for the email service to the debug logs. Simply send an email to the address and check the debug log for that user.


The following unit test class will get you 100% code coverage.

/**
 * @Description: Test class for  ProcessContactApplicantEmail
 */
@isTest
private class ProcessContactApplicantEmail_Test {

    static testMethod void myUnitTest() {
       // create a new email and envelope object
      Messaging.InboundEmail email = new Messaging.InboundEmail() ;
      Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
   
      // setup the data for the email
      email.subject = 'Test Contact Applicant';
      email.fromname = 'FirstName LastName';
      env.fromAddress = 'sfdcsrini@email.com';
   
      // add an attachment
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfile.txt';
      attachment.mimeTypeSubType = 'text/plain';
   
      email.binaryAttachments =
        new Messaging.inboundEmail.BinaryAttachment[] { attachment };
   
      // call the email service class and test it with the data in the testMethod
      ProcessContactApplicantEmail emailProcess = new ProcessContactApplicantEmail();
      emailProcess.handleInboundEmail(email, env);
   
      // query for the contact the email service created
      Contact contact = [select id, firstName, lastName, email from contact
        where firstName = 'FirstName' and lastName = 'LastName'];
   
      System.assertEquals(contact.firstName,'FirstName');
      System.assertEquals(contact.lastName,'LastName');
      System.assertEquals(contact.email,'sfdcsrini@email.com');
   
      // find the attachment
      Attachment a = [select name from attachment where parentId = :contact.id];
   
      System.assertEquals(a.name,'textfile.txt');

    }
}



Email Logs:

  • Are csv files that can be accessed by clicking Setup -> Monitoring -> Email Log Files. The logs contain the emails sent/received through salesforce along with the email addresses, date/time, delivery status and error codes. But, it does NOT capture the body or attachments of an email.
  • Since developers do not have access to system log files in the context of an inbound email class, they may want to create a custom object to log any exceptions or debug statements.












 
| ,