Tag Archives: Salesforce

Get All Objects and Its Fields in Salesforce Org

We can use Schema.getGlobalDescribe() to get all properties of sObject and its fields.

Apex Class:

public class SampleController {
    
    Public string selectedObj {get;set;}
    public String selectedField {get; set;}
    
    Public List<Selectoption> getObjList(){
        List<Schema.SObjectType> objList = Schema.getGlobalDescribe().Values();     
        List<SelectOption> objNames = new List<SelectOption>();
        objNames.add(new SelectOption('','-- Select --'));
        for(Schema.SObjectType obj : objList)
        {
            objNames.add(new SelectOption(obj.getDescribe().getName(),obj.getDescribe().getLabel()));
        }
        objNames.sort();
        return objNames;
    }
    
    public List<SelectOption> getObjectFields() {
        List<SelectOption> fieldNames = new List<SelectOption>();
        fieldNames.add(new SelectOption('','-- Select --'));
        if(!String.isBlank(selectedObj)){
            Map<String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
            Schema.SObjectType ObjSchema = schemaMap.get(selectedObj);
            Map<String, Schema.SObjectField> fieldMap = ObjSchema.getDescribe().fields.getMap();
            for (String fieldName: fieldMap.keySet()) 
            {  
                fieldNames.add(new SelectOption(fieldName, fieldMap.get(fieldName).getDescribe().getLabel()));
            }
        }
        return fieldNames;
    }      
}

Visualforce Page:

<apex:page controller="SampleController">
    <apex:form> 
        <apex:pageBlock>
            <apex:pageBlockSection columns="2">
                
                <apex:pageBlockSectionItem >
                    <apex:outputlabel value="Object Names :"/> 
                    <apex:actionRegion >      
                        <apex:selectList value="{!selectedObj}" size="1">
                            <apex:selectOptions value="{!ObjList}"/>
                            <apex:actionSupport event="onchange" rerender="objFields"/>
                        </apex:selectList>
                    </apex:actionRegion>                         
                </apex:pageBlockSectionItem>
                
                <apex:pageBlockSectionItem >
                    <apex:outputlabel value="Field Names :"/>   
                    <apex:outputPanel id="objFields">   
                        <apex:actionRegion >  
                            <apex:selectList value="{!selectedField}" size="1">
                                <apex:selectOptions value="{!ObjectFields}"/>
                            </apex:selectList>
                        </apex:actionRegion>      
                    </apex:outputPanel>
                </apex:pageBlockSectionItem>
                
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output:

Test Class For Future Method

Future Method:

public class AccountHelper {
	@future
	public static void UpdateAccounts(List<Id> accountIds){
		//Get those records based on the IDs
		List<Account> accList = [SELECT Name FROM Account WHERE Id IN : accountIds];
		//Process records
	}
}

Test Class:

@isTest
public class TestAccountHelper {
    
    private static User CreateUser(){
        String orgId = UserInfo.getOrganizationId();
        String standardUserProfileId = [SELECT Id From Profile WHERE Name = 'Standard User'].Id;
        User u = new User(
            FirstName = 'Test',
            LastName = 'User',
            Alias = 'TestUser', 
            profileId = standardUserProfileId ,
            Email = orgId + '@test.org',
            Username = orgId + '@test.org',
            EmailEncodingKey = 'ISO-8859-1',
            LanguageLocaleKey = 'en_US',
            LocaleSidKey = 'en_US',  
            TimeZoneSidKey = 'America/Los_Angeles'
        );
        insert u;
        return u;
    }
    
    private static Account CreateAccount(){
        Account acc = new Account( Name = 'Test Account', 
                                  Type = 'Technology Partner', 
                                  Industry = 'Technology',
                                  Phone = '9898989898'
                                 );
        insert acc;
        return acc;
    }
    
    private static testMethod void testUpdateAccounts(){
        
        User u = CreateUser();
        System.runAs(u) {
            Account acc = CreateAccount();
            List<Id> accountIds = new List<Id>();
            accountIds.add(acc.Id);
            
            Test.startTest();
            AccountHelper.UpdateAccounts(accountIds);
            Test.stopTest();
        }
        //Verify account is inserted
        List<Account> accList = [SELECT Id From Account WHERE Name = 'Test Account'];
        System.assertEquals(1, accList.size());
    }
}

