Showing posts with label Dynamic Apex. Show all posts
Showing posts with label Dynamic Apex. Show all posts

Saturday, March 20, 2021

System.TypeException: Cannot have more than 10 chunks in a single operation

 While working on requirement where we have to perform DML on multiple object dynamically by using sobject, we got below error:


"System.TypeException: Cannot have more than 10 chunks in a single operation. Please rearrange the data to reduce chunking."


This kind of error appears if your list of sobject contains more than 10 types of object records or record of objects are not ordered based on object. For example if you are adding lead, account and contact record to sobject list by using below format:

Lead1,Account1,Contact1,Lead2,Account2,Contact2,Lead3,Account3,Contact3,Lead4,Account4,Contact4

This will be considered as 12 chunks on sobject and while performing DML, you will get this error.

If you want to avoid it, then rearrange the records in below format:

Lead1,Lead2,Lead3,Lead4,Account1,Account2,Account3,Account4,Contact1,Contact2,Contact3,Contact4

This sequence of records will be considered as 3 chunks and is allowed in single DML operation.

Execute below script and you will get this error:

List<sObject>  sbList=new List<sObject>();

for(integer i=0;i<10;i++){

    sblist.add(new Lead(lastname='Test Leat'+i,company='test company'+i));

    sblist.add(new Account(name='Test Account'+i));

    sblist.add(new Contact (lastname='test name'+i,email='test@gmail.com'+i));

}

insert sblist;



Ways to resolve this kind of error:

  • Rearrange the records in list so that all records belonging to one object are stored together in list.

List<sObject>  sbList=new List<sObject>();
for(integer i=0;i<10;i++){
    sblist.add(new Lead(lastname='Test Leat'+i,company='test company'+i));
}
for(integer i=0;i<10;i++){
    sblist.add(new Account(name='Test Account'+i));
}
for(integer i=0;i<10;i++){
    sblist.add(new Contact (lastname='test name'+i,email='test@gmail.com'+i));
}
insert sblist;

  • Sort the sobject list before performing DML

List<sObject>  sbList=new List<sObject>();
for(integer i=0;i<10;i++){
    sblist.add(new Lead(lastname='Test Leat'+i));
    sblist.add(new Account(name='Test Account'+i));
    sblist.add(new Contact (lastname='test name'+i,email='test@gmail.com'+i));
}
sblist.sort();
insert sblist;

Hope this will help!!




Sunday, August 11, 2019

Accessing Child Records from sObjects using getSobjects method

Dynamic queries plays very important role when we need to run different SOQL based on different inputs. By using dynamic apex, we can store the output of queries in sObjects list and then can even check if parent record contains any child records. Even if you want to fetch child record information then you can use "getSobjects('relationshipname') method to get child information.

Below is code snippet to get all opportunities and contacts information related to Account:

Hope this will help!!!

Thursday, June 13, 2019

Accessing Parent Field Values from sObjects in Dynamic Queries Using Dynamic Apex

In case of dynamic queries, we often store queries output in sObject and then refer field values. In order to refer field values, we first type cast generic sObject into specific objects like Account, Contact or custom objects as mentioned below:

string qString = 'Select id, name from Account Limit 1';
sObject sb = database.query(qString);
Account acc = (Account)sb;
string accountName = acc.Name;

Suppose we know the field API names then we can utilize the concept of sObject to get field values directly without type casting as mention below:

string qString = 'Select id, name from Account Limit 1';
sObject sb = database.query(qString);
string accountName = sb.get('Name');

So now with the help of sObjects concept, we can access parent field values from child records.

Now consider a scenario in which I have list which stores all field API names which can be used to query opportunity line items. I will generate the dynamic query and will use concept of sObject to access Opportunity fields from sObject which is output of dynamic query.

List<string> fieldAPINamesList = new List<string>{'Id','Opportunity.Name','Opportunity.Partner__r.Name'};
string qString ='Select '+string.join(fieldAPINamesList,',')+ ' from OpportunityLineItem where id=\'00k90000002z4ml\'';
system.debug('****qString:'+qString);
sobject sb = database.query(qString);
//syntax to get OpportunityLineItem Id  value from sObject
string OpportunityLineItemId = string.valueof(sb.get('Id'));
system.debug('******OpportunityLineItemId:'+OpportunityLineItemId);
//syntax to get Opportunity.Name field value from sObject
string OpportunityName = string.valueof(sb.getSobject('Opportunity').get('Name'));
system.debug('******OpportunityName:'+OpportunityName);
//syntax to get Opportunity.Partner__r.Name field value from sObject
//If partner field in opportunity is blank then you will get null pointer exception
string partnerName = string.valueof(sb.getSobject('Opportunity').getSObject('Partner__r').get('Name'));
system.debug('******partnerName:'+partnerName);

