Monday, January 16, 2017

Metadata Type in Salesforce

What is Metadata ?

Data about data is called metadata i.e Metadata describe data. 
Whene you are creating a custom field on an Object, you are required to configure few properties such as field name, data type, field length, require or not. This field definition is metadata.

Custom Metadata type extend this features, which is customizable, deployable, packageable and upgradeable. Creating Custom Metadata type and custom metadata type records are almost identical with creating custom object and custom object record. In Apex., custom metadata types can be treated as SObjects and respond to SOQL queries the same way SObject would.

Custom metadata type have great and valuable features which makes it very useful package-able component. It can be used as custom setting  and can be deployed as any other metatdata type.



Custom Metadata Supports following Custom field types -

  • Checkbox
  • Date
  • Date and Time
  • Email
  • Number
  • Percent
  • Phone
  • Picklist [Can't use global picklist values]
  • Text
  • Text Area
  • URL
  • Metadata Relationship
Creating Custom Metadata Type in Salesforce 

Try Creating a Custom Setting, you will get a tip like below screen to to use metadata type if you are using list custom setting.


Create Custom Metadata Type

Setup > Develop > Custom Metadata Types



Metadata type Page settings looks similar to Custom Object like below screen -



It also support Page Layouts. 


Custom Object Vs Custom Metadata 

Custom metadata records can be queried using SOQL, but the platform internally caches the metadata records and can retrieve them more quickly than it retrieves SObject records. Querying custom metadata also doesn’t count towards SOQL limits, which is good news for performance and throughput in enterprise organizations.


Custom metadata rows resemble custom object rows in structure. You create, edit, and delete custom metadata rows in the Metadata API or in Setup. Because the records are metadata, you can migrate them using packages or Metadata API tools. Custom metadata records are read-only in Apex (that’s the only limitation which I feel makes where you might need to choose Custom setting over custom metadata type).

The biggest advantage Custom metadata type gives is it does not count into SOQL queries for each Apex transaction.

Custom Settings Vs Custom Metadata

Custom metadata records can be packaged, which is not the case for either custom objects or custom settings. You have greater control over the visibility of custom metadata types; you can hide the custom metadata types themselves or just hide specific records. You can also control whether or not users can update record values on a field by field basis.

These are major selling points for adopting custom metadata types. Package developers often want to ship default records with their managed packages. Prior to custom metadata types, they would have spent considerable development effort writing post-install scripts to create the data. They would also have to ensure the application coped gracefully with the data not existing; either because it hasn’t yet been created or because a user deleted it.


Custom metadata records can also be pushed from sandboxes to production orgs via change sets. This allows you to follow platform best practices; testing out changes in a sandbox before migrating them via change sets into the production org.

In other hand, records of Custom object and Custom settings can only be migrated manually- For example

  • Export and Import of Data to Salesforce org using Dataloader or Import Wizard .
  • Regenerate the existing data using some script.
  • Renter the whole set of data manually.[Which is practically tedious or impoissible]
All these above manual process are time consuming and error prone.

Difference between Custom Settings and Custom Metadata Type in Salesforce


FunctionalityCustom SettingsCustom Metadata
Unlimited calls/queries
CUD from Apex
Currency type field
Picklist type field
Metadata Relationship
Associate for an organization,
profile, or specific user
◯(Hierarchy)
Metadata deployOnly definitionsDefinitions and records
Apex testsNeeds to create test dataDirectly access
Translation WorkbenchNot supportedStill not supported


Using Custom Metadata in Apex and VF page


VF Page and Controller - 



Output -


Access Custom Metadata Records Programatically


Use SOQL to access your custom metadata types and to retrieve the API names of the records of those type. DML operations aren't allowed on custom metadata in Apex.

The Custom Metadata Type has a suffix of __mdt instead of __c(for custom object and fields) , but the field created in Metadata type are having suffic __c like Custom object.

Following example - query that returns standard and custom fields for all records of ISO2_Code__mdt custom metadata type -

ISO2_CODE__mdt [] codes = [SELECT MasterLabel, Country_Name__c FROM ISO2_Code__mdt];

for(ISO2_Code__mdt c : codes ) {
    System.debug('Metadata Types values-'+c.MasterLabel+' : '+
                           c.Country_Name__c);
}

Limitations of Custom Metadata Types 

Caching

Custom metadata records are cached at the type level after the first read request. Caching enhances performance on subsequent requests. Requests that are in flight when metadata is updated don’t get the most recent metadata.


Global Picklist

Global picklists aren't supported on custom metadata types. You can only use SObject picklists.



Monday, January 25, 2016

ActionFunction in Visualforce

ActionFunction component provides support for invoking Controller action method directly from JavaScript code using AJAX request. An apex:ActionFunction component must be child of an apex:form component.

ActionFunction component is used hen we want to call a controller method from Javascript.

Where as Apex ActionSupport - which only provide support for invoking controller action methods from other Visualforce components, <apex:actionFunction> defines a new JavaScript function which can then be called from within a block of JavaScript code.

Example of using Action function.

Controller -

 public class AccountActionFunction {  
   public Account acc{get;set;}  
   public boolean showfname{get;set;}  
   public boolean showlname{get;set;}  
   public boolean showWebAddr{get;set;}  
   public AccountActionFunction() {  
     System.debug('###Inside Constructor');  
     acc = new Account();  
     showfname = false;  
     showlname = false;  
     showWebAddr = false;  
   }  
   public PageReference AccountTypeChange() {  
     System.debug('$$$- Inside AccountTypeChange()');  
     if(acc.Account_Type__c == 'Person') {  
       showfname = true;  
       showlname = true;  
     } else if(acc.Account_Type__c == 'Company') {  
       showWebAddr = true;  
     } else {  
       showfname = false;  
       showlname = false;  
       showWebAddr = false;  
     }  
     return null;  
   }  
   public String getAccounts() {  
     System.debug('@@@ insite getAccounts()');  
     return null;  
   }  
 }  
Visualforce Page -
 <apex:page controller="AccountActionFunction" tabStyle="Account" action="{!getAccounts}">  
   <apex:form >  
     <apex:actionFunction name="AccountTypeJS" action="{!AccountTypeChange}" reRender="typePB"/>  
     <apex:pageBlock >  
       <apex:pageBlockSection title="Select Account type for Different fields" columns="2" id="typePB" collapsible="false">  
         <apex:inputField value="{!acc.Account_Type__c}" onchange="AccountTypeJS()"/>  
         <apex:inputField value="{!acc.First_Name__c}" rendered="{!showfname}"/>  
         <apex:inputField value="{!acc.Last_Name__c}" rendered="{!showlname}"/>  
         <apex:inputField value="{!acc.Web_Address__c}" rendered="{!showWebAddr}"/>  
       </apex:pageBlockSection>  
     </apex:pageBlock>  
   </apex:form>  
 </apex:page>  
 

Thursday, December 24, 2015

Using Constructor in Apex

A Constructor is code that is invoked when an object is created from the class. You do not need to write a constructor for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
public class AClass {
// No argument Constructor
public AClass() {
//Constructor code
}
}

Object can be instantiated as below -
AClass obj = new AClass();

If you write a constructor with argument(i.e parametrised constructor), you can use that constructor to create an object using those argument.  If a class contain parametrised constructor, then default constructor wont create by automatically,you need to create no-argument constructor explicitly.
# Constructor can be overloaded i.e. there can be more then one Constructor for a class, each having different parameters.
# One constructor can call another constructor using this(...) syntax also called as Constructor chaining as in below example with no argument and one argument constructor.
public class TestClass2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestClass2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestClass2(Integer ObjectSize) {
size = ObjectSize;
}
}
Object can be instantiated either -
TestClass2 objOne = new TestClass2();
TestClass2 objTo = new TestClass2(31);

