Monday 29 December 2014

Some of Setup Objects in Salesforce.com

Hi,
The following are the Setup Objects in Salesforce.com.
I got this  from "http://www.salesforce.com/us/developer/docs/api_toolingpre/api_tooling.pdf".
You can get more information from the above link.

Object
Descripion
CompactLayout
Represents the values that define a compact page layout.
CustomField
Represents a custom field on a custom object that stores data unique to your
organization.
CustomObject
Represents a custom object that stores data unique to your organization. Includes access to the associated CustomObject object and related fields in Salesforce Metadata API.
EmailTemplate
Represents an email template
EntityDefinition
Provides row based access to metadata about standard and custom objects.
FieldDefinition
Provides row based access to metadata about standard and custom fields of
standard and coustom objects.
FlexiPage
Represents a Lightning Page. A Lightning Page is the home page for an app that appears as a menu item in the Salesforce1 navigation menu. Includes access to the associated FlexiPage object in the Salesforce Metadata API.
Layout
Represents a page layout. For more information, see “Managing Page Layouts” in the Salesforce online help.
MenuItem
Represents a menu item.
Profile
Represents a user profile. A profile defines a user's permission to perform different functions within Salesforce.
ProfileLayout
Represents a profile layout.
QuickActionDefinition
Represents the definition of a quick action.
QuickActionList
Represents a list of quick actions.
QuickActionListItem
Represents an item in a quick action list
RecordType
Represents a custom record type.
User
Represents a user.
ValidationRule
Represents a formula that is used for specifying when a criteria is met. This includes both validation rules and workflow rules. Includes access to the associated ValidationRule object in the Salesforce Metadata API.
WorkflowAlert
Represents a workflow alert. A workflow alert is an email generated by a workflow
rule or approval process and sent to designated recipients
WorkflowFieldUpdate
Represents a workflow field update
WorkflowOutboundMessage
Represents an outbound message. An outbound message is a workflow, approval, or milestone action that sends the information you specify to an endpoint you designate, such as an external service. Outbound messaging is configured in the
Salesforce setup menu. Then you must configure the external endpoint. You can
create a listener for the messages using the SOAP API.
WorkflowRule
Represents a workflow rule that is used to fire off a specific workflow action when
the specified criteria is met. Includes access to the associated WorkflowRule object in Salesforce Metadata API.
WorkflowTask
Represents a workflow task that is used to fire off a specific workflow action when
the specified criteria is met. Includes access to the associated WorkflowRule object
in Salesforce Metadata API.

Sunday 14 December 2014

Generation of JSON String , Deserialize and Serialize

Hi,
We have a small example ,how to generate json .The below code is used for  generating json string.
To generate JSON string we have to use "JSONGenerator " and "createGenerator(true)" method.



JSONGenerator gen=JSON.createGenerator(true);
gen.writeStartArray();
gen.writeStartObject();
gen.writenumberField('StudentNumber',1);
gen.writeStringField('StudentName','Balaji');
gen.writeEndObject();
gen.writeStartObject();
gen.writenumberField('StudentNumber',2);
gen.writeStringField('StudentName','Shilpa');
gen.writeEndObject();
gen.writeEndArray();
String jsonString= gen.getAsString();
System.debug('jsonString:'+jsonString);

Output:
=====
jsonString:[ {
"StudentNumber" : 1,
"StudentName" : "Balaji"
 }, {
  "StudentNumber" : 2,
   "StudentName" : "Shilpa"
  } ]

To deserialize the above json string ,we have to prepare a class as shown below.
Class:
======
public class Studentscls{
    public Class StudentDetail{
        public integer StudentNumber{get;set;}
        public String StudentName{get;set;}  
    }
}

Execution:
------------
To deserialize JSON string we have "deserialize" method as shown below by using above class.

List<Studentscls.StudentDetail>  studentList = (List<Studentscls.StudentDetail>)JSON.deserialize(jsonString,List<Studentscls.StudentDetail>.class);
System.debug('Deserialized Result:'+studentList);

OuptPut:
======
Deserialized Result:(StudentDetail:[StudentName=Balaji, StudentNumber=1], StudentDetail:[StudentName=Shilpa, StudentNumber=2])

To serialize above list we have to user "serialize()" method as shown below.
--------------------------------------------------------------------------------------------