Note: While accessing the parent record details in child to parent query, you will get null pointer exception if parent is blank in child record.

I have written an utility method which takes sObject and fieldAPIName as a parameter and returns field value. Please refer below code for reference:

If you run above script in developer console by specifying correct opportunityLineItem Id, then you will see below logs:


Hope this will help!!!

Thursday, May 30, 2019

How to get all Child Objects List along with Relationship Names related to Parent Object using Apex

Sometimes it is required to get the list of all child relationship names in order to identify all related child objects to a parent object.

Dynamic apex helps to find out all related child object. Suppose you want to find all related object for Account then use below code snippet:



You can specify any object API name and run this code snippet in developer console.

You can also use workbench to find out list of child objects. Navigate to Info tab and select Standard & Custom Objects.


Hope this will help!!

Monday, October 29, 2018

Way to get complete RecordType Information (like DeveloperName) using describe

In summer'18 release, new methods have been introduced through which we can retrieve all recordtype info using describe information. Below are 2 methods introduced in summer'18:

  • Schema.DescribeSObjectResult.getRecordTypeInfosByDeveloperName()
  • Schema.RecordTypeInfo.getDeveloperName()

Suppose you want to retrieve all recordtype information for account object then use below code:

Below is console output

Hope this help!!

Thursday, June 1, 2017

Generic Dynamic & Responsive Datatable Lightning Component with Sort, Search and Pagination Feature

Sometimes it is required to display set of records in Lightning component with different features like sort, search and pagination. In order to perform this operation every time with help of server side controller is not advisable approach specially for lightning experience.

I have created Lightning datatable component which can display records from any sobject. You need to specify below mention component attributes and it will display record in datatable with all features.


  • objAPIname (Like Account, Contact etc.)
  • fieldsAPINameList (comma seperated field API names like "Name,Type,Industry")
  • columnsLabelList (comma seperated column labels which you to specify like "Account Name, Type, Industry")
  • sortingOrder (specify field to sort records like "LastModifiedDate DESC")
  • columnForHyperLink (specify Field API name which will appear as hyper link for record detail page)
  • filterCriteria (criteria to filter records like "Industry !=null")
  • recordsLimit (number of records returned from sobject like 200, 100 etc)

Now we are going to display contact records in datatable by using below syntax in any app or withing any component:


<c:LightningJSONDataTable objAPIname="Contact"     
fieldsAPINameList="Name, Account.Name, Email"
columnsLabelList="Contact name, Account Name, Email"
sortingOrder="LastModifiedDate DESC" 
columnForHyperLink="Name"
filterCriteria="Email != null" 
recordsLimit="100"/>

below is image snapshot:


You can download the complete code from below URL:

Or you can install unmanaged package from below URL in your org:

https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000BGlf


Hope this will help!!!

More Blogs>>: 
DYNAMICALLY CREATING AND DESTROYING LIGHTNING COMPONENTS    
RAISING AND HANDLING CUSTOM EVENTS IN sALESFORCE lIGHTNING    
WHY TO USE DESIGN RESOURCE AND HOW TO ADD DYNAMIC OPTION TO DATASOURCE    
PASSING INNER WRAPPER CLASS TO LIGHTNING COMPONENT    
LIGHTNING COMPONENT FOR RECORDTYPE SELECTION FOR ANY SOBJECT    

Sunday, January 15, 2017

Customizable Visualforce Component to display Hierarchy Relationship between records for any Object (Account Hierarchy, Case Hierarchy etc.)

It is very common use case to display hierarchy relation between records in tabular form (for example account hierarchy, case hierarchy etc.) In order to achieve this, I have created a reusable visualforce component for this purpose which can be customize as per requirement to display hierarchy in table tree grid.



Below are inputs required for component:
  1. Specify the object name for which you want to display hierarchy.
  2. Specify the parent field API name (used for self relationship).
  3. Specify the API names of fields separated by comma which you want to display in table tree grid.
  4. Specify the columns labels separated by comma (make sure sequence is same as that of API fields name )for table tree grid.
  5. Specify the field API name which will display as hyperlink for record detail page.

You can create new VF page and include this component and specify above inputs and component will display the hierarchy of record starting from top most parent. 

Below is visualforce component and apex class code:


For example to generate the account hierarchy, create a VF page with code :
<apex:page controller="hierarchyComponentController">
<c:hierarchyComponent sObjectAPIName="Account" sParentfieldAPIName="ParentId" ColumnsToDispaly="Name, Type, Industry" RecordLinkfieldAPIName="Name" ColumnsLabels="Account Name, Type, Industry"/>
</apex:page>

Note: Don't forget to append record Id on visualforce page url for which you want to display hierarchy. Below is sample URL:
https://xxxxxxxxx.visual.force.com/apex/accHierarchy?id=0019000001NqoXZ

Hope this will help...

This can be used as base code and can be customize as per your requirements.

Looking forward for everyone's comment and feedback.




Refer Below Links for Salesforce Interview Questions

Tuesday, September 13, 2016

Dynamic Apex in Salesforce

You can fetch all sobject and their field information in apex by using describe methods. Apex gives 2 data types for sobject and field information.
  1. Token: A lightweight, serializable reference to an sObject or a field that is validated at compile time.
  2. Describe Result: It contains all the describe information about sobject and fields. Describe result objects are not serializable, and are validated at runtime.
It is easy to move from a token to its describe result, and vice versa. Both sObject and field tokens have the method getDescribe which returns the describe result for that token.
On the describe result, the getSObjectType and getSObjectField methods return the tokens for sObject and field, respectively.

Finding All object in Organization

Schema getGlobalDescribe method returns a map that represents the relationship between all sObject names (keys) to sObject tokens (values).
For example:
Map<String, Schema.SObjectType> schemaMapOfOrg = Schema.getGlobalDescribe();
The map has the following characteristics:
  • It is dynamic, that is, it is generated at runtime on the sObjects currently available for the organization, based on permissions.
  • The sObject names are case insensitive. 
  • The keys use namespaces as required. The keys reflect whether the sObject is a custom object.
Creating sObjects Dynamically

If we need to create contact record dynamically, then use below code:
String typeName='Contact';
Schema.SObjectType objToken = Schema.getGlobalDescribe().get(typeName);
sobject son= objToken.newSObject();
son.put('firstname','Execute1');
son.put('LastName','Kumar');
son.put('Email','sunil.kumar2@in.gmail.com');
insert son;

Apex code to find all sobject and their fields

Apex code to generate SOQL to fetch all fields of an object

Monday, September 12, 2016

RecordTypeId using Describe & SOQL

RecordTypeId of an object can be determined by using 2 different options:

For example we will find out the recordtypeId of "Renewal" recordtype of opportunity.

By Using Describe:
Id renewalRecordTypeId = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal').getRecordTypeId();
Advantage: Saves on SOQL limits but uses a describe call.

By using SOQL:
Id renewalRecordTypeId =[select id from recordType where  sobjectType='Opportunity' AND DeveloperName='Renewal'].Id;
Advantage of SOQL: If in future, someone change the name of recordtype, the code will work as it refers developername.

Thursday, May 12, 2016

Create sObjects Dynamically in Apex

If you need to create record dynamically, then use below code:

For example, we are creating a contact record. 

String typeName="Contact";
Schema.SObjectType objToken = Schema.getGlobalDescribe().get(typeName);
sobject con= objToken.newSObject();
con.put("firstname","Sunil");  //first parameter is field API name and second is its value
con.put("LastName","Kumar");
con.put("Email","sunil02kumar@gmail.com");
insert con;

You can create any object record dynamically.

If you want to insert many records through list, you can store sObjects in list of sObjects and perform DML on list. 

Monday, November 26, 2012

Viewing and Editing all Custom Settings in Visualforce Page


To see or edit custom setting records, we navigate to each custom setting, click on manage button and edit/ view custom settings records.

In order to avoid this navigation for all custom setting, I thought of creating a VF page where we can select custom setting present in organization and view/ edit records related to the selected custom settings on the same VF Page.

In order to achieve this, I have created a VF page named as "Sunil_CSDetails". Also I have created a batch class which will check for custom settings present in organization and will store their API names in one custom object (say "CS_Name__c"). You can use standard name field or custom text field (say "Name__c") to store API name of custom object.


User will click on Refresh button in order to fetch all custom settings present in the organization. After clicking on Refresh button, user will see progress bar with status. When the operation is finished, a new button will appear on the page with a message to click on that button.


After clicking on "Display Options" button, the page will display a picklist with all available custom settings and records related to selected option.
Now you can select any custom settings present in organization and view related records. Click on "Edit" button in order to edit any custom settings records.

You can download zip file from the link below which contains apex classes, VF page and custom objects.

Download Apex class and VF Page code from here

Looking forward to your comments and views.





Refer Below Links for Salesforce Interview Questions