# Constructor overloading- Constructor with different order argument is possible 
public class Leads {
//No-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the one above, they are in a different order,            so this is legal
public Leads (Boolean call, String email) {}
}


Static and Instance in Apex Salesforce

In Apex, you can have static methods, variables, and initialization code. However, Apex classes can’t be static.You can also have instance methods, member variables, and initialization code, which have no modifier, and local variables.
Static : Static methods, variables and initialization code have following characteristics.
  • They are associated with a class.
  • They'r allowed only in outer class.
  • They'r initialized only when the class is loaded.
  • They'r not transmitted as part of the view state for a VF page.
Instance(Local) : Instance methods, member variables, and initialization code have these characteristics.
  • They'r are associated with a particular object.
  • They'r created with every object instantiated from the class in which they'r declared.
Local Variables have following characteristics -
  • They’re associated with the block of code in which they’re declared
  • They must be initialized before they’re used.
Static Methods and Variables - 
Static methods ans variables used only with outer class. Inner class have no static methods or variables. A static method or variable doesn't require an instance of the class to access, you can access directly using the class name.
A static variable is static only within the scope of the apex transaction, it's not static across the server or organization. Ex - If an apex DML cause a trigger to fire multiple time, the static variable persist across these trigger call. [Use static variable to avoid trigger recursive]
Static variable is used to store information that is shared across all instances of a class. Ex- A recursive trigger can use the value of a class variable to determine when to exit the recursion.
 public class runOnce {  
     public static boolean firstRun = true;  
 }  
 trigger AccTrigger on Account (before delete, after delete, after undelete) {  
     if(Trigger.isBefore && Trigger.isDelete){  
         if(runOnce.firstRun){  
             Trigger.old[0].addError('Before Account Delete Error');  
             runOnce.firstRun=false;  
         }  
     }  
 }