String studentJSONString=Json.serialize(studentList);
System.debug('Student JSONString:'+studentJSONString);

Output:
=====

Student JSONString:
[{"StudentNumber":1,"StudentName":"Balaji"},{"StudentNumber":2,"StudentName":"Shilpa"}]


Saturday 6 December 2014

Wrapper List Sorting(Column Sorting) using Comparable Interface

Comparable Interface adds sorting support for Lists that contain non-primitive types, that is, Lists of user-defined types.

Whenever we want to achieve column sorting in wrapper list then we have to implement Comparable and we should define the "compareTo" method as shown below.

Here i am querying the account object records and passing them to wrapper list for giving example. Basically a wrapper class can contain combination of different types. For all such type of things also it will work.Comparable interface is very useful for sorting wrapper list.


Class:
======

public class AccountClass {

    public List<AccountWrappercls> wrapperList{get;set;}
    public string sortableField{get;set;}
    public string sortOrder{get;set;}
    public string previoussortfield{get;set;}
    public AccountClass(){
        wrapperList = new List<AccountWrappercls>();
        sortableField = 'name';
        sortOrder = 'asc';
        previoussortfield =sortableField;
        for(Account actobj:[select id,name,ActiveDate__c,ACnumber__c from Account where ActiveDate__c!=null and ACnumber__c!=null]){
                AccountWrappercls wrapObj = new AccountWrappercls(actobj.ActiveDate__c,actobj.Acnumber__c,actobj.name);
                wrapperList.add(wrapObj);
        }           
        wrapperList.sort();
    }
    public pagereference doSort(){      
        //sortorder='asc';      
        if(previoussortfield == sortableField){
            sortorder='desc';
            previoussortfield=null;
        }
        else{
            sortorder='asc';            
            previoussortfield=sortableField;
        }
        System.debug('sortableField:::'+sortableField);
        System.debug('sortOrder::'+sortOrder);
        AccountWrappercls.sortableField = sortableField;
        AccountWrappercls.sortorder = sortOrder;        
        wrapperList.sort();
        return null;
    }
}

Class Which Implements Comparable interface:
======================================
public  class AccountWrappercls implements comparable{
  public Date createdDate {get;set;}
  public decimal num1 {get;set;}
  public String  name {get;set;}
  public static String sortableField='name';
  public static String sortOrder='asc';  
  public AccountWrappercls(Date createdDate,decimal num1,String  name){
      this.createdDate = createdDate;
      this.num1 = num1;
      this.name =name;
      //this.sortableField = sortableField;
      //this.sortOrder = sortOrder;
  }
   public  Integer compareTo(Object compareTo) {
     AccountWrappercls compWrap = (AccountWrappercls)compareTo;
     if(sortOrder == 'asc'){
    if(sortableField == 'num1'){     
            if (num1 == compWrap.num1) return 0;
          if (num1 > compWrap.num1) return 1;
          return -1;        
    }
    if(sortableField == 'name'){     
            if (name == compWrap.name) return 0;
          if (name > compWrap.name) return 1;
          return -1;        
    }
    if(sortableField == 'createdDate'){     
            if (createdDate == compWrap.createdDate) return 0;
          if (createdDate > compWrap.createdDate) return 1;
          return -1;        
    }}else{
      if(sortableField == 'num1'){     
            if (num1 == compWrap.num1) return 0;
          if (num1 > compWrap.num1) return -1;
          return 1;        
    }
    if(sortableField == 'name'){     
            if (name == compWrap.name) return 0;
          if (name > compWrap.name) return -1;
          return 1;        
    }
    if(sortableField == 'createdDate'){     
            if (createdDate == compWrap.createdDate) return 0;
          if (createdDate > compWrap.createdDate) return -1;
          return 1;        
    }
    }
    
    return null;
    }    
    
}
Visualforce Page:
==============
<apex:page controller="AccountClass">
 <apex:form >
  <apex:pageBlock id="pb">
   <apex:pageBlocKTable value="{!wrapperList}" var="wrapObj">
    <apex:column >
     <apex:facet name="header">
      <apex:commandLink value="Name {!IF(sortableField=='name',IF(sortOrder='asc','▼','▲'),'')}" action="{!doSort}" rerender="pb">
       <apex:param name="name" value="name" assignTo="{!sortableField}"></apex:param>
      </apex:commandLink>
     </apex:facet>
     
      <apex:outputText value="{!wrapObj.name}"/>
     
    </apex:column>
    <apex:column >
     <apex:facet name="header">
      <apex:commandLink value="Ac Number {!IF(sortableField=='num1',IF(sortOrder='asc','▼','▲'),'')}" action="{!doSort}" rerender="pb">
        <apex:param name="num1" value="num1" assignTo="{!sortableField}"></apex:param>
      </apex:commandLink>
     </apex:facet>
     
      <apex:outputText value="{!wrapObj.num1}"/>
         
    </apex:column>
    <apex:column >
     <apex:facet name="header">
      <apex:commandLink value="Date {!IF(sortableField=='createdDate',IF(sortOrder='asc','▼','▲'),'')}" action="{!doSort}" rerender="pb">
       <apex:param name="createdDate" value="createdDate" assignTo="{!sortableField}"></apex:param>
      </apex:commandLink>
     </apex:facet>
     
      <apex:outputText value="{0, date, MM/d/yyyy}">
       <apex:param value="{!wrapObj.createdDate}"/>
      </apex:outputText>
        
    </apex:column>
   </apex:pageBlocKTable>
  </apex:pageBlock>
 </apex:form>