EmailMessage in Salesforce

“EmailMessage” represents an email in Salesforce.

EmailMessage Supported Calls:

  • create()
  • delete()
  • describeLayout()
  • describeSObjects()
  • getDeleted()
  • getUpdated()
  • query()
  • retrieve()
  • undelete()
  • update()
  • upsert()
  • EmailMessage is only available for organizations that use Email-to-Case or Enhanced Email, which is automatically enabled for most customers.
  • Customer Portal users have read access to EmailMessage if the value for the ParentID field is associated with a case. Otherwise, access is determined by sharing access of the associated task.
  • update() is supported only on records whose Status is Draft. When a record’s Status is not Draft, update() is supported only for the IsExternallyVisible field and custom fields.

Fields in EmailMessage:

Field Label API Field Name Type Length Properties Description
Activity ActivityId reference 15 Create, Filter, Group, Nillable, Sort ID of the activity that is associated with the email. Usually represents an open task that is created for the case owner when a new unread email message is received.
BCC Ids BccIds JunctionIdList Create, Update A string array of IDs for contacts, leads, and users who were sent a blind carbon copy of the email message. Each ID is linked to an EmailMessageRelation record, which represents the relationship between an email message and a Contact, Lead, or User record.
BCC Address BccAddress string 4000 Create, Filter, Nillable, Sort, Update A string array of email addresses for recipients who were sent a blind carbon copy of the email message. This field should include only email addresses that are not associated with Contact, Lead, or User records in Salesforce. If the recipient is a contact, lead, or user, add their ID to the BccIds field instead of adding their email address to the BccAddress field. Then the email message is automatically associated with the contact, lead, or user.
CC Address CcAddress string 4000 Create, Filter, Nillable, Sort, Update A string array of email addresses for recipients who were sent a carbon copy of the email message. This field should include only email addresses that are not associated with Contact, Lead, or User records in Salesforce. If the recipient is a contact, lead, or user, add their ID to the CcIds field instead of adding their email address to the CcAddress field. Then the email message is automatically associated with the contact, lead, or user.
CC Ids CcIds JunctionIdList Create, Update A string array of IDs for contacts, leads, and users who were sent a carbon copy of the email message. Each ID is linked to an EmailMessageRelation record, which represents the relationship between an email message and a Contact, Lead, or User record.
Created By CreatedById reference 15 Defaulted on create, Filter
Created Date CreatedDate datetime Defaulted on create, Filter
Deleted IsDeleted boolean Defaulted on create, Filter Indicates whether the object has been moved to the Recycle Bin (true) or not (false). Label is Deleted.
EmailMessage ID Id id 15
From Address FromAddress email 1000 Create, Filter, Nillable, Update The address that originated the email.
From Name FromName string 1000 Create, Filter, Nillable, Update The sender’s name.
HTML Body HtmlBody textarea 32000 Create, Nillable, Update The body of the email in HTML format.
Has Attachment HasAttachment boolean Defaulted on create, Filter Indicates whether the email was sent with an attachment (true) or not (false).
Headers Headers textarea 32000 Create, Nillable, Update The Internet message headers of the incoming email. Used for debugging and tracing purposes. Does not apply to outgoing emails.
Is Incoming Incoming boolean Create, Defaulted on create, Filter Indicates whether the email was received (true) or sent (false).
Is Client Managed IsClientManaged boolean Create, Defaulted on create, Filter, Group If EmailMessage is created with IsClientManaged set to true, users can modify EmailMessage.ContentDocumentIds to link file attachments even when the Status of the EmailMessage is not set to Draft.
Is Externally Visible IsExternallyVisible boolean Create, Defaulted on create, Filter, Group, Update If the community case feed is enabled, IsExternallyVisible controls the external visibility of emails in communities. When IsExternallyVisible is set to true—its default value—email messages are visible to external users in the case feed.
Only emails with the ParentId field populated are available to be externally visible in communities.
This field can’t be updated if the email’s Status is set to Draft.
Last Modified By LastModifiedById reference 15 Defaulted on modify, Filter
Last Modified Date LastModifiedDate datetime Defaulted on modify, Filter
Message Date MessageDate datetime Create, Filter, Nillable, Update The date the email was created.
Message Identifier MessageIdentifier string 255 Create, Filter, Group, Nillable, Sort, Update The ID of the email message.
Parent Case ParentId reference 15 Create, Filter, Group, Nillable, Sort ID of the case that’s associated with the email.
Related To Id RelatedToId reference 15 Create, Filter, Group, Nillable, Sort The RelatedToId represents nonhuman objects such as accounts, opportunities, campaigns, cases, or custom objects. RelatedToIds are polymorphic. Polymorphic means a RelatedToId is equivalent to the ID of a related object.
Reply-to Email Message ReplyToEmailMessageId reference 15 Create, Filter, Group, Nillable, Sort ID of the inbound or outbound EmailMessage the current EmailMessage is a reply to. It’s not possible to reply to a message whose Status is Draft.
Status Status picklist 40 Create, Filter, Restricted picklist, Update Read only. The status of the email. For example, New, Draft, Unread, Replied, or Sent.
Subject Subject string 3000 Create, Filter, Nillable, Update The subject line of the email.
System Modstamp SystemModstamp datetime
Thread Identifier ThreadIdentifier String 255 Create, Filter, Group, Nillable, Sort, Update The ID of the email thread the email message belongs to.
Text Body TextBody textarea 32000 Create, Nillable, Update The body of the email, in plain text format.
To Address ToAddress string 4000 Create, Filter, Nillable, Update A string array of email addresses for recipients who were sent the email message. This field should include only email addresses that are not associated with Contact, Lead, or User records in Salesforce. If the recipient is a contact, lead, or user, add their ID to the ToIds field instead of adding their email address to the ToAddress field. Then the email message is automatically associated with the contact, lead, or user.
Validate From Address ValidateFromAddress picklist Create, Filter, Nillable, Update A string array of email addresses for recipients who were sent the email message. This field should include only email addresses that are not associated with Contact, Lead, or User records in Salesforce. If the recipient is a contact, lead, or user, add their ID to the ToIds field instead of adding their email address to the ToAddress field. Then the email message is automatically associated with the contact, lead, or user.