A static variable defined in a trigger doesn’t retain its value between different trigger contexts within the same transaction, such as between before insert and after insert invocations. Instead, define the static variables in a class so that the trigger can access these class member variables and check their static values.
 public static void method() {  
     String Database = '';  
     Database.insert(new Account());  
 }  
Local variable names are evaluated before class names. If a local variable has the same name as a class, the local variable hides methods and variables on the class of the same name. As in the above example you have local variable and class having same name- Database, it will give compile time error, because Salesforce reports that the method doesn’t exist or has an incorrect signature.
Instance Methods and Variables -
An instance member variable is declared inside a class, but not within a method. 
Initialization Code :-
{                                                                              static {
        //Code Here                                                              // Code Here
 }                                                                               }
Initialization code is a block of code as above and static initialization code is a block of code preceded with keyword static.
The instance initialization code in a class is executed each time an object is instantiated from that class. These code blocks run before the constructor. A static initialization block runs only once, regardless of how many times you access the class that contains it.
A class can have any number of either static or instance initialization code blocks. The code blocks are executed in the order in which they appear in the file.

Saturday, December 19, 2015

Apex Class Defination

A class is a template or blue print from which objects are created. A class can contain variables and methods. Variables are used to specify the state of an object and Methods are used to control behaviour. A class can contain other classes, exception type and initialization code.
An Interface is a class which none of the methods have been implemented- the method signatures are there, but the body of each method is empty.
public class outerClass {
    // Outer Class Code
    class innerClass {
       //Inner Class Code
    }
}
# Access modifier for outer class should be public or global.
# You do not have to use an access modifier in the declaration of an inner class.
Use the Syntax for class defination -

private | public | global | [virtual | abstract | with sharing | without sharing] class ClassName [Implements InterfaceNameList] [extends ClassName]
{
      //The body of the class
}

# Private access modifier declares that this class is only known locally, that is, only by this section of code. This is the default access for inner classes—that is, if you don't specify an access modifier for an inner class, it is considered private. This keyword
can only be used with inner classes.
# Public access modifier declares that this class is visible in your application or namespace.
# The global access modifier declares that this class is known by all Apex code everywhere. All classes that contain methods defined with the webService keyword must be declared as global. If a method or inner class is declared as global, the outer,
top-level class must also be defined as global.
# The with sharing and without sharing keywords specify the sharing mode for this class.
# The virtual definition modifier declares that this class allows extension and overrides. You cannot override a method with the override keyword unless the class has been defined as virtual.
The abstract definition modifier declares that this class contains abstract methods, that is, methods that only have their signature declared and no body defined.
A class can implement multiple interfaces, but only extend one existing class. This restriction means that Apex does not support multiple inheritance. The interface names in the list are separated by commas.