</apex:page>                                        


                                        
Output:
======


Saturday 26 July 2014

Select All CheckBox using Jquery in visualforce page

We have many requirements to have "Select All " records in visualforce page. We can achieve this through the javascript and Jquery.

If we choose jquery we can reduce the lines of code in javascript and we can easily get the functionality.

<apex:page controller="MassUpdateAllcls" sidebar="false">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#parentCheck").click(function() {
                $(".childCheck").prop('checked', this.checked);
                
            });
            $(".childCheck").click(function(){
                if ($('input.childCheck[type=checkbox]:not(:checked)').length){
                    $("#parentCheck").removeAttr('checked');    
                }else{
                    $("#parentCheck").prop('checked',true);
                }
            });
        })
    </script>
      <apex:form >
          <apex:pageBlock >
              <apex:pageBlockTable value="{!accountWrapperList}" var="actWrap">
                  <apex:column >
                      <apex:facet name="header">
                         <input type="checkbox" id="parentCheck"/>
                      </apex:facet>
                      <apex:inputCheckbox value="{!actWrap.isSelect}" styleClass="childCheck"/>
                  </apex:column>
                  <apex:column headerValue="Account Name" value="{!actWrap.actobj.Name}"/>
              </apex:pageBlockTable>
          
          </apex:pageBlock>
      </apex:form>
</apex:page>

Output:
====

Set Console Tab title using "Salesforce Console Integration Toolkit"

Hi,

I have the requirement to have a visualforce page in the console view. But when we open a visualforce page from a button or something in the console view then console set the title for console tab as "ExternalPage".
But we want to change that title.

We can change the title of Console tab when we open "visualforce pages or third party applications" by using "Salesforce Console Integration Toolkit"

To use this in the visualforce page we should include the following script file.

<apex:includeScript value="/support/console/20.0/integration.js"/>

Eg:
==
<apex:page>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<apex:includeScript value="/support/console/20.0/integration.js"/>
<script>
 $(document).ready(function() {

      sforce.console.setTabTitle('My Title for Console Tab');
 });
</script>
</apex:page>

when we open this page then title "My Title for Console Tab" for Console Tab where visualforce page opened in console view.

Not only these we can customize more things in Console by using this Tool Kit.

For more information "Salesforce Console Integration Toolkit".

Sunday 29 June 2014

Lead Conversion in Apex

Here i am going to explain how to convert lead using apex code.
We have "ConvertLead()" method in apex to convert lead.To use this we just need to insert lead first after that we need to pass lead id into "setLeadId()" method as shown below.
Lead leadobj=new Lead();
leadobj.Company = 'AbC Company;
leadobj.LastName = 'Balaji';
insert leadobj;
//Passing lead id
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadobj.id);
//Getting converted status of lead from LeadStatus
//This is used to get Converted Status we set on lead with Lead Status field.
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
//setting convert status.
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr=Database.convertLead(lc);

After converting lead we can get ConvertedAccountId,ConvertedContactId,ConvertedOpportunityId.

