SEOSEO News

Coding Marvels: Navigating Dynamic Apex in Salesforce / Blogs / Perficient


Aloha Trailblazers!

Today we are going to understand and learn more about dynamic apex. As per Salesforce Documentation, Dynamic Apex enables developers to create more flexible applications. In simpler terms dynamic apex allows you to create generic code that could be reused along with multiple sObjects.Thus reducing the overhead of creating the block of code multiple times for multiple objects. The term “Dynamic” usually means typing wherein your variable doesn’t have a fixed type.

An important feature of a dynamic language is “Late binding”. In this, the binding of methods and functions to their definitions is done at the run time rather than at the compile time. This allows you to define the methods, modify the class structure, and even add or delete methods at runtime.

Dynamic languages also support another important feature called “reflection”. Wherein a program can modify itself by inspecting its own structure and behavior.

Is Apex a dynamic language?

Apex is a statically typed object-oriented language, but it also has dynamic programming language features. In Apex you can build classes and methods to work with any objects(custom or standard) without actually hardcoding it’s names.

The adaptability of this reusability aspect is excellent, suitable for crafting a versatile data access layer capable of querying, inserting, and updating any object. It’s particularly useful for integrating with external systems where integration logic may undergo changes.

Many Apex frameworks, including Salesforce ISV products, heavily rely on the dynamic features of the language. ISVs extensively use these capabilities to ensure their products can be easily used across different Salesforce orgs, regardless of customization and metadata. For example, they achieve this by creating dynamic Apex methods and triggers using the Tooling API.

Dynamic SOQL

Dynamic SOQL refers to the creation of a SOQL string at run time with apex code. For example, you can create a search based on input from the user.

To create a dynamic SOQL query at run time you have to use the Database.query or Database.querywithbinds methods.

The following code snippet returns more than a single record:

List<sObject> sobjList = Database.query(string);

The code snippet below returns a list of sObjects using a map of bind variable:

List<sObject> sobjList = Database.queryWithBinds(string, bindVariablesMap, accessLevel);

Handling Record Types via Dynamic Apex

One of Salesforce’s best practices is not hardcoding the IDs of your metadata this can significantly reduce the chances of error.

Dynamic Apex enables you to handle different record types and access their ID and labels dynamically.

Handling Record Types

Managing Permissions via Dynamic Apex

You can use dynamic apex to check a user’s access to a specific object or its fields.

The below code snippet demonstrates the use of Schema describe methods to check a user’s accessibility to the Name field of Contact Object. You can thus programmatically determine the user’s access levels. This can be further helpful in enforcing appropriate field-level security.

Managing Permissions Via Dynamic Apex

Dynamic Trigger Login

Dynamic trigger logic refers to the ability to create triggers in Salesforce Apex code that can adapt to different conditions or events at runtime. This means you can write Apex code that can change its behavior based on various factors, such as field values, user permissions, or even metadata settings.

Here’s a simplified example to illustrate dynamic trigger logic:

Let’s say you want to create a trigger that automatically assigns a task to a user whenever a new lead is created. However, you also want to customize this behavior based on specific criteria, such as the lead’s source or industry.

trigger LeadTrigger on Lead (after insert) {

    // Loop through all the new leads

    for (Lead newLead : Trigger.new) {

        // Check if the lead's source is 'Web' and industry is 'Technology'

        if (newLead.LeadSource == 'Web' && newLead.Industry == 'Technology') {

            // Create a task and assign it to a specific user

            Task newTask = new Task();

            newTask.Subject="Follow up on Technology Lead";

            newTask.Priority = 'Normal';

            newTask.Status="Not Started";

            newTask.OwnerId = '005XXXXXXXXXXXX'; // Replace with the Salesforce user ID

            newTask.WhatId = newLead.Id;


            // Insert the task record

            insert newTask;

        } else {

            // Custom logic based on other conditions


        }

    }

}

 

In this example, we have a trigger called LeadTrigger that fires after new lead records are inserted (after insert). Inside the trigger, we iterate over each new lead (for (Lead newLead : Trigger.new)) and check specific conditions (if (newLead.LeadSource == ‘Web’ && newLead.Industry == ‘Technology’)). If the conditions match, we create a task and assign it to a specific user.

The key point here is that the trigger logic is dynamic because it can be customized and adapted based on different conditions or events. The flexibility of Dynamic Apex simplifies trigger management and maintenance. This is particularly beneficial in complex Salesforce org configurations with multiple triggers and varying requirements.

Enhancing VF pages with Dynamic Component Generation

In Salesforce development, VF Pages serve as the backbone for creating user interfaces for specific business needs. While traditional development methods involve manually creating HTML for each element, dynamic component generation offers a more efficient approach. By using Visualforce’s dynamic rendering capabilities, developers can create customizable user interfaces to adapt to runtime data.

Here’s a practical example demonstrating dynamic component generation in action. In the Visualforce page below, we utilize the <apex:repeat> tag to iterate over a list of accounts returned by the getAccounts() method in the controller. Within the repeat block, we employ <apex:outputPanel> to structure each account’s details, dynamically populating fields such as name, industry, and annual revenue using expressions like {!acc.Name}, {!acc.Industry}, and {!acc.AnnualRevenue}.

Vf Page Example

In the corresponding Apex controller, the getAccounts() method queries the necessary fields from the Salesforce database and returns a list of accounts. This list is then utilized by the Visualforce page to dynamically generate components, ensuring that the user interface remains responsive to changes in data.

Apex Code For Vf Page

Embracing dynamic component generation in Visualforce development streamlines code, enhances flexibility, and builds more resilient user interfaces. This approach empowers organizations to adapt and evolve their applications in response to changing business requirements.

Best practices

Governor Limits Awareness: Ensure your code complies with Salesforce governor limits to handle large data volumes efficiently.

Error Handling: Implement robust error handling mechanisms, including try-catch blocks, to manage exceptions gracefully and prevent failures.

Security Considerations: Sanitize user inputs, validate access permissions, and follow Salesforce security best practices to protect sensitive data.

Code Maintainability: Write clean, well-documented code with meaningful variable names and comments to enhance readability and maintainability.

Testing Strategy: Develop comprehensive unit tests covering various scenarios, including positive and negative test cases, to validate Dynamic Apex functionality thoroughly.

Concluding note on Dynamic Apex

Dynamic Apex provides Salesforce developers with a range of opportunities, allowing for flexible and powerful code. From managing permissions to constructing dynamic queries and robust frameworks, Dynamic Apex is essential for modern Salesforce development. Its adaptability enables it to respond to changing requirements without structural code alterations. By understanding its features and best practices, developers can leverage Dynamic Apex to create resilient, adaptable, and innovative applications.

You may also explore

Top 5 Salesforce Best Practices on Apex Code





Source link

Related Articles

Back to top button
Social media & sharing icons powered by UltimatelySocial
error

Enjoy Our Website? Please share :) Thank you!