Sunday, January 10, 2016

How to Refresh a record in Console

Include JS in VF page
<apex:includeScript value="/support/console/26.0/integration.js"/>

Then use below link to open new record .
<A HREF="#" onClick="RefreshPrimaryTab();return false">         Click here to refresh </A>

Write below Java Script code in VF page
    <script type="text/javascript">
    
        function RefreshPrimaryTab() 
        {
            sforce.console.getFocusedPrimaryTabId(showTabId);
        }
            
        var showTabId = function showTabId(result) 
        {
            var tabId = result.id;
            alert('Primary Tab IDs: primaryTabId ' + tabId );
            sforce.console.refreshPrimaryTabById(tabId , true, refreshSuccess);
        };
                   
        var refreshSuccess = function refreshSuccess(result) 
        {
            //Report whether refreshing the primary tab was successful
            if (result.success == true) 
            {
                alert('Primary tab refreshed successfully');
            } 
            else 
            {
                alert('Primary did not refresh');
            }
        };
       
    </script>

Imp Link :- http://www.salesforce.com/us/developer/docs/api_console/Content/sforce_api_console_methods_tabs.htm

Custom Popup in Salesforce | Visualforce page

Please check below link for live demo
http://amitblog-developer-edition.ap1.force.com/CustomPopup




Class Should be:

public with sharing class CustomPopupController {

    public boolean showPopup {get;set;}
    
    public CustomPopupController ()
    {
        showPopup = false;
    }
    
    public PageReference openPopup()
    {
        showPopup = true;
        return null;
    }
    
    public PageReference Cancel()
    {
        showPopup = false;
        return null;
    }
    

}

Page Should be:-

<apex:page controller="CustomPopupController">
<style type="text/css">
    .popupBackground{
        background-color:black;
        opacity: 0.20;
        filter: alpha(opacity = 20);
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 9998;
    }
    .custPopup{
        background-color: white;
        border-width: 2px;
        border-style: solid;
        z-index: 9999;
        left: 50%;
        padding:10px;
        position: absolute;
        width: 500px;
        margin-left: -250px;
        top:100px;
    }

</style>
<apex:form >
 <apex:pageBlock > 

 <apex:commandButton action="{!openPopup}" value="Open Popup" />
 
 <apex:outputPanel id="tstpopup" rendered="{!showPopup}">
                <apex:outputPanel styleClass="popupBackground" layout="block" />
                    <apex:outputPanel styleClass="custPopup" layout="block" >
                        <center>
                              Hello this is Custom pop-Up<BR></BR>
                             <apex:commandButton value="Save"  action="{!Cancel}" />
                             <apex:commandButton value="Cancel" action="{!Cancel}" />
                        </center>
                 </apex:outputPanel>
 </apex:outputPanel>

</apex:pageBlock>
</apex:form>
</apex:page>

INVALID_FIELD_FOR_INSERT_UPDATE: Account: bad field names on insert/update

ISSUE:

Insert error code INVALID_FIELD_FOR_INSERT_UPDATE: Account: bad field names on insert/update call: Salutation
This error often occurs when the default Account record type in Salesforce has been changed to a Person Account record type. The default Account Record Type must be set to a Business Account record type.

RESOLUTION:

To resolved this, login to Salesforce and go to

Setup --> Manage Users --> profile --> and click on the Administrator profile ( or the profile of the Salesforce user specified in the Data Migration setup).

Scroll down to the Record Type settings and click on edit in the Accounts section. Modify the default record type to be a business account record type and click Save.

Trigger Context Variables

1) isExecuting Returns true if the current context for the Apex code is a trigger, not a Visualforce page, a Web service, or anexecuteanonymous() API call.
2) isInsert Returns true if this trigger was fired due to an insert operation, from the Salesforce user interface, Apex, or theAPI.
3) isUpdate Returns true if this trigger was fired due to an update operation, from the Salesforce user interface, Apex, or theAPI.
4) isDelete Returns true if this trigger was fired due to a delete operation, from the Salesforce user interface, Apex, or theAPI.
5) isBefore Returns true if this trigger was fired before any record was saved.
6) isAfter Returns true if this trigger was fired after all records were saved.
7) isUndelete Returns true if this trigger was fired after a record is recovered from the Recycle Bin (that is, after an undelete operation from the Salesforce user interface, Apex, or the API.)
8) new Returns a list of the new versions of the sObject records.Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers.
9) newMap A map of IDs to the new versions of the sObject records. Note that this map is only available in before update, after insert, and after update triggers.
10) old Returns a list of the old versions of the sObject records.Note that this sObject list is only available in update and delete triggers.
11) oldMap A map of IDs to the old versions of the sObject records.Note that this map is only available in update and delete triggers.
12) size The total number of records in a trigger invocation, both old and new.