Some times we don't want to create Account ,Contact from lead Conversion. Because those may be existing  with the same names. Then we can set existing AccountId, Contactid in lead conversion as shown in below.

Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(leadobj.id);  
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr=Database.convertLead(lc);
 lc.setLeadId(leadobj.id);
 lc.setAccountId(existingaccountId);  
 lc.setContactId(existingContactId);

If we do conversion with this method then we can have all the standard functionalities as in standard lead conversion.




Quote Sync in Apex

Here i am going to explain how to sync quote in apex .

We have "SyncedQuoteId" field on Opportunity object. If we want to sync a quote with opportunity then we just need to update opportunity with Quote Id as shown below. Then the Quote will be in sync with opportunity which we updated.


Opportunity oppobj=new Opportunity(id=opportunityId,SyncedQuoteId=quoteobj.id);
 update oppobj;

Record Type Id without SOQL query

Hi,

We have getRecordTypeInfosByName() method to get record type id with out SOQL query.
We can avoid SOQL query on RecordType object with this method.The following example shows how to access Record Type information through dynamic apex.

Schema.DescribeSObjectResult resSchema = Account.sObjectType.getDescribe();
//getting all Recordtype  Account
Map<String,Schema.RecordTypeInfo> recordTypeInfo = resSchema.getRecordTypeInfosByName(); 
//Getting Business Record Type Id
Id rtId = recordTypeInfo.get('Business').getRecordTypeId();

Tuesday 6 May 2014

Working with custom button in service cloud console and the regular salesforce.com application

Hi,

I am going to explain how to work with custom button in service cloud console mode and the regular salesforce.com application.

Basically we have a requirement i.e we need to create a list button for populating some of the fields from parent record.This should works in regular salesforce.com application  and service cloud console mode.

If we use " window.open " method for both it won't work for service cloud console mode in a proper way.So we need to use different things to work with both .The following things are useful whenever you want to construct an url from custom button for both service cloud console mode and regular salesforce.com app.

if (typeof(srcUp) == 'function') {
srcUp('/a1z/e?retURL=%2F{!Acccount.Id}&CF00Ne0000000u_lkid={!Contact.Id}');
} else {
window.open('/a1z/e?retURL=%2F{!Acccount.Id}&CF00Ne0000000u_lkid={!Contact.Id}','_parent');
}

Here,we check to see if the srcUp method is defined with "if(typeof(srcUp)=='function')".If we are in the Service Cloud Console ,this condition will evaluate to true.If it is false and we are in the regular app, we use the javascript "window.open" method to open our target url in a new window.

For more information please look into below url:
Click here for more information



Sunday 4 May 2014

Showing Attachment Preview and related record detail by passing attachment id in salesforce.com

Hi,

Here in the following example i am using one custom component ,visualforce page and an extension.Here the custom component is used to display preview of attachment by getting the id from visualforce page where it is included.In this component i am using "Object" ,"embed" html tags to show preview of attachment.

Component Code:
===============
<apex:component >
<apex:attribute name="height" type="String" description="TODO: Describe me"/>
<apex:attribute name="width" type="String" description="TODO: Describe me"/>
<apex:attribute name="value" type="String" description="TODO: Describe me"/>
<object data="/servlet/servlet.FileDownload?file={!value}" type="application/pdf" width="{!width}" height="{!height}">
 <embed src="/servlet/servlet.FileDownload?file={!value}" width="{!width}" height="{!height}"/>
</object >
</apex:component>

Visualforce Page:
=============
<apex:page standardcontroller="Attachment" extensions="Attachradiocls1" sidebar="false">
    <h1 style="padding:10px;width:100%;float:left; font-size:24px; color:#015ba7;">ABC Company</h1>
    <table cellpadding="0" cellspacing="0">
        <tr>
            <td style="width: 283px; vertical-align:top; background:#CCC;border-right: #F0F0F0 2px solid;">
                <div style="margin:20px;">
                <h1>Contact Info</h1>
                <table>
                    <tr>
                        <td>
                            Contact Name:
                        </td>
                        <td>
                            {!contobj.Name}
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Contact Email:
                        </td>
                        <td>
                            {!contobj.Email}
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Lead Source:
                        </td>
                        <td>
                            {!contobj.Leadsource}
                        </td>
                    </tr>
                </table>
                </div>
            </td>
            <td>
                <table cellpadding="0" cellspacing="0">
                    <tr>
                        <td>
                        <c:Pdfcomponent value="{!attachment.id}" width="824px" height="1135px"/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</apex:page>