EmailMessage Usage:
If your organization uses Email-to-Case, a case is created when an email is sent to one of your company’s addresses. The email, which is related to the case by the ParentID field, is stored as an EmailMessage record. When users view the email, they see the EmailMessage record.

If your organization uses Enhanced Email, each email is stored as an EmailMessage record and a Task record. When users view an email, they see the EmailMessage record.

Salesforce Sales Cloud Data Model

Leads : Represents a prospect or lead.
Accounts : Represents an organization or person involved with your business such as customers, competitors or partners.
Contacts : Represents a contact, which is a person associated with an account.
Opportunity : Represents an opportunity, which is a sale or pending deal.
Product : Represents a product that your org sells.
Opportunity Line Item : Represents an opportunity line item, which is a member of the list of Product2 products associated with an Opportunity.
Price Books : Represents to establish different pricing structures for products.
Quote : Represents a quote, which is a record showing proposed prices for products and services.
Order : Represents an order associated with a contract or an account. An order record is an agreement between a company and a customer to provision services or deliver products with a known quantity, price, and date.
Contract : Represents a contract(Business Legal Agreement) associated with an Account.
Campaigns : Represents and tracks a marketing campaign, such as a direct mail promotion, webinar, or trade show.
Campaign Members : Represents the association between a campaign and either a lead or a contact.

Custom Clone Button in Salesforce

Salesforce provides Clone functionality for some standard objects(Standard Clone button), However some standard objects do not have this button. For this purpose of cloning we will need to create custom button that will perform the functionality of cloning.

This cloning functionality can be achieved by writing a javascript for this custom button.

As an example lets create a custom button “Clone” on Account object that will clone the record.

Simply override your custom button “Clone” with the following javascript and you will have your custom Clone button that functions exactly like standard clone button

{!REQUIRESCRIPT("/soap/ajax/22.0/connection.js")} 
window.parent.location.href="/{!Account.Id}/e?&clone=1&retURL=/{!Account.Id}";

Note: retUrl specifies the location where you want to be on press of back button.