Sample trigger


trigger AccountTrigger on Account( after insert, after update, before insert, before update)
{

    AccountTriggerHandler handler = new AccountTriggerHandler(Trigger.isExecuting, Trigger.size);
    
    if( Trigger.isInsert )
    {
        if(Trigger.isBefore)
        {
            handler.OnBeforeInsert(trigger.New);
        }
        else
        {
            handler.OnAfterInsert(trigger.New);
        }
    }
    else if ( Trigger.isUpdate )
    {
        if(Trigger.isBefore)
        {
            handler.OnBeforeUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
        else
        {
            handler.OnAfterUpdate(trigger.New ,trigger.Old,Trigger.NewMap,Trigger.OldMap);
        }
    }
}


Create one Trigger Handler Class


public with sharing class AccountTriggerHandler 
{
    private boolean m_isExecuting = false;
    private integer BatchSize = 0;
    public static boolean IsFromBachJob ;
    public static boolean isFromUploadAPI=false;
    
    public AccountTriggerHandler(boolean isExecuting, integer size)
    {
        m_isExecuting = isExecuting;
        BatchSize = size;
    }
            

    public void OnBeforeInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On Before Insert');
    }
    public void OnAfterInsert(List<Account> newAccount)
    {
        system.debug('Account Trigger On After Insert');
    }
    public void OnAfterUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On After Update ');
        AccountActions.updateContact (newAccount);
    }
    public void OnBeforeUpdate( List<Account> newAccount, List<Account> oldAccount, Map<ID, Account> newAccountMap , Map<ID, Account> oldAccountMap )
    {
        system.debug('Account Trigger On Before Update ');
    }

    @future 
    public static void OnAfterUpdateAsync(Set<ID> newAccountIDs)
    {

    }      
    public boolean IsTriggerContext
    {
        get{ return m_isExecuting;}
    }
    
    public boolean IsVisualforcePageContext
    {
        get{ return !IsTriggerContext;}
    }
    
    public boolean IsWebServiceContext
    {
        get{ return !IsTriggerContext;}
    }
    
    public boolean IsExecuteAnonymousContext
    {
        get{ return !IsTriggerContext;}
    }
} 

Create one Trigger Action Class



public without sharing class AccountActions 
{
    public static void updateContact ( List<Account> newAccount)
    {
        // Add your logic here
    }
}

SourcePlease check below post for full example of Trigger
http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

SingleEmailMessage Vs MassEmailMessage | Send Email by Apex

SingleEmailMessage Vs MassEmailMessage





SINGLE EMAILMASS EMAIL
Multiple recipients?YesYes
Personalized body?Yes (single body only)Yes
Special permission needed?NoYes, has to be enabled
Merge fields?YesYes
Personalized merge fields?Yes (only one record at a time)Yes
Templates?YesYes
Template possibilities?Text/HTML/Visualforce/Custom TemplatesText/HTML/Custom Template


SingleEmailMessage:

Single emails are like regular individual emails that may go to one or more addresses (to/cc/bcc), but each of these emails has the same body


Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.toAddresses = new String[] { 'abc@gmail.com', 'xyz@gmail.com' };
message.optOutPolicy = 'FILTER';
message.subject = 'Opt Out Test Message';
message.plainTextBody = 'This is the message body.';
Messaging.SingleEmailMessage[] messages =   new List<Messaging.SingleEmailMessage> {message};
Messaging.SendEmailResult[] results = Messaging.sendEmail(messages);

if (results[0].success) 
{
    System.debug('The email was sent successfully.');
} else 
{
    System.debug('The email failed to send: ' + results[0].errors[0].message);
}
Please check below post to see all other method
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_single.htm 

 
MassEmailMessage:

Mass emails typically go to a large number of addresses (currently capped to 250 per email), with personalized message bodies.
public void SendEmail()
{
 List<contact> lstcon=[Select id from contact limit 2];
 List<Id> lstids= new List<Id>();
 for(Contact c:lstcon)
 {
  lstids.add(c.id);
 }
 EmailTemplate et=[Select id from EmailTemplate where name = 'EmailTemplatename' limit 1];
 
 Messaging.MassEmailMessage mail = new Messaging.MassEmailMessage();
 mail.setTargetObjectIds(lstIds);
 mail.setSenderDisplayName('System Admin');
 mail.setTemplateId(et.id);
 Messaging.sendEmail(new Messaging.MassEmailMessage[] { mail });
}
 Please check below post to see all other method

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_mass.htm 

  
Related link
https://developer.salesforce.com/page/An_Introduction_To_Email_Services_on_Force.com 