Extension Code:
==============
public with sharing class Attachradiocls1 {
    public Contact contobj{get;set;}
    public Attachradiocls1 (ApexPages.Standardcontroller stdcontroller){
        contobj=new Contact();
        String id=ApexPages.CurrentPage().getParameters().get('id');
        if(id!=null && id!=''){
            Attachment att=[select id,name,parentId,body from attachment where id=:id];
            //body=att.body.tostring();
            contobj=[select id,name,Email,LeadSource from Contact where id=:att.parentId];
        }
        
    }
}

Output:
======





Tuesday 18 March 2014

Mobile supported table using jquery mobile in Salesforce.com

Hi,

Here I am going to explain how to design a table which supports mobile also using jquery mobile.
Before we are going to work with jquery mobile we just need to include the following files
into our visualforce page.

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>

in the above

The meta viewport tag  specifies how the browser should control the page zoom level and dimensions. By default, mobile devices assume that pages are about 900 pixels wide. This is to make it work well with existing desktop sites, but the screens may look zoomed out and too wide. By setting the viewport attributes, the browser is set to the screen width of the device - and the content remains at the correct scale.

We just need to use html table and use <apex:repeat> tag to display our records.

We need to use different attributes which are supported by jquery mobile to design our table

like dat-role,data-mode etc in table tag

Eg:
===
Controller:
============
public  class Accountdislaycls {
  public List<Account> lstaccount{get;set;}
  public Accountdislaycls(){
    lstaccount=new List<Account>();
    lstaccount=[select id,name,industry,type from Account];
   
  }
}

==================
Visualforce page:
======================
<apex:page controller="Accountdislaycls" standardstylesheets="false" showHeader="false">
    <head>
      <meta charset="utf-8"></meta>
      <meta name="viewport" content="width=device-width, initial-scale=1"/>
      <title>dialog demo</title>
      <link rel="stylesheet" href="//code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css"/>
      <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
      <script src="//code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
      <style>
            th
            {
                border-bottom: 1px solid #d6d6d6;
            }
            tr:nth-child(even)
            {
                background:#e9e9e9;
            }
    </style>
    </head>
    <div data-role="page">
        <div data-role="header">
             <h1>Account Table</h1>
        </div>
        <div data-role="main">
            <table data-role="table"  data-mode="columntoggle" class="ui-responsive ui-shadow" data-column-btn-text="Click me to hide or show columns!">
                <thead>
                    <th data-priority="1">Account Id</th>
                    <th data-priority="2">Account Name</th>
                    <th data-priority="3">Type</th>
                    <th data-priority="4">Industry</th>
                </thead>
                <tbody>
                     <apex:repeat value="{!lstaccount}" var="act">
                         <tr>
                            <td>{!act.id}</td>
                            <td>{!act.name}</td>
                            <td>{!act.type}</td>
                            <td>{!act.industry}</td>
                         </tr>
                     </apex:repeat>
                </tbody>
            </table>
        </div>
        <div data-role="footer">
            <h1>Account Details</h1>
        </div>
    </div>
</apex:page>
                             
in the above example

data-role="page"  is the page displayed in the browser
data-role="header"  creates a toolbar at the top of the page (often used for title or search buttons)
data-role="main" defines the content of the page, like text, images, buttons, forms, etc.
"ui-content" class adds extra padding and margin inside the page content
data-role="footer" creates a toolbar at the bottom of the page
Inside these containers, you can add any HTML elements - paragraphs, images, headings, lists, etc.

data-role="table" defines the table which can use properties from jquery mobile
Use class 'ui-responsive" to support responsive design
data-mode="columntoggle" hide columns when there is not enough width to display the data.

jQuery Mobile will hide columns from the right side of the table.
However, you are allowed to specify which column that should be hidden or shown in a specific order.
 Add the data-priority attribute to the table's header (<th>) and specify a number between 1 (highest priority) to 6 (lowest priority)

Note:
====
If we do not specify a priority for a column,
the column will be persistent and not available for hiding.
output:


How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...