Tag: Custom Controller

  • Interview Question Part – 3

    Interview Question Part – 3

    1. What is an Apex class in Salesforce?

    An Apex class in Salesforce is a blueprint or template for creating custom business logic and functionality. It is written in the Apex programming language, which is similar to Java, and is used to define the behavior of objects in the Salesforce platform.

    2. Explain the syntax of creating an Apex class.

    The syntax for creating an Apex class is as follows:

    public class ClassName { 
    // Class variables, properties, and methods 
    }

    The keyword “public” denotes the access level of the class, and it can be either public or private. The class name follows the “class” keyword, and the body of the class is enclosed within curly braces.

    3. What is the difference between a standard controller and a custom controller?

    A standard controller is a pre-built controller provided by Salesforce for standard objects like Account, Contact, or Opportunity. It provides basic functionality and automatically handles most of the operations related to data retrieval, manipulation, and standard page actions.

    On the other hand, a custom controller is a controller that you create to define custom logic and behavior for a Visualforce page or a Lightning component. It allows you to implement custom business processes and extend functionality beyond what is provided by the standard controller.

    4. How can you define a method in an Apex class?

    public returnType methodName(parameterList) { 
    // Method body 
    }

    5. What is the purpose of the “public” and “private” access modifiers in Apex?

    The “public” and “private” access modifiers in Apex control the visibility and accessibility of variables and methods within a class.

    1. public” means that the variable or method can be accessed from outside the class.
    2. private” means that the variable or method can only be accessed within the class itself.

    By using these access modifiers, you can define the level of encapsulation and control the interaction with the class’s internal members.

    dont miss out iconDon’t forget to check out: Are You Here To Know Reasons To Hire Salesforce Developer For Your Business?

    6. Explain the difference between “static” and “instance” methods in Apex.

    In Apex, the “static” keyword is used to define a method or variable that belongs to the class itself rather than an instance of the class. It means that the method or variable can be accessed without creating an instance of the class.

    On the other hand, an “instance” method is a method that operates on a specific instance of a class. It requires an object of the class to be created, and the method is invoked on that object.

    “static” methods or variables are associated with the class itself, while “instance” methods or variables are associated with individual instances of the class.

    7. How do you define a variable in Apex? What are the different data types available?

    In Apex, you can define a variable using the following syntax:

    dataType variableName [= initialValue];

    The dataType specifies the type of data that the variable can hold, and the variableName is the name you give to the variable. The “= initialValue” part is optional and is used to assign an initial value to the variable.

    Apex supports various data types, including primitives like Integer, Boolean, and String, as well as complex types like sObjects, lists, and maps.

    8. How can you implement exception handling in Apex?

    Ans. Exception handling in Apex allows you to catch and handle errors or exceptional situations that may occur during the execution of your code. You can implement exception handling using try-catch blocks.

    try { 
    // Code that may throw an exception 
    } 
    catch (ExceptionType e) { 
    // Code to handle the exception 
    }

    Inside the try block, you place the code that may throw an exception. If an exception occurs, it is caught by the catch block, where you can handle the exception appropriately. The “ExceptionType” specifies the type of exception you want to catch.

    You can use “finally” blocks to specify code that should be executed regardless of whether an exception is thrown or not.

    9. Explain the difference between a trigger and an Apex class.

    A trigger is an Apex code that is executed before or after specific data manipulation operations, such as insert, update, delete, or undelete, on Salesforce objects. Triggers are used to enforce data integrity, perform additional logic, or update related records based on certain conditions.

    On the other hand, an Apex class is a general-purpose class that can be written to encapsulate business logic and reusable functionality. It can be invoked from various contexts like triggers, Visualforce pages, or Lightning components.

    In summary, a trigger is specific to a particular object and is automatically executed based on data manipulation events, while an Apex class is a reusable piece of code that can be invoked from multiple contexts.

    10. How can you write a test class for an Apex class? What is the purpose of test classes?

    To write a test class for an Apex class, you create a separate class in Salesforce that contains test methods. Test classes are used to verify that your code works as expected and to achieve code coverage, which is a requirement for deploying Apex code to production.

    The purpose of test classes is to simulate different scenarios and assert the expected outcomes. They help ensure that the code is functioning correctly and prevent regressions when making changes.

    Test classes follow a naming convention and are annotated with the @isTest annotation. Inside the test class, you write methods with the @isTest annotation to define test methods.

    11. What are the best practices for writing efficient Apex code?

    Best practices for writing efficient Apex code include:

    1. Bulkify your code: Design your code to process data in bulk to avoid hitting governor limits and improve performance.
    2. Use selective queries: Query only the necessary data to minimize database operations and optimize performance.
    3. Minimize SOQL and DML statements: Reduce the number of queries and updates to conserve resources.
    4. Avoid nested loops: Nested loops can result in poor performance. Use collections and efficient algorithms to avoid nested loops whenever possible.
    5. Cache frequently accessed data: Store frequently accessed data in memory for faster access and reduced database calls.
    6. Handle exceptions gracefully: Implement proper exception handling to handle errors and prevent unhandled exceptions from impacting the user experience.
    7. Follow naming conventions: Use clear and descriptive names for variables, classes, and methods to enhance code readability.
    8. Use governor limit-aware coding: Be aware of the Salesforce governor limits and design your code to stay within those limits.
    9. Write comprehensive unit tests: Ensure that your code is thoroughly tested to catch any issues early and maintain code quality.

    12. How can you query records from the database using SOQL in Apex?

    SOQL (Salesforce Object Query Language) is used to query records from the database in Salesforce. In Apex, you can use SOQL statements to retrieve records based on specified conditions.

    The basic syntax for a SOQL query in Apex is as follows:

    List<SObject> records = [SELECT field1, field2 FROM ObjectName WHERE condition];

    1. “List<SObject>” defines the variable to store the query results.
    2. “SELECT field1, field2” specifies the fields to retrieve from the object.
    3. “FROM ObjectName” specifies the object to query.
    4. “WHERE condition” filters the records based on specified conditions.

    You can also use additional clauses like ORDER BY, LIMIT, and OFFSET to further refine your queries.

    13. What is the purpose of DML statements in Apex? Give examples of different DML operations.

    DML (Data Manipulation Language) statements in Apex are used to perform CRUD (Create, Read, Update, Delete) operations on records in the database.
    Some examples of DML operations in Apex are:

    Inserting a Record:

    ObjectName record = new ObjectName(field1 = value1, field2 = value2); 
    insert record;

    Updating a Record:

    ObjectName record = [SELECT field1, field2 FROM ObjectName WHERE Id = 'recordId']; 
    record.field1 = newValue;
    update record;

    Deleting a Record:

    ObjectName record = [SELECT field1, field2 FROM ObjectName WHERE Id = 'recordId']; 
    delete record;

    DML statements are used to interact with the database and modify record data.

    14. How do you enforce sharing rules in an Apex class?

    Sharing rules in Salesforce determine the level of access users have to records. In an Apex class, you can enforce sharing rules by using the “with sharing” keyword.

    By default, Apex classes run in system mode, which ignores the organization’s sharing rules. However, when you specify “with sharing” in the class definition, the class runs in user mode, respecting the sharing rules.

    This means that the code inside the class will honor the record-level access permissions and sharing settings defined by the organization’s sharing rules, profiles, and sharing settings.

    Enforcing sharing rules ensures that the Apex class operates within the defined access controls, providing the appropriate level of record visibility and security.

    15. Explain the difference between a constructor and a method in Apex.

    Ans. In Apex, a constructor is a special method used to initialize the object of a class. It is invoked when an object is created using the “new” keyword. Constructors have the same name as the class and do not specify a return type.

    public class MyClass { 
        public MyClass() { 
             // Constructor logic 
        } 
    }

    On the other hand, a method is a block of code that performs a specific action. Methods are used to encapsulate reusable functionality within a class. They can accept input parameters, execute a series of statements, and optionally return a value.

    The main difference between a constructor and a method is that a constructor is automatically invoked when an object is created, whereas a method is called explicitly by the code.

    16. What is the “with sharing” keyword in Apex? How does it impact record visibility?

    Ans. The “with sharing” keyword in Apex is used to enforce record-level access permissions and sharing rules in a class. When a class is declared with “with sharing,” it runs in user mode and respects the organization’s sharing rules.

    The “with sharing” keyword affects the visibility of records based on the user’s access permissions, profile settings, and sharing rules. It ensures that the code in the class only works with the records that the user has proper access to, providing a secure and controlled environment.

    By default, Apex classes run in system mode, which ignores sharing rules. However, when “with sharing” is specified, the class operates in user mode and respects the sharing settings.

    17. How can you schedule Apex classes to run at specific times?

    Ans. You can schedule Apex classes to run at specific times using the Schedulable interface in Apex. The Schedulable interface allows you to define a class as a scheduled job that can be executed according to a specified schedule.

    To schedule an Apex class, you need to implement the Schedulable interface and define the schedule using the System.schedule method.

    Here’s an example of scheduling an Apex class to run every day at a specific time:

    public class MyScheduledClass implements Schedulable { 
         public void execute(SchedulableContext context) { 
         // Logic to be executed on schedule 
         } 
    } 
    // Schedule the Apex class to run every day at 8 AM String cronExp = '0 0 8 * * ?'; 
    String jobName = 'MyScheduledJob'; System.schedule(jobName, cronExp, new MyScheduledClass());

    This code schedules the MyScheduledClass to run every day at 8 AM based on the specified cron expression.

    18. What is the purpose of the “Database” class in Apex?

    Ans. The “Database” class in Apex provides methods to perform database operations like insert, update, upsert, delete, and query records. It also allows you to interact with records in bulk and handle governor limits.

    Some common use cases for the “Database” class include:

    1. Performing DML operations on records in bulk.
    2. Querying records with dynamic SOQL queries.
    3. Inserting or updating records while bypassing triggers.
    4. Handling partial success and DML exceptions.
    5. Retrieving the ID of the inserted or updated record.

    The “Database” class provides additional capabilities beyond the standard DML statements and is useful for advanced database operations in Apex.

    19. How can you implement asynchronous processing in Apex?

    Ans. Asynchronous processing in Apex allows you to execute code in the background without blocking the user interface or other operations. It helps improve performance and provides a way to handle long-running or resource-intensive tasks.

    To implement asynchronous processing, you can use features like future methods, batch Apex, and queueable Apex.

    1. Future methods: They are annotated with the @future annotation and allow you to execute a method asynchronously. The method is queued for execution and runs in a separate thread.
    2. Batch Apex: It allows you to process large sets of data in smaller chunks or batches. Batch Apex jobs are divided into multiple batches, and each batch is processed independently.
    3. Queueable Apex: It allows you to chain and schedule the execution of jobs. Each job is added to a queue and executed in sequence, providing flexibility and control over the execution order.

    These asynchronous processing methods help handle time-consuming tasks, integrate with external systems, and perform complex operations in a scalable manner.

    20. Explain the concept of batch Apex and its use cases

    Ans. Batch Apex is a feature in Salesforce that allows you to process large sets of data asynchronously in smaller chunks or batches. It is useful when dealing with large data volumes that exceed the normal governor limits.

    Batch Apex jobs are divided into multiple batches, and each batch can process a subset of the data. The data is processed in a batch-by-batch manner, and the results can be collected and processed after each batch or at the end of the job.

    Batch Apex jobs follow a specific pattern:

    1. Start method: It collects the initial set of records to be processed and sets up the batch job.
    2. Execute method: It processes each batch of records and performs the required operations.
    3. Finish method: It handles any post-processing tasks after all batches have been executed.

    Batch Apex is useful for data transformation, data migration, complex calculations, and other scenarios where large volumes of data need to be processed efficiently.

    21. What are governor limits in Apex? How do they impact the execution of code?

    Ans. Governor limits in Apex are runtime limits set by Salesforce to ensure the efficient and fair use of shared resources. They restrict the number of resources a transaction or code execution can consume, such as CPU time, heap size, database queries, and DML operations.

    Governor limits impact the execution of code by enforcing certain boundaries to prevent abuse, optimize performance, and maintain system stability. If a transaction or code execution exceeds the limits, it results in a runtime exception.

    Developers need to be mindful of governor limits when writing Apex code to avoid hitting limits and ensure the code performs optimally.

    Examples of governor limits include:

    1. CPU time limit: Specifies the maximum amount of CPU time a transaction can use.
    2. Query rows limit: Restricts the number of records that can be returned in a single query.
    3. Heap size limit: This limits the amount of memory a transaction can use.
    4. DML statements limit Limits the number of records that can be inserted, updated, or deleted in a single transaction.

    Understanding and optimizing code to stay within governor limits is crucial for maintaining a scalable and efficient Salesforce application.

    22. How can you implement triggers in Apex? What are the different trigger events available?

    Ans. Triggers in Apex are pieces of code that execute before or after specific data manipulation operations, such as insert, update, delete, or undelete, on Salesforce objects. They are used to enforce data integrity, perform additional logic, or update related records based on certain conditions.

    To implement triggers, you define trigger handlers that contain the logic to be executed when a trigger event occurs. Trigger handlers can be written as separate classes or as methods within the trigger itself.

    Trigger events include:

    1. before insert: Triggered before records are inserted.
    2. before update: Triggered before records are updated.
    3. before delete: Triggered before records are deleted.
    4. after insert: Triggered after records are inserted.
    5. after update: Triggered after records are updated.
    6. after delete: Triggered after records are deleted.
    7. after undelete: Triggered after records are undeleted.

    By using triggers, you can automate processes, maintain data integrity, and extend the functionality of Salesforce objects.

    dont miss out iconCheck out another amazing blog by Aman here: Mule Dreamin: Shaping MuleSoft+Salesforce Together for a Powerful Integration

    23. Explain the difference between a before trigger and an after trigger.

    Ans. Before triggers and after triggers are types of triggers in Apex that determine when the trigger logic is executed in relation to the data manipulation operation.

    1. Before triggers: They are executed before the data manipulation operation occurs. Before triggers are used to perform validation or modification on the records before they are saved to the database. They are commonly used to enforce business rules and validate data.
    2. After triggers: They are executed after the data manipulation operation occurs. After triggers are used to perform additional logic or update related records based on the changes made by the trigger operation. They can be used to update fields, create related records, or invoke external services.

    The choice between before and after triggers depends on the specific requirements of the business logic and the timing of the necessary operations.

    24. How can you implement a trigger handler class in Apex? What are the benefits of using a trigger handler pattern?

    Ans. A trigger handler class in Apex is a design pattern that separates the trigger logic from the trigger itself. It provides a structured way to handle trigger events and improves code maintainability and reusability.

    The trigger handler pattern involves creating a separate class to hold the trigger logic. The trigger itself acts as a bridge between the Salesforce platform and the trigger handler class.

    Benefits of using a trigger handler pattern include:

    1. Separation of concerns: The trigger handler class focuses solely on the trigger logic, making it easier to understand and maintain.
    2. Reusability: The same trigger handler class can be used for multiple triggers, reducing code duplication.
    3. Testability: The trigger handler class can be unit tested independently of the trigger.
    4. Scalability: The trigger handler pattern allows for easier extension and modification of trigger logic as business requirements change.

    By adopting the trigger handler pattern, you can write cleaner and more modular trigger code, leading to better code organization and easier maintenance.

    25. What is the purpose of the “Schema” class in Apex? How can you use it for dynamic SOQL and DML operations?

    Ans. The “Schema” class in Apex provides metadata information about the Salesforce objects, such as fields, relationships, and object definitions. It allows you to dynamically retrieve information about objects and fields at runtime.

    The “Schema” class provides methods to access and manipulate metadata, including:

    • getGlobalDescribe(): Returns a map of all object describe information.
    • getSObjectType(): Returns the SObjectType for a given object name.
    • getDescribe(): Returns the describe information for a specific object or field.

    You can use the “Schema” class for dynamic SOQL and DML operations, dynamic field retrieval, and generating dynamic user interfaces.

    For example, you can dynamically query fields based on user input, dynamically create or modify fields, or generate UI components based on the metadata obtained from the “Schema” class.

    26. How do you handle bulkification in Apex code? Why is it important?

    Ans. Bulkification in Apex refers to designing code that can efficiently process large sets of data. It involves writing code in a way that operates on collections of records rather than individual records, reducing the number of database queries and DML statements.

    Bulkification is important to avoid hitting governor limits and optimize code performance. By processing data in bulk, you can minimize the number of queries and updates, conserve resources, and improve overall execution speed.

    To achieve bulkification, you can follow these best practices:

    1. Query records in bulk: Use SOQL queries with proper filters and retrieve all necessary records in a single query instead of querying inside a loop.
    2. Perform DML operations in bulk: Use collections like lists and sets to hold records and perform DML operations on them outside of loops.
    3. Use collections for processing: Iterate over collections of records to perform calculations or operations, rather than processing one record at a time.
    4. Minimize SOQL and DML statements: Reduce the number of queries and updates by batching them together.

    By adopting these practices, you can ensure your code can handle large volumes of data efficiently and avoid performance issues.

    27. Explain the concept of a trigger context variable in Apex.

    Ans. In Apex, a trigger context variable is an object that provides contextual information about the trigger event being executed. It contains information such as the records involved, the operation type, and the trigger execution context.

    The trigger context variable is automatically available within a trigger and can be accessed using the Trigger keyword. It provides access to various trigger context variables, such as:

    1. Trigger.new: Returns a list of new records being inserted or updated.
    2. Trigger.old: Returns a list of old records before they were updated or deleted.
    3. Trigger.newMap: Returns a map of new records, with the record IDs as keys.
    4. Trigger.oldMap: Returns a map of old records, with the record IDs as keys.
    5. Trigger.isInsert: Indicates if the trigger event is an insert operation.
    6. Trigger.isUpdate: Indicates if the trigger event is an update operation.
    7. Trigger.isDelete: Indicates if the trigger event is a delete operation.

    By using the trigger context variables, you can access and manipulate the records involved in the trigger event and perform specific logic based on the operation type.

    28. How can you perform unit testing for triggers in Apex?

    Ans. Unit testing for triggers in Apex involves writing test classes to ensure the trigger logic behaves as expected and meets the desired requirements. Unit tests help validate the trigger functionality, test different scenarios, and identify potential issues or bugs.

    To perform unit testing for triggers, you typically follow these steps:

    1. Create test data: Generate the necessary records and data to replicate the trigger scenario and cover different test cases.
    2. Execute the trigger event: Perform the specific DML operation that triggers the logic, such as insert, update, or delete.
    3. Assert the expected outcome: Check if the trigger behavior matches the expected results and validate the changes made by the trigger.
    4. Handle bulk testing: Ensure the trigger handles bulk data correctly by testing with multiple records in a single transaction.
    5. Handle governor limits: Verify that the trigger stays within the governor limits and handles large data volumes efficiently.

    By writing comprehensive unit tests, you can ensure the reliability and correctness of your trigger logic and avoid regressions when making changes to the code.

    29. What is a SOQL injection? How can you prevent it in Apex?

    Ans. SOQL injection is a security vulnerability that occurs when an application allows user-supplied input to directly manipulate a SOQL query. It can lead to unauthorized access, data breaches, or data corruption.

    To prevent SOQL injection in Apex, it is essential to use parameterized queries and sanitize user input. The recommended approach is to use bind variables in your SOQL queries, where the user input is passed as a parameter rather than concatenated directly into the query.

    Here’s an example of a vulnerable query without proper prevention:

    String input = 'example';
    String query = 'SELECT Id FROM Account WHERE Name = \'' + input + '\'';
    List<Account> accounts = Database.query(query);
    To prevent SOQL injection, you should use bind variables:
    String input = 'example';
    List<Account> accounts = [SELECT Id FROM Account WHERE Name = :input];

    By using bind variables, the input is automatically sanitized and treated as a parameter, reducing the risk of injection attacks.

    30. How can you implement a batchable interface in Apex? When would you use batch Apex?

    Ans. The Batchable interface in Apex allows you to process large sets of data by dividing the workload into smaller batches. It provides a way to handle complex or time-consuming operations that exceed the normal governor limits.

    To implement the Batchable interface, you need to define three methods:

    1. start: Collects the initial set of records to be processed and sets up the batch job.
    2. execute: Processes a batch of records and performs the required operations.
    3. finish: Handles any post-processing tasks after all batches have been executed.

    Batchable jobs can be queued and run asynchronously, allowing for the efficient processing of large data volumes without hitting governor limits.

    Batch Apex is typically used for scenarios such as data transformation, data migration, data cleansing, and complex calculations where large volumes of data need to be processed in a controlled and efficient manner.

    31. What is the purpose of a queueable interface in Apex? How does it differ from batch Apex?

    Ans. The Queueable interface in Apex provides a way to execute code asynchronously in the background. It allows you to chain and schedule the execution of jobs, providing flexibility and control over the order of execution.

    Unlike batch Apex, queueable jobs don’t have specific batch size limitations and can be used for smaller-scale processing. They are useful for scenarios where you need to perform lightweight asynchronous processing, integrate with external systems, or handle time-consuming tasks without blocking the user interface.

    To implement the Queueable interface, you define a class that implements the interface and implement the execute method. The execute method contains the logic to be executed asynchronously.

    Queueable Apex jobs can be enqueued and scheduled to run at a specific time or after the completion of other jobs, allowing for efficient job management and resource utilization.

    32. How can you handle exceptions and errors in Apex? What are the best practices?

    Ans. Exception handling in Apex allows you to handle and recover from runtime errors, ensuring the stability and reliability of your code. When an exception occurs, the normal flow of execution is disrupted, and control is transferred to the exception handling code.

    In Apex, you can handle exceptions using try-catch blocks. The try block contains the code that may throw an exception, and the catch block handles the exception and defines the desired behavior.

    Here’s an example of exception handling in Apex:

    try { 
         // Code that may throw an exception Integer result = 10 / 0; 
         // Division by zero 
        } 
    catch (Exception e) { 
        // Exception handling code System.debug('An exception occurred: ' + e.getMessage()); 
    }

    In the example, if an exception occurs during the division operation, the control is transferred to the catch block, and the exception message is logged.

    Best practices for exception handling in Apex include:

    1. Catch specific exceptions: Handle specific exceptions rather than using a general catch-all block to handle different types of exceptions differently.
    2. Provide meaningful error messages: Log or display informative error messages to help with troubleshooting and debugging.
    3. Graceful error handling: Handle exceptions gracefully and provide fallback or alternative paths of execution when errors occur.
    4. Use system exceptions when appropriate: Utilize standard system exceptions for common error conditions, such as DmlException or QueryException.

    By implementing effective exception handling, you can improve the robustness and reliability of your Apex code.

    33. Explain the concept of a “helper” class in Apex. Why would you use it?

    Ans. In Apex, a “helper” class refers to a class that provides reusable methods or functionality to assist other classes or components. Helper classes are used to modularize code, improve code organization, and promote reusability.

    Here are some reasons why you would use a helper class:

    1. Code organization: Helper classes separate specific functionality from the main class, making the codebase more manageable and maintainable.
    2. Reusability: Helper methods can be shared and used by multiple classes or components, avoiding code duplication.
    3. Encapsulation: By encapsulating related functionality in a helper class, you can provide a clean and concise API to other classes, abstracting the underlying implementation details.
    4. Testability: Helper methods can be unit tested independently, simplifying the testing process and ensuring the correctness of the functionality.
    5. Modularity: Helper classes can be easily updated or replaced without affecting the main class, promoting code extensibility and flexibility.

    Overall, using helper classes helps improve code structure, maintainability, and code reuse in Apex development.

    34. How can you make a callout to an external system from Apex code?

    Ans. To make a callout to an external system from Apex code, you can use Apex HTTP classes. Salesforce provides a robust set of classes for making HTTP requests and handling responses.

    Here’s an example of making a callout using Apex HTTP classes:

    HttpRequest request = new HttpRequest(); 
    request.setEndpoint('https://api.example.com/endpoint'); 
    request.setMethod('GET'); 
    HttpResponse response = new HttpResponse(); 
    Http http = new Http(); try { response = http.send(request); 
    if (response.getStatusCode() == 200) { 
         // Handle successful response String responseBody = response.getBody(); 
         // Process the response 
         } 
         else { 
         // Handle error response String errorMessage = 'Callout error: ' + response.getStatusCode() + ' - ' + response.getStatus(); // Handle the error 
         } 
    } 
    catch (Exception e) { 
    // Handle exception System.debug('Exception: ' + e.getMessage()); 
    }

    In the example, an HTTP GET request is made to an external API endpoint. The response is then handled based on the status code and processed accordingly.

    Apex HTTP classes allow you to make various types of HTTP requests, set request headers, handle request and response bodies, and handle errors or exceptions that may occur during the callout.

    35. What is the purpose of a future method in Apex? When would you use it?

    Ans. The “future” method in Apex is used to perform long-running or time-consuming operations asynchronously. It allows you to execute a method in the background without blocking the user interface.

    A future method is defined using the @future annotation and must return void. It can be called trigger handlers, Visualforce pages, or other Apex code.

    Here’s an example of a future method:

    public class MyFutureClass { 
         @future public static void performLongOperation() 
         { 
              // Perform long operation asynchronously // ... 
         } 
    }

    In the example, the performLongOperation the method is marked with the @future annotation, indicating that it should be executed asynchronously.

    Future methods are commonly used for tasks such as sending emails, making external callouts, performing calculations, or executing any other operations that may take a significant amount of time.

    By using future methods, you can offload time-consuming operations to run asynchronously and ensure a smooth user experience.

  • Learn All About Visualforce in Salesforce – The Complete Guide

    Learn All About Visualforce in Salesforce – The Complete Guide

    Introduction

    With the help of the web development framework Visualforce, programmers may create complex, unique user interfaces for desktop and mobile apps that can be hosted on the Lightning Platform. You can use Visualforce to create apps that follow the Lightning Experience’s design guidelines as well as your own entirely unique user interface.

    Developers can add new functionality to existing Salesforce features, replace existing features with new ones, and create entirely new apps using Visualforce. Use the robust standard controller functions that are already included or create your own unique business logic with Apex. You can develop tools for your own business or make programs to sell on the AppExchange.

    Anyone who has developed web applications is familiar with visual force app development. By combining components, HTML, and optional stylistic components, developers build Visualforce pages. For a more lively and rich user experience, Visualforce can integrate with any mainstream web technology or JavaScript framework. There is a distinct URL for each page. When a page is accessed, the server renders the page into HTML, handles any data processing necessary for it, and sends the output to the browser for display.

    dont miss out iconDon’t forget to check out: Share Visualforce Pages Between Classic and Lightning Experience | Salesforce Trailhead

    Developers can use Visualforce to create a Visualforce page definition. A page definition consists of two primary elements:

    • Visualforce Markup
    • A Visualforce Controller

    Visualforce Markup

    Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code contained within a single <apex: page> tag. The markup specifies which user interface elements should be present on the page and how they should be displayed.

    Visualforce Controllers

    A connected Visualforce markup component has a set of instructions called a Visualforce controller that describe what occurs when a user interacts with that component, such as clicking a button or link. Additionally, controllers provide users access to the data that should be presented on a page and have the power to change how components behave.

    Developers have two options for adding controller logic: using a standard controller from the Lightning platform or creating a custom controller by creating a class in Apex.

    Standard Controller: A standard controller consists of the same functionality and logic that is used for a standard Salesforce page. For example, if you use the standard Accounts controller, clicking a Save button on the Visualforce page results in the same behaviour as clicking Save on a standard Account edit page.

    Custom Controller: A custom controller is a class created in Apex that implements all of a page’s functionality independently of a standard controller. You can specify new navigational items or actions when using a custom controller, but you must also reimplement any functionality that was previously supplied by a standard controller.

    Developers can also use extensions for adding extra functionality to standard or custom controllers. A controller extension is an Apex class that extends or replaces the behaviour of a standard or custom controller. Extensions allow you to use another controller’s functionality while adding your own custom logic.

    Visualforce Pages Have Various Use Cases

    Visualforce pages can be used by developers to:

    • Standard buttons, such as the new button for accounts or the Edit button for contacts, can be overridden.
    • Override tab overview pages, such as the home page of the Accounts tab.
    • Define custom tabs
    • Include components in detailed page layouts.
    • Create dashboard components or personalized help pages.
    • Customize, extend, or integrate the Salesforce console’s sidebars (custom console components)
    • In the Salesforce mobile app, add navigation menu items and actions.

    dont miss out iconCheck out another amazing blog by Parvez here: RemoteAction Annotation In Apex | Salesforce Apex Developer Guide

    Example of VF Page:

    <apex:page standardController="Account" recordSetVar="accounts"
    tabstyle="account" sidebar="false">
        <apex:pageBlock >
            <apex:form >
              <apex:pageBlockTable value="{!accounts}" var="a" id="list">
                <apex:column value="{!a.name}"/>
                <apex:column value="{!a.AccountNumber}" />
              </apex:pageBlockTable>
            </apex:form>
         </apex:pageBlock>
    </apex:page>
  • Salesforce Interview Questions – Part 1

    Salesforce Interview Questions – Part 1

    1. Give me an example of one admin part and one development part which is used in the current organisation.

    2. What is the difference between a data loader and a data import wizard?

    Data Import Wizards Data Loader
    You need to load less than 50,000 records. You need to load 50,000 to five million records. If you need to load more than 5 million records.
    The objects you need to import are supported by the wizard. You need to load into an object that is not supported by the Data Import Wizard.
    You don’t need the import process to be automated. You want to schedule regular data loads, such as nightly imports

    3. What is the difference between batchable and schedulable class?

    Schedulable Class Batchable Class
    To execute any class at a specific time we use the scheduling apex It divides the whole process into batches (each batch handles 200 records at a time).
    first needs to implement the Schedulable interface for the class First need to implement the Salesforce-provided interface Database.Batchable
    The Schedulable interface contains one method that must be implemented, execute The Batchable interface contains three methods that must be implemented, Start, Execute, Finish
    Run Scheduled Class like that :
    YourScheduleApexClass s=new YourScheduleApexClass();
    s.execute(null) ;
    Run Batch Class like that :
    Id <variable name>= Database.executeBatch(new <Class name>(), batch size);

    4. What are the future methods?

    A future method runs in the background, asynchronously. You can call a future method for executing long-running operations. Each future method is queued and executes when system resources become available. The execution of your code doesn’t have to wait for the completion of a long-running operation.

    5. What are the governor limits?

    Apex runs in a multitenant environment, the Apex runtime engine strictly enforces limits so that runaway Apex code or processes don’t monopolize shared resources. These limits count for each Apex transaction.

    For Batch Apex, these limits are reset for each execution of a batch of records in the execute method.

    Batch Apex
    Apex Transaction Limits
    Apex Transaction Limits

    6. What is the difference between SOQL and SOSL?

    SOQL(Salesforce Object Query Language) SOSL(Salesforce object Search Language)
    Using SOQL we can Search only on one object at a time. Using SOSL we can search on many objects at a time.
    We can query on all fields of any data type We can query only on fields whose data type is text,phone and Email.
    We can use SOQL in Triggers and classes. We can use in calsses but not in Triggers.
    We can perform DML operation on query results. We cannot perform DML operation on search result

    7. How to write a test class?

    @isTest
    private class MyTestClass {
        @isTest static void myTest() {
            // code_block
        }
    }

    dont miss out iconDon’t forget to check out: Fair Interview Conversation with Certified Salesforce Business Analyst

    8. What are the different types of events in triggers?

    Here is a list of trigger events in Salesforce:

    • before insert
    • before update
    • before delete
    • after insert
    • after update
    • after delete
    • after undelete

    9. What are the different types of flows?

    The Salesforce Flow can be classified into five subtypes:

    1. Screen flows
    2. Schedule-triggered flows
    3. Auto launched flows
    4. Record-triggered flows
    5. Platform Event-triggered flow.

    10. What are the different uses of record-triggered and schedulable triggered flows?

    Uses of Scheduled Triggered flow:

    • A schedule-triggered flow starts at the specified time and frequency.
    • The View All Data permission is required to activate an auto-launched flow that has a trigger.
    • If a flow is scheduled to run once with a date and time that already passed, the flow doesn’t run.

    Uses of Record Triggered flow:

    • A record-triggered flow can start after the record is created or update.
    • The View All Data permission is required to activate an auto-launched flow that has a trigger.
    • Only these elements are supported: Assignment, Decision, Get Records, and Loop.

    11. Write a test class for updating account record?

    @isTest
    public class testAccountUpdate {
        @testSetup static void dataSetup() {
            Account acc = new Account();
            acc.Name = 'Person 1';
            insert ACC;
        }
        @isTest static void accountUpdate() {
            Account acc = [SELECT Name, Phone FROM Account WHERE Name='Person 1'];
            acc.Phone = 'xxx-xxx-xxxx';
            update ACC;
        }
    }

    12. What is a mixed DML error?

    This error will occur when you try to persist in the same transaction and change to a Setup Object and a non-Setup Object.

    For e.g. if you try to update an Opportunity record and a User record at the same time.

    13. What are states in vf?

    View state holds the state of the Visualforce page. the view state of a web page is composed of all the data that’s necessary to maintain the state of the controller during server requests (like sending or receiving data).

    14. What is the API used during deployment?

    Salesforce continues to support the use of checkStatus() when using deploy() with API version 28.0 or earlier.

    15. What is the difference b/w queueable and future?

    Future Method Queueable Job
    1. Future will never use to work on SObjects or object types. 1. Queueable Jobs can contain the member variable as SObjects or custom Apex Types.
    2. When using the future method we cannot monitor the jobs which are in process. 2. When using queueable jobs it will make the AsyncApexJob which we can monitor like Scheduled jobs.
    3. The future method cannot be called inside the future or batch class. 3. Queueable Apex can be called from the future and batch class.
    4. The future method will never be queued. 4. Using Queueable Apex will chain up to queueable jobs and in Developer Edition it is only 5 Jobs.

    16. What is the flow of data in lwc?

    We can Flow the data between components in Two way

    components

    LWC Data Flow
    1. Parent to Child (Passing Data Down)
    2. Child to Parent (Passing Data Up)

    17. What is the difference b/w workflow & process builder?

    Workflow is able to update some fields

    • Update a field
    • Send an email
    • Create a Task
    • Send an outbound message

    Process Builder is capable of updating any field that has any related record.

    • Create A New Record
    • Update Any Related Record
    • Quick Action To Create A Record, Update A Record Or Log A Call
    • Launch A Flow
    • Send An Email
    • Post To Chatter
    • Submit For Approval
    • Call Apex Methods

    dont miss out iconCheck out another amazing blog by Aman Garg here: Knowledge of Salesforce User Licenses and its Types

    18. What are relationships in Salesforce?

    A Relationship is a way in which two or more people or things are connected with each other.

    Different types of Relationships in Salesforce:

    • Master-Detail relationship.
    • Lookup Relationship.
    • May-Many Relationship.
    • Hierarchy Relationship (we can not use this relationship).

    19. What is the difference between Master-details & look-up relationships?

    Master-detail Relationship Lookup Relationship
    in master-detail relationship field value is mandatory in lookup relationship field value is not mandatory
    If parent record is deleted automatically child records is deleted If parent record is deleted automatically child records are not deleted
    an object is allowed only 2 master-detail relationship fields an object is allowed only 25  relationship fields
    if we give any rules to parent that rules automatically goes to the child.
    Child does not conatin any seperate rules.
    parent rules and child rules are may be same or not.
    we can directly conert master-detail relationship to lookup relationship if we cannot give a value to the lookup field then we can’t  directly conert lookup relationship
    to master-detail relationship here first we need to give a value to the lookup field.
    if we give a value tomaster-detail relationship field that value doesnot changed. if we give a value to lookup relationship field we can change that value whenever we required.

    20. What is synchronous & asynchronous apex?

    Asynchronous Apex:-

    • Asynchronous Apex is used to run processes in a separate thread, at a later time.
    • An asynchronous process is a process or function that executes a task “in the background” without the user having to wait for the task to finish.
    • Asynchronous processes are started in a new thread, with higher governor and execution limits.

    Example:
    Trigger
    Controller Extension
    Custom Controller

    Synchronous Apex:-

    • Synchronous Apex means the entire Apex code is executed in one single go.
    • Synchronous execution does not wait for available resources.

    Example:
    Batch
    @future Annotation
    Queueable Interface

    21. Write down the soql query of parent-child (account & contact)?

    SOQL query of parent-child record like that:

    Select Id, Account.Name [Select Id From Contact] From Account.

    22. is the finish method mandatory?

    Finish method is mandatory in apex batch class. If you don’t write Finish Method, there will be Compile Error and Class won’t be saved at all.

    23. Write down the syntax of batch class?

    Global (Database.Querylocator | Iterable<Sobject>) Start(Database.Batchablecontext Bc) {
        // Collect The Batches Of Records Or Objects To Be Passed To Execute
    }
    Global Void Execute(Database.Batchablecontext Bc, List<P> Records){
        // Process Each Batch Of Records
    }   
    Global Void Finish(Database.Batchablecontext Bc){
        // Execute Any Post-Processing Operations   
    }

    24. What is the use of database. stateful?

    When using Database.Stateful, only instance member variables retain their values between transactions. Static member variables don’t retain their values and are reset between transactions.

    25. How to call batch class from batch?

    Call another batch class from a batch class

    • Call another batch class in the finish method.
    • Using Queueable Apex

    26. What is the process of execution of each method?

    • start method:
    • execute method
    • finish method

    27. What is the trigger best practices?

    Triggers Best Practices are:

    1. One Trigger Per Object
    2. Logic-less Triggers
    3. Context-Specific Handler Methods
    4. Bulkify your Code
    5. Avoid SOQL Queries or DML statements inside FOR Loops
    6. Avoid Hardcoding IDs

    28. Write down the parent to child & child to parent query?

    We Will Use Object__r.Field For Child To Parent And Select Id [Select Id From Child Object] From Parent Object

    29. How to implement list and map in a single program?

    30. What are the vf pages & triggers?

    Vf Pages -: Developers can use Visualforce to create a Visualforce page definition. A page definition consists of two primary elements:

    • Visualforce markup: Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single <apex:page> tag. The markup defines the user interface components that should be included on the page, and the way they should appear.
    • A Visualforce controller: A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in the associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed on a page and can modify component behaviour.

    Triggers: Apex can be invoked by using triggers. Apex triggers enable you to perform custom actions before or after changes to Salesforce records, such as insertions, updates, or deletions.

    A trigger is Apex code that executes before or after the following types of operations:

    • insert
    • update
    • delete
    • merge
    • upsert
    • undelete

    31. What are the Standard Controller and Custom Controller?

    Custom Controllers: A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller but override one or more actions, such as edit, view, save, or delete. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user.

    Standard Controllers: A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in the associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed on a page, and can modify component behavior.

    32. What are the aura bundles?

    Aura Bundles: A bundle contains an Aura definition, such as an Aura component, and its related resources, such as a JavaScript controller. The definition can be a component, application, event, interface, or token collection.

    Aura Bundles types :

    • .cmp
    • .design
    • .svg
    • .js
    • .css
    • .auradoc
    • .evt
    • .tokens

    33. How to querying large data sets?

    If the query results return more than 1,000 records, then a SOQL query for loop must be used instead, since it can process multiple batches of records through the use of internal calls to query and queryMore.

    34. What are the aura events?

    There are two types of events in the framework:

    • Component events are handled by the component itself or a component that instantiates or contains the component.
    • Application events are handled by all components that are listening to the event. These events are essentially a traditional publish-subscribe model.
  • Visualforce Basics | Salesforce Learning Guide

    Visualforce Basics | Salesforce Learning Guide

    Visualforce is a powerful tool and a stimulating framework allowing developers to explain the interface component and to create sophisticated custom interfaces which will be hosted natively on the lightning platform The Visualforce framework consists of two elements: a tag-based markup and a set of server-side controllers making it easier for developers to perform database operations

    That is, components are defined using the markup language on the page and bind it to the controller (Standard or custom) to perform logical operations on the components.

    The server hosts the visual force, so whenever any Visualforce code is written it will be generated and will be run on the servers.

    Controllers and Extensions

    • Salesforce has provided the basic building functionality to be followed and used with appropriate logic for a Standard controller that works for a standard page as set by Salesforce. 

    Syntax: <apex:page standardController=”Contact”>

    For example, if we are going to use the standard Obj Opportunity, then we need to use a standard controller, clicking on the Save button on that Visualforce page will result in the same behaviour as clicking Save on a standard Opportunity edit page. A Standard list controller: Visualforce pages as the name suggests that can display the records in a list manner or act on a list of records. Examples of already present Salesforce pages that work with sets of records include list pages, related lists, and mass action pages.

    dont miss out iconDon’t forget to check out: Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

    Example code:

    <apex:page standardController="Contact" recordSetVar="contacts">
        <apex:pageBlock title="Contacts List">
            <!-- Contacts List example of Standard List Controller -->
            <apex:pageBlockTable value="{! contacts }" var="ct">
                <apex:column value="{! ct.FirstName }"/>
                <apex:column value="{! ct.LastName }"/>
                <apex:column value="{! ct.Email }"/>
                <apex:column value="{! ct.Account.Name }"/>
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:page>

     

    contact list

    • A Custom controller can be defined as a class written in Apex that provides the functionality of all of the page’s logic and behaviour without leveraging a typical standard controller. Access for the custom controller is embedded in the VF page as <apex:page controller=”ContactsListWithController“>  Custom controller, you’ll define new navigation elements or behaviours, but you want to also reimplement any functionality that was already provided during a standard controller.

    dont miss out iconCheck out another amazing blog by Narendra here: Understanding Accounts & Contacts for Sales Process | Salesforce Guide

    Syntax

    <apex:page controller="ContactsListWithController">
        <apex:form>
            <apex:pageBlock title="Contacts List" id="contacts_list">
    <!--Example of custom controller-->
                <!-- Contacts List goes here -->
            </apex:pageBlock>
        </apex:form>
    </apex:page>
    Custom Controller Apex Class
    public class ContactsListWithController {
        // Controller code goes here
    }

     

  • Introduction to Visualforce Pages | Salesforce Guide

    Introduction to Visualforce Pages | Salesforce Guide

    What is Visualforce Page?

    Visualforce page is a web development language created by Salesforce. The syntax for this language is like HTML. It allows developers to build custom web pages. Not intended for pure custom website creation, only useful for internal work of Salesforce.

    It allows developers to easily create a complete custom page that has the exact look and feel like a standard Salesforce page. A basic level web design or web development skillset is required to create a Visualforce page like HTML skill.

    Why Do We Use Visualforce Pages?

    • To work on complex pages.
    • To display records from multiple objects.
    • When we want more than 2 column displays of data.
    • To edit multiple records at the same time.
    • To create multiple records at the same time.
    • To add custom analytics capabilities.

    dont miss out iconDon’t forget to check out: Salesforce Lightning Component Inside Lightning Web Component Using Visualforce Page

    Types of Controllers in Visualforce Page

    There are basically 3 types of Controllers i.e.

    • Standard Controller: With the help of this controller we can use the standard functions like save, edit, delete etc. We don’t need to code for a standard controller, it is already built-in.
    • Custom Controller: To customize the functionality of the controller, we use custom controllers. We use the apex class to create custom controllers.
    • Extension Controller: It is a combination of standard and custom controllers.

    Issues with Standard Controller

    • We cannot show data from multiple objects.
    • We cannot write our logic in some apex class and call the same when a button is pressed.
    • We cannot fetch data from the database.
    • We cannot do any DML.
    • Relationship data fetching process is not feasible.

    Basic Visualforce page example

    Calculator by using visualforce page:

    Visualforce Page Code:

    <apex:page controller="Numbers">
        <apex:form>
            <apex:pageBlock title="My Content Section">
                Number 1: <apex:inputText value="{!NumberA}"/>
                Number 2: <apex:inputText value="{!NumberB}"/>
                <apex:commandButton value="Sum" Action="{!ShowAdd}"/>
                <apex:commandButton value="Sub" Action="{!ShowSub}"/>
                <apex:commandButton value="Mul" Action="{!ShowMul}"/>
                <apex:commandButton value="Div" Action="{!ShowDiv}"/>
                <apex:outputlabel id="Id1"> {!message} </apex:outputlabel>
            </apex:pageBlock>
        </apex:form>
    </apex:page>

    dont miss out iconCheck out another amazing blog by Romil here: Types of Relationships in Salesforce – All You Need to Know

    Controller Code:

    Public class Numbers{
        Public integer NumberA{get;set;}
        Public integer NumberB{get;set;}
        Public string message{get;set;}    
        Public void ShowAdd(){
            String result = 'The result is ' +(NumberA+NumberB);
            message=result;
        }    
        Public void ShowSub(){
            String result = 'The result is ' +(NumberA-NumberB);
            message=result;
        }    
        Public void ShowMul(){
            String result = 'The result is ' +(NumberA*NumberB);
            message=result;
        }    
        Public void ShowDiv(){
            String result = 'The result is ' +(NumberA/NumberB);
            message=result;
        }
    }

     

  • Callouts from Batch Apex and Calling One Batch Apex to Another Batch | Salesforce Tutorial Guide

    Callouts from Batch Apex and Calling One Batch Apex to Another Batch | Salesforce Tutorial Guide

    What number of callouts would we be able to bring in Batch Apex?

    As far as possible currently is 100 callouts, which implies on the off chance that you have one callout in your execute strategy you can keep the batch size as 100. 

    Suppose we have two callouts then our batch size can be 50 in size. 

    On the off chance that you get Callouts governing cutoff points to mistake how would you redress it?

    An excessive number of SOQL queries: 101 

    Since Apex runs on a multi-tenant stage, the Apex runtime rigorously upholds cutoff points to guarantee code doesn’t corner shared assets

    Avoid the SOQL queries/query that is/are inside of the FOR loops

    Let us know, Batch is Synchronous or Asynchronous operations

    Asynchronous:

    In an Asynchronous call, the thread won’t wait until it finishes its jobs prior to continuing to next. Rather it continues to next leave it’s anything but a different thread. In an Asynchronous call, the code runs in numerous threads which assists with doing numerous tasks as background occupations.

    Example:- Batch, @future Annotation

    dont miss out iconDon’t forget to check out: How To Use Database.Stateful Interface In Batch Apex In Salesforce

    Synchronous:

    In a Synchronous call, the thread will wait until it completes its tasks before proceeding to the next. In a Synchronous call, the code runs in a single thread.

    Example:

    • Trigger
    • Controller Extension
    • Custom Controller

    Here is an example for Callout in Batch Apex

    global class CalloutExample implements Database.Batchable<sObject>,   Database.AllowsCallouts {
        public String query = 'Select ID,FirstName, LastName, Email, Name from Contact;
        global Database.QueryLocator start(Database.BatchableContext BC) {
            return Database.getQueryLocator(query);
        }
        global void execute(Database.BatchableContext BC, List<Account> records) {       
            String endpoint;       
            for ( integer i = 0; i< records.size(); i++ ){
                try {                 
                    HttpRequest req = new HttpRequest();
                    HttpResponse res = new HttpResponse();
                    Http http = new Http();
                    // Set values to Parameters
                    endpoint = 'Your endpoint will be here';
                    req.setHeader('Authorization', header);
                    req.setHeader('Content-Type', 'application/json');
                    req.setEndpoint(endpoint);
                    req.setMethod('POST');
                    req.setBody('Json body you want to send');  
                    req.setCompressed(true);
                    // This is imp according to SF, but please check if the web service accepts the info.  
                    // You have to set it to false.
                    if (!Test.isRunningTest()) {      
                        res = http.send(req);
                        String Response = res.getBody();
                        System.debug('Response:' + res.getBody());
                    }           
                    // Here we do what we want to do with our response            
                }
                catch (Exception e) {       
                    System.debug('Error is :' + e.getMessage() + 'LN:' + e.getLineNumber() );         
                }
            }
        } 
        global void finish(Database.BatchableContext BC){ }
    }

    How can we call another batch apex from batch apex

    Batch Number 1:

    global class OneToAnotherBatch implements Database.Batchable<Sobject>{
        //Here, Method to get the data to be processed 
        global database.Querylocator Start(Database.BatchableContext bc){
            String query = 'Select Id, FirstName, LastName, Name From Account Limit 500';
            return Database.getQueryLocator(query);
        }
        //Here is method to execute the batch
        global void execute(Database.BatchableContext bc, Sobject[] scope){
            for(Sobject s: scope){
                Account acct = (Account)s;
                // To do with your logic
                // Here we do what we want to do with your logic
            }
        }
        //Here is the method to be called after the execution.
        global void finish(Database.BatchableContext bc){
            //Add your start code for the other batch job here
            Database.executeBatch(new BatchTwo());
        }
    }

    Batch Number 2:

    global class BatchTwo implements Database.Batchable<Sobject>{
        //Here, Method to get the data to be processed 
        global database.Querylocator start(Database.BatchableContext bc){
            string query = 'Select Id, FirstName, LastName, Name From Contact Limit 1000';
            return Database.getQueryLocator(query);
        }
        //Here is Method to execute the batch
        global void execute(Database.BatchableContext bc, Sobject[] scope){
            for(Sobject s : scope){
                Contact cont = (Contact)s;
                // To do with your logic
                // Here we do what we want to do with your logic
            }
        }
        //Here is Method to be called after the execute
        global void finish(Database.BatchableContext bc){}
    }

    dont miss out iconCheck out another amazing blog by Ratnesh here: Batch Apex in Salesforce (Basics, Governor Limits, Custom Iterable of Batch)

    Maximum size of the batch and minimum size of the batch

    The Minimum size for Batch Apex in Salesforce is 1.

    The Maximum size for Batch Apex in Salesforce is 2000.

    How can we track the details of the current running Batch using BatchableContext?

    Integer Jobs= [SELECT COUNT() FROM AsyncApexJob WHERE JobType='BatchApex' AND Status IN ('Processing','Preparing','Queued')] ;
    if(Jobs > 6){
        throw new TooManyBatchApexJobsException();
    }
  • Visualforce Pages in Salesforce | The Developer Guide

    Visualforce Pages in Salesforce | The Developer Guide

    Visualforce Page In Salesforce

    Visualforce Page is just like HTML, i.e, It is a tag-based markup language. It allows developers to build sophisticated, user-custom interfaces. It has some user interface components such as a section of a page, a related list, or a field.

    It consists of two primary elements :

    • Visualforce markup
    • Visualforce controller

    Where can we use this Visualforce Page?

    • Override Standard buttons, Tab overview pages
    • Define Custom Tabs
    • Create a dashboard component and other more things we can do with this Visualforce Page.

    Simple Examples of Visualforce Page:

    <apex:page>
    <h1>Welcome Visualforce Page</h1>
    </apex:page>

    dont miss out iconDon’t forget to check out: Get Selected Records from ListView in Visualforce Page | GETRECORDIDS JavaScript | StandardSetController Salesforce

    What is a Controller?

    A Controller is an apex class that is used to implement all the logic of a Visualforce page without holding/supporting the standard functionality.

    In Visualforce, we have two types of controller:

    • Standard Controller
    • Custom Controller

    Standard Controller:

    A standard controller is a class that inherits all the standard properties of objects and the functionality of standard buttons. It also provides common operations such as CRUD (Create/ Read/ Update/ Delete) on any Standard or Custom object. E.g.

    <apex:page standardController=”Account”>
    </apex:page>

    Example of Standard Controller:

    <apex:page standardController="Account">
      <apex:form>
        <apex:pageBlock title="My Content" mode="edit">
          <apex:pageBlockButtons>
            <apex:commandButton action="{!save}" value="Save"/>
          </apex:pageBlockButtons>
          <apex:pageBlockSection title="My Content Section" columns="2">
            <apex:inputField value="{!account.name}"/>
            <apex:inputField value="{!account.site}"/>
            <apex:inputField value="{!account.type}"/>
            <apex:inputField value="{!account.accountNumber}"/>
          </apex:pageBlockSection>
        </apex:pageBlock>
      </apex:form>
    </apex:page>

    Custom Controller:

    A custom controller is an Apex class that applies all the logic for a page without holding a standard controller. E.g,

    <apex:page Controller=”myController”>
    </apex:page>

    Building Standard List Controller

    It is just similar to a standard controller that can display a set of records.

    Example of Standard List Controller:

    <apex:page standardController="Account" recordSetVar="accounts" tabstyle="account" sidebar="false">
      <apex:pageBlock>
        <apex:pageBlockTable value="{!accounts}" var="acc">
          <apex:column value="{!acc.name}"/>
        </apex:pageBlockTable>
      </apex:pageBlock>
    </apex:page>

    dont miss out iconCheck out an amazing Salesforce Video Tutorial here: Creating Multi Screen Wizard Using Apex and Visualforce Salesforce

    Building Custom List Controller

     It is just similar to a standard list controller that displays a set of records.

    <apex:page controller="ContactsListWithController">
        <apex:form>
            <apex:pageBlock title="Contacts List" id="contacts_list">
    <apex:pageBlockTable value="{! contacts }" var="ct">
         <apex:column value="{! ct.FirstName }"/>
         <apex:column value="{! ct.LastName }"/>
         <apex:column value="{! ct.Title }"/>
         <apex:column value="{! ct.Email }"/>
    </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:form>
    </apex:page>
    private String sortOrder = 'LastName';
    public List<Contact> getContacts() {
        List<Contact> results = Database.query(
            'SELECT Id, FirstName, LastName, Title, Email ' +
            'FROM Contact ' +
            'ORDER BY ' + sortOrder + ' ASC ' +
            'LIMIT 10'
        );
        return results;
    }

     

  • Controller Extensions in Salesforce | The Developer Guide

    Controller Extensions in Salesforce | The Developer Guide

    Controller Extension is an Apex Code that extends the functionality of a Standard or Custom Controller.

    When to Use Controller Extensions

    • When we want to use the built-in functionality of a Standard Controller but override one or more actions, like edit, view, save, or delete.
    • When we want to add new actions.
    • When we want to build a Visualforce page that respects user permissions
    • If the Controller Extension extends a Standard Controller it will execute in user mode in which permissions, field-level security, and sharing rules of the current user apply, even though a controller extension class executes in system mode.

    dont miss out iconDon’t forget to check out: Enhance Your Single View of The Customer Using Salesforce Marketing Cloud Connect

    Types of Extensions

    1. Standard controllers: It is used for performing operations on a single record.
    2. Standardsetcontrollers: It is used for performing operations on a group of records.

    Example: Methods of apexpages.standardcontroller

    Apex Class:

    public class allmethods {
        public apexpages.StandardController cont {set;get;}
        public account acc {set;get;}
        public account acc1 {set;get;}
        public allmethods(apexpages.StandardController controller){
            cont=controller;
            string[] ss= new string[]{'name','email__c','industry','rating'};
            acc=(account)cont.getrecord();
        }
        public void savenew(){
            insert acc;
            acc.clear();
        }
    }
    

    Visualforce Page:

    <apex:page standardController="account" extensions="allmethods">
        <apex:form>
            <apex:commandButton value="SAVE" action="{!save}"/>
            <!---- This is applicable only for Edit and detail page---> 
            <apex:commandButton value="cancel" action="{!cancel}"/> 
            <!---- This is applicable only for Edit and detail page---> 
            <apex:commandButton value="delete1" action="{!delete}"/> 
            <!---- This is applicable only for detail page---> 
            <apex:commandButton value="edit1" action="{!edit}"/> 
            <!---- This is applicable only for detail page---> 
            <apex:commandButton value="SAVEnew" action="{!savenew}"/> 
            <!---- This is a custom functionality so it is visible in the page---> 
            <apex:pageblock> 
                <apex:inputField value="{!account.name}"/> 
                <apex:inputField value="{!account.Email__c}"/> 
                <apex:inputField value="{!account.industry}"/> 
                <apex:inputField value="{!account.rating}"/> 
            </apex:pageblock>
        </apex:form>
    </apex:page>

    Example1: Customizing “new” button with a custom Visualforce page in account object without extensions.

    Visualforce Page:

    <apex:page standardController="account">
        <apex:form>
            <apex:pageBlock>
                <apex:commandButton value="save" action="{!save}"/>
                <apex:commandButton value="cancel" action="{!cancel}"/>
                <apex:pageBlockSection columns="2">
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="account name"/>
                        <apex:inputField value="{!account.name}"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="Email"/>
                        <apex:inputField value="{!account.Email__c}"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="industry"/>
                        <apex:inputField value="{!account.industry}"/>
                   </apex:pageBlockSectionItem>
                   <apex:pageBlockSectionItem>
                       <apex:outputLabel value="rating"/>
                       <apex:inputField value="{!account.rating}"/>
                   </apex:pageBlockSectionItem>
               </apex:pageBlockSection>
           </apex:pageBlock>
        </apex:form>
    </apex:page>
    

    The above page is linked to new button using below steps Setup -> Customize -> Accounts -> Buttons, Links, and Actions -> Edit(New) -> Visualforce page -> save

    dont miss out iconCheck out another amazing blog by Kirandeep here: What Are Events In Salesforce Lightning Component

    Example2: Creating functionality of “save&New” Button using Extensions(We cannot retrieve existing save&new functionality).

    Apex Class:

    public class SaveNew {
        public account acc {set;get;}
        public saveNew(apexpages.StandardController controller){
            acc=new account();
        }
        public void savene(){
            insert acc;
            acc=new account();
        }
    }
    

    Visualforce Page:

    <apex:page standardController="account" extensions="SaveNew">
        <apex:form>
            <apex:pageBlock>
                <apex:commandButton value="save" action="{!save}"/>
                <apex:commandButton value="save&New" action="{!saveNe}"/>
                <apex:commandButton value="cancel" action="{!cancel}"/>
                <apex:pageBlockSection columns="2">
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="account name"/>
                        <apex:inputField value="{!acc.name}"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="Email"/>
                        <apex:inputField value="{!acc.Email__c}"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="industry"/>
                        <apex:inputField value="{!acc.industry}"/>
                    </apex:pageBlockSectionItem>
                    <apex:pageBlockSectionItem>
                        <apex:outputLabel value="rating"/>
                        <apex:inputField value="{!acc.rating}"/>
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection> 
            </apex:pageBlock> 
        </apex:form>
    </apex:page>
  • Custom Lookup Field in Visualforce Page | Salesforce Developer Guide

    Custom Lookup Field in Visualforce Page | Salesforce Developer Guide

    We all know about the Standard Lookup functionality, it’s provided by Salesforce. The standard Lookup field gives a dialog box that supports a little quantity of customization. If you want the results ordered and filtered then you have to enable the Enhanced lookup. So if you want to create a VF page with a standard controller, you can easily create a standard lookup field.

    Here we can discuss the Custom Lookup Field is a Visualforce Page:

    If you want to create a VF page with a custom controller then you have to create a custom lookup field. In this scenario, first, you have to create a VF page for lookup.

    Let’s take an example for a better understanding of it.

    In this example, we can create a VF page and on this page, we can use the custom lookup field.

    dont miss out iconDon’t forget to check out: 4 Reasons to use AngularJS in Salesforce Visualforce pages

    Controller: 

    Let’s first create a Controller for the VF page and named as CustomLookupController.apxc

    public with sharing class CustomLookupController {
        public String query {get; set;}
        public List<Account> accounts {get; set;}
        public Boolean doneLookup {get; set;}    
        // constructor
        public LookupController() {
        	doneLookup=false;
        }
        // executes the search
        public PageReference runQuery() {
            List<List<Account>> searchResults=
                [FIND :query IN ALL FIELDS RETURNING 
                    Account (id, name, billingstreet, billingcity, billingpostalcode)];
            accounts=searchResults[0];
            doneLookup=true;
            return null;
        }
    }
    

    Main Visualforce Page:

    Now, create a VF page to show the lookup details. And it’s named as LookupPopup.vfp

    <apex:page controller="CustomLookupController " sidebar="false" showheader="false" standardstylesheets="true">
    <head>
        <title>Custom Lookup</title>
    </head>
      <apex:messages />
      <apex:form id="form" >  
         <div style="width 90%; margin-left:10px">
            <div style='text-align:center; font-size:20px; font-weight:bold'>Lookup</div>
            <p>Please enter the search term below and click the 'Go' button.  This will
               execute a search across all text fields</p>
            <p><span style="color:red">IMPORTANT: </span>Please ensure you enter at least two characters</p>
            <hr/>
            <span><apex:inputText value="{!query}" id="query"/></span> 
            <span><apex:commandButton value="Go" action="{!runQuery}"/></span>        
            <apex:pageBlock mode="mainDetail" rendered="{!doneLookup}">
              <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Close Window" onclick="CloseWindow(); return false;" />
              </apex:pageBlockButtons>
              <apex:pageBlockSection columns="1">
                  <apex:pageBlockTable value="{!accounts}" var="account">
                    <apex:column headerValue="Name">
                      <apex:outputLink value="#" onclick="fillIn('{!account.Name}', '{!account.id}')">{!account.Name}</apex:outputLink>       
                    </apex:column>
                    <apex:column headerValue="Street" value="{!account.BillingStreet}"/>
                    <apex:column headerValue="City" value="{!account.BillingCity}"/>
                    <apex:column headerValue="Postcode" value="{!account.BillingPostalCode}"/>
                  </apex:pageBlockTable>    
              </apex:pageBlockSection>
            </apex:pageBlock>
         </div>
       </apex:form>
       <script language="javascript">
       window.onload = new function() 
       { 
          // bring popup window to front
          window.focus(); 
          var ele=document.getElementById('{!$Component.form.block.section.query}');
          if (ele)
          {
             ele.focus();
          }
       }   
       function fillIn(name, id)
       {
          var winMain=window.opener;
          if (null==winMain)
          {
             winMain=window.parent.opener;
          }
          var ele=winMain.document.getElementById('{!$CurrentPage.parameters.namefield}');
          ele.value=name;
          ele=winMain.document.getElementById('{!$CurrentPage.parameters.idfield}');
          ele.value=id;
          winMain.closeLookupPopup();
       }
       </script>   
    </apex:page>
    

    Lookup Visualforce Page:

    Finally, Create a VF page named Lookup.vfp

    <apex:page standardController="Opportunity">
      <apex:form >
        <apex:pageBlock mode="mainDetail" title="Create Opportunity">
          <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}" />
            <apex:commandButton value="Cancel" action="{!cancel}" />
          </apex:pageBlockButtons>
          <apex:pageBlockSection title="Detail">
            <apex:inputField value="{!Opportunity.Name}" />
            <apex:inputField value="{!Opportunity.CloseDate}"/>
            <apex:inputField value="{!Opportunity.Amount}" />
            <apex:inputField value="{!Opportunity.StageName}" />
            <apex:pageBlockSectionitem >
              <apex:outputLabel value="Account"/>
              <apex:outputPanel layout="inline" style="vertical-align:middle">
      	        <apex:inputHidden value="{!Opportunity.AccountId}" id="targetId" />
                <apex:inputText size="20" id="targetName" onFocus="this.blur()"/>
                <a href="#" onclick="openLookupPopup('{!$Component.targetName}', '{!$Component.targetId}'); return false"><apex:image style="vertical-align:middle;width:21px; height:21px" value="/img/icon/telescope16.png" /></a>
              </apex:outputPanel>
            </apex:pageBlockSectionitem>
          </apex:pageBlockSection>
        </apex:pageBlock>
      </apex:form>
      <script>
        var newWin=null;
        function openLookupPopup(name, id)
        {
            var url="/apex/LookupPopup?namefield=" + name + "&idfield=" + id;
            newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
            if (window.focus) 
            {
                newWin.focus();
            }            
            return false;
        }                  
        function closeLookupPopup()
        {
           if (null!=newWin)
           {
              newWin.close();
           }  
        }
      </script>
    </apex:page>
    

    dont miss out iconCheck out another amazing blog by Shweta here: How Does a Post Install Script Work? – Salesforce Developer Guide

    Output:

    When you can Click on the telescope button to the right of the accounts field it opens the popup window. And this lookup window contains the account id of the selected account. 

  • Displaying data from the related Supplier__c records on a Visualforce page that has a custom controller for the Buyer__c object

    Displaying data from the related Supplier__c records on a Visualforce page that has a custom controller for the Buyer__c object

    How can a developer display data from the related Supplier__c records on a Visualforce page that has a custom controller for the Buyer__c object?

    The Problem

    An org has a data model with a Buyer__c object that has a lookup relationship to Region__c and a Supplier__c object has a lookup relationship to Region___c.
    How can a developer display data from the related Supplier__c records on a Visualforce page that has a custom controller for the Buyer__c object?

    I have first recreated a similar data model in my Dev Org

    I have also created a VF page with a custom controller for Buyer__c and a custom extension for querying related data from Supplier__c.

    dont miss out iconDon’t forget to check out: Access sObject’s (Salesforce Object Type) Fields and Its Record | Apex Developer Guide

    BuyerPage.vfp – 

    <apex:page controller="BuyersSamplePageController" extensions="BuyersSamplePageControllerExt" sidebar="false">
    <style type="text/css">
    .outBorder {
        border:3px outset black;
    }
    .inBorder{
        border-top:2px dotted blue;
        border-left:2px dotted blue;
    }
        .inlineTable {
        display: inline-flex !important;
    }
    </style>
    
    <apex:pageBlock title="List of Buyer & Suppliers" >
        <div class="inlineTable">
            <apex:dataTable value="{!buyersList}" var="b" styleclass="outBorder" width="550px" >
                <apex:column styleclass="inBorder">
                    <apex:facet name="header">Buyer ID </apex:facet>
                    <apex:outputText >{!b.Id}</apex:outputText>
                </apex:column>
                <apex:column styleclass="inBorder">
                    <apex:facet name="header">Buyer Name </apex:facet>
                    <apex:outputText >{!b.Name}</apex:outputText>
                </apex:column>
            </apex:dataTable>
    
            <!-- nesting suppliers table (not recommended) -->
            <apex:dataTable value="{!supplierList}" var="s" styleclass="outBorder" width="550px">
                <apex:column styleclass="inBorder">
                    <apex:facet name="header">Supplier ID </apex:facet>
                    <apex:outputText >{!s.Id}</apex:outputText>
                </apex:column>
                <apex:column styleclass="inBorder">
                    <apex:facet name="header">Supplier Name </apex:facet>
                    <apex:outputText >{!s.Name}</apex:outputText>
                </apex:column>
            </apex:dataTable>
        </div>
    </apex:pageBlock>
    </apex:page>

    BuyersSamplePageController – 

    public class BuyersSamplePageController {
        public List<Buyer__c> buyersList{get;set;}
        public BuyersSamplePageController(){
            buyersList = new List<Buyer__c>();
            buyersList = [select id,name from Buyer__c];
        }
    }

    BuyersSamplePageControllerExt – 

    public class BuyersSamplePageControllerExt {
        public List<Supplier__c> supplierList{get; set;}
        public BuyersSamplePageControllerExt(BuyersSamplePageController custCtrl){
            supplierList = new List<Supplier__c>();
            supplierList = [SELECT id, name FROM Supplier__c] ;
        }
    }

    Buyers/Suppliers list – 

    dont miss out iconCheck out an amazing tutorial video here: What is Apex? | Way to become a Salesforce Developer | Salesforce Development Tutorials

    As you can see here, now I have been able to retrieve data from the Supplier on the VF page using extensions!

    Side note: I have nested the 2 tables for buyers & suppliers, for illustration purposes only. If you want to combine two different objects in a single table and display it on a VF page then use a Wrapper class.