Dynamic retrieval of object label & field label

You can describe sObjects either by using tokens or the describeSObjects Schema method.


Apex Class


public with sharing class DescibeDemoController 
{
    public Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
    public String selectedObject {get; set;}
    public List<FieldWrapper> listField{get;set;}

    public DescibeDemoController() 
    {
        listField = new List<FieldWrapper>();
    }

    // find all sObjects available in the organization
    public  List<SelectOption> getListObejectName() 
    {
        List<SelectOption> objNames = new List<SelectOption>();
        List<String> entities = new List<String>(schemaMap.keySet());
        entities.sort();
        for(String name : entities)
            objNames.add(new SelectOption(name,name));
        return objNames;
    }

    
    // Find the fields for the selected object
    public void showFields() 
    {
        listField.clear();
        Map <String, Schema.SObjectField> fieldMap = schemaMap.get(selectedObject).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            schema.describefieldresult dfield = sfield.getDescribe();
            FieldWrapper wObj = new FieldWrapper();
            wObj.fieldName = dfield.getLabel ();
            wObj.fieldAPIName = dfield.getname();
            listField.add(wObj);
        }
    }

    public class FieldWrapper
    {
        public String fieldName {get; set;}
        public String fieldAPIName {get; set;}
    }

}
VF Page


<apex:page controller="DescibeDemoController">
    <apex:form id="Describe">
        <apex:pageBlock id="block2" >
            <apex:pageblockbuttons location="top" >
                    <apex:commandButton value="Show Fields" action="{!showFields}" />
            </apex:pageblockbuttons>
            
            <apex:pageblocksection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel >Object Name</apex:outputLabel>
                    <apex:selectList value="{!selectedObject}" size="1">
                        <apex:selectOptions value="{!ListObejectName}"/>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
            </apex:pageblocksection>
        </apex:pageBlock>
        
        <apex:pageBlock id="result" title="Field Detail for {!selectedObject}" rendered="{!if(listField.size > 0 ,true,false)}"   >
            <apex:pageBlockTable value="{!listField}" var="field" rendered="{!if(listField.size > 0 ,true,false)}"> 
                <apex:column value="{!field.fieldName }" headerValue="Name" />
                <apex:column value="{!field.fieldAPIName }"  headerValue="API Name"/>
            </apex:pageblockTable>
        </apex:pageblock>
    </apex:form>
</apex:page>

Record ID Prefix | Object Type from Record ID Prefix | Prefix of an Object in Salesforce.

We know there are two types of record-id are present in salesforce (18 digit -- Case Insensitive,15 digit -- Case Sensitive). Only 3 digit of ids represent object type .The following is a list of the Salesforce Standard Object ID prefixes


Object
Prefix
Account
001
NOTE
002
Contact
003
User
005
Opportunity
006
Activity
007


 Please check below post for more detail

If you want to get the Prefix of any object . Please try below code.


String keyPrefix = Account.sObjectType.getDescribe().getKeyPrefix();
System.debug('PREFIX--' + keyPrefix );


If you want to get the Object Name from RecordId then please try below code.


public class SchemaGlobalDescribeToGetObjectName
{
    public static String findObjectNameFromRecordIdPrefix(String recordIdOrPrefix)
 {
  String objectName = '';
        try
  {
            String IdPrefix = String.valueOf(recordIdOrPrefix).substring(0,3); 
            Map<String, Schema.SObjectType> gd =  Schema.getGlobalDescribe(); 
            for(Schema.SObjectType stype : gd.values())
   {
                Schema.DescribeSObjectResult r = stype.getDescribe();
                String prefix = r.getKeyPrefix();
                if(prefix!=null && prefix.equals(IdPrefix))
    {
                    objectName = r.getName();
                    System.debug('Object Name! ' + objectName);
                    break;
                }
            }
        }catch(Exception e){
            System.debug(e);
        }
        return objectName;
    }
}


If you want to Get the Object prefix by Workbench then please try below step :-

The easiest way to find out which key prefix maps to which object is by using a tool like the workbench . After you log into workbench, go to and pick an object from the pick list.

Step 1 :- Login in to Workbench

Step 2:- Info > Standard & Custom Objects 


Step 3:- Then select your object



How to get RecordTypeId without SOQL | Get RecordTypeId by Describe Call

Some time in code we need to get recordTypeId . For that generally we used SOQL like below :-



Id contRecordTypeId = [Select id from RecordType where sObjectType = 'Contact' and developerName ='NameOfRecordType' ].id ; 


You can try below Describe to get record Type Id without SOQL



Id contRecordTypeId = Schema.SObjectType.Contact.getRecordTypeInfosByName().get('NameOfRecordType').getRecordTypeId();