Class Variables -
To declare a variable, specify the following:
• Optional:  Modifiers, such as public or final, as well as static.
• Required: The data type of the variable, such as String or Boolean.
• Required: The name of the variable.

• Optional:  The value of the variable.
Syntax - 
[public | private | protected | global] [final] [static] data_type variable_name
[= value]

Class Methods-
To define a method, specify the following:
• Optional: Modifiers, such as public or protected.
• Required: The data type of the value returned by the method, such as String or Integer. Use void if the method does not return a value.
• Required: A list of input parameters for the method, separated by commas, each preceded by its data type, and enclosed in parentheses(). If there are no parameters, use a set of empty parentheses. A method can only have 32 input parameters.
• Required: The body of the method, enclosed in braces {}. All the code for the method, including any local variable declarations, is contained here.
Syntax for defining a method:
[public | private | protected | global] [override] [static] data_type method_name (input parameters)
{
     // The body of the method
}
Note: You can only use override to override methods in classes that have been defined as virtual.

Thursday, December 17, 2015

Dynamic Apex in Salesforce

Dynamic Apex enable developers to create more flexible applications by providing them with the ability to :
  • Access sObject and field describe information.
  • Access Saelsforce app information.
  • Write dynamic SOQL queries, dynamic SOSL queries and dynamic DML.

Live Agent Setting and Customization

Live Agent lets service organizations connect with customers or website visitors in real time through a Web-based, text-only chat. After you set up and customize your basic Live Agent implementation, add it to the Salesforce console so that your agents and supervisor can start chat to assist customers.

You can Customize Live Agent to create a personalize chat experience for your customer service agents and customers using custom code. We will explain the details about how :
  • How to enable and setup Live Agent in the Org.
  • Customize deployment using the Deployment API.
  • Customize the appearance of customer facing chat window using VF page and components.
  • Create Prechat form to collect basci information from customer before they begin chat with an agent.
  • Create post-chat pages that appear to customer after chat complete.
  • Enable Quick Text for the agent for quick response to customer.
  • Enable to share details from Knowledge article in Live agent chat.
Enable Live Agent
You have to enable live agent in your org before you start customizing live agent in Salesforce. To enable live agent in your org.
          Setup > Quick Find/Search > Type Live Agent and enable Live agent as below screen. 
Once you have enebaled Live Agent, you can see the 4 objects marked in green in above screen shot-
  1. Live Chat Transcripts.
  2. Live Chat Transcript Events.
  3. Live Chat Visitors.
  4. Live Agent Sessions
Live Chat Transcripts - Live Chat Transcripts is a standard object is automatically created for each Live Agent chat session and Live Chat Transcript fields help you to keep track information about your agents chat with customer.

Live Chat Transcript Events - Live Chat Transcript Events is a standard object that keep tack events that occur between your agent and customer during chat. It contains event details like Chat requested, Accpeted, Transfer, cancelled, agent left, visitor left etc.

Live Chat Visitors - Live Chat Visitor is a website visitor who has started chat or tried a start chat session. Every time an agent chat with a customer, Salesforce automatically create a visitor record that identifies the customer's computer.

Each new visitor is associated with a session key, which Salesforce creates automatically. A session key is a unique ID that is stored in the visitor record and on the visitor's PC as a cookie. If a customer participates in multiple chats, Salesforce uses the session key to link the customer to their visitor record, associating that record to all related chat transcripts.

Live Agent Sessions - Live Agent Sessions object stores live agent session information, created automatically. This contain information about the agent session, time spent online, Time spent in chats etc.
Live agent session object information is used to create most report in Live Agent called Live Agent Session Report.