Developer Fundamentals Flashcards

1
Q

How can a developer check if the current user is able to delete the current object?

Choose 1 answer.

A. Use the is Deletable() method of the DescribeSObjectResult Class

B. Use the Deletable() method of the SObjectResult Class

C. Use the canDelete() method of the SObjectResult Class

X D. Use the canDelete() method of the DescribeSObjectResult Class

A

✔️ A. Use the is Deletable() method of the DescribeSObjectResult Class

The isDeletable() method of the DescribeSObjectResult class returns true if the object can be deleted by the current user, and false if otherwise. The class contains several other methods that can be used to determine other types of permissions of the current user such as isAccessible(), isCreateable, isSearchable(), and more.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Which of the following events are fired when an Aura component loads on a page?
Choose 3 answers.

A. init

B. render

C. load

D. after Render

E. start

A

✔️A. init

✔️ B. render

✔️ D. after Render

The ‘init’ event signals that a component initialization is complete. The ‘render’ event triggers the start of component rendering. The ‘after Render’ event signals that the rendering is complete. At this point, one can interact with the DOM tree to do additional processing.

The ‘load’ and ‘start’ options are not alid terms used to describe events in the rendering lifecycle of an Aura component.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

A company has a business requirement that cannot be met using the declarative tools available in its Salesforce org. As a result, the Salesforce Administrator of the company has resorted to installing a suitable package available in the AppExchange marketplace. What are the benefits of using AppExchange?

Choose 2 answers.

A. AppExchange can scan an org for any security vulnerabilities.

B. AppExchange apps may include support and maintenance.

C. AppExchange offers reviewed and proven solutions for customers.

D. AppExchange installs additional development tools in the org.

A

✔️B. AppExchange apps may include support and maintenance.

✔️C. AppExchange offers reviewed and proven solutions for customers.

Salesforce AppExchange is a marketplace for downloading solutions such as apps and components for the Salesforce platform. It has both free and paid solutions, which may include support and maintenance.

The AppExchange platform is used for installing an already built solution instead of additional development tools for building the solution. It is not used for scanning security vulnerabilities.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up summaries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Cosmic Lux is a company that uses Salesforce as the primary system to manage accounts. An ERP system is currently used to manage contact records of customers in Europe. The sales director of the company would like to store only the accounts associated with these contacts in Salesforce. To make the related contacts visible in Salesforce, Salesforce Connect should be used. The contacts in the ERP system have not been configured to store the Salesforce ID of the parent account record. A developer has been asked to show all the related contacts from the external system on the account detail page in Salesforce. Once Salesforce Connect has been configured, which relationship field should the developer define on the external object for this requirement?

Choose 1 answer.

A. Indirect Lookup

B. Internal Lookup

C. External Lookup

D. Lookup

A

✔️A. Indirect Lookup

An indirect lookup relationship field can be used to link a child external object to a parent standard or custom object in Salesforce, such as the Account object. A custom unique, external ID field on the parent Account object can be selected to match against the child’s indirect lookup relationship field, whose values are determined by the specified External Column Name. Since the external system does not contain unique record identifiers for the account records from Salesforce, a custom External ID field needs to be used. That is why using an indirect lookup relationship is the only way of meeting this requirement.

A lookup relationship can only be used for this use case if the external object includes a column that identifies related Salesforce records by their 18-character IDs. An external lookup relationship links a child standard, custom, or external object to a parent external object. In this case, it is necessary to link a child external object to a parent standard object, so an external lookup relationship cannot be used. There is no relationship field called ‘Internal Lookup.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

Se puede utilizar un campo de relación de búsqueda indirecta para vincular un objeto externo secundario a un objeto estándar o personalizado principal en Salesforce, como el objeto Cuenta. Se puede seleccionar un campo de ID externo personalizado y único en el objeto Cuenta principal para que coincida con el campo de relación de búsqueda indirecta del secundario, cuyos valores están determinados por el Nombre de columna externa especificado. Dado que el sistema externo no contiene identificadores de registro únicos para los registros de cuenta de Salesforce, se debe utilizar un campo de ID externo personalizado. Por eso, utilizar una relación de búsqueda indirecta es la única forma de cumplir con este requisito.

Una relación de búsqueda solo se puede utilizar para este caso de uso si el objeto externo incluye una columna que identifica registros de Salesforce relacionados por sus ID de 18 caracteres. Una relación de búsqueda externa vincula un objeto externo, personalizado o estándar secundario a un objeto externo principal. En este caso, es necesario vincular un objeto externo secundario a un objeto estándar principal, por lo que no se puede utilizar una relación de búsqueda externa. No existe ningún campo de relación denominado “Búsqueda interna”.

Objetivo: Fundamentos del desarrollador

Objetivo detallado: Dado un escenario, determinar, crear y acceder al modelo de datos apropiado, incluidos objetos, campos, relaciones e identificaciones externas.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Cosmic Transport would like to use the Lightning Component Framework for adding functionality that allows the company’s users to manage its transportation services. A developer has been asked to work on a few custom Lightning web components that will be added to Lightning pages and tabs. Which of the following is an important consideration for this use case?

Choose 1 answer.

A. The Lightning Component Framework allows only Aura components to be added to Lightning tabs.

B. My Domain needs to be deployed in order to add the components to Lightning pages and tabs.

C. Each Lightning web compoñent bundle must contain at least a controller and a CSS file.

D. Each Lightning web component must be wrapped in an Aura component before it can be added.

A

Choose 1 answer.

✔️B. My Domain needs to be deployed in order to add the components to Lightning pages and tabs.

The Lightning Component Framework allows both Aura components and Lightning web components to be added to Lightning pages and tabs. However, My Domain needs to be deployed first before the components can be added to Lightning tabs, Lightning pages, as standalone apps, as actions and action overrides, as custom Lightning page templates, or elsewhere in the org.

Each Lightning web component that renders Ul consists of an HTML file, a JavaScript file (controller), and a metadata configuration file. A Lightning web component does not need to be contained in an Aura component for it to be added to a page or as a tab.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

A construction company in the housing development business uses the Contact object to track different types of contacts they deal with on a daily basis. The company’s Salesforce developer is building a feature for its partner contacts and has written the code below to determine information about a specific record type. Which line of code should be added to line 5?

  1. RecordType recType [SELECT Id, Name FROM RecordType
  2. WHERE Sobject Types “Contact” AND DeveloperName=”PartnerContact’
  3. LIMIT 1];
  4. Schema. DescribeSObjectResult result Schema.SObjectType.Contact;
    5.
  5. Schema, RecordTypeInfo recordTypeInfo mapRecTypes.get(recType.id);

Choose 1 answer.

A. Map Id, Schema.RecordTypeInfo> mapRecTypes result.getRecordTypeInfos();

B.Map<Id, Schema. RecordTypeInfo> mapRecTypes result.getRecordTypeInfosById();

C. MapeId, Schema. RecordTypeInfo> mapRecTypes result.getRecordTypes();

A

B.Map<Id, Schema. RecordTypeInfo> mapRecTypes result.getRecordTypeInfosById();

To return a map of the record ids and details of their associated record types, the getRecordTypeInfosById() method of the Schema DescribeSObjectResult class can be used. The data type used to store the results of this method is a map collection in which the key is an id and the value is the Schema. Record TypeInfo class.

A The ‘getRecord TypeInfos’ method returns a list of the record types, but since line 6 contains code that uses the get() method, a method that returns a map should be used. There are no methods called getRecord Types’ and ‘getRecordTypelds

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

RecordType rectType = [SELECT Id, Name, DeveloperName FROM RecordType WHERE SobjectType = 'Contact' Limit 1];
    Schema.DescribeSObjectResult result = Schema.SObjectType.Contact;
    Map<Id, Schema.RecordTypeInfo> mapRecTypes = result.getRecordTypeInfosById();
    Schema.RecordTypeInfo recordTypeInfo = mapRecTypes.get(rectType.Id);
    System.debug('RecordTypeInfo Name: ' + recordTypeInfo.getName());
    System.debug('RecordTypeInfo DeveloperName: ' + recordTypeInfo.getDeveloperName());
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How can a developer check if a user has read access to a field and if the field can be displayed on a Visualforce page?

Choose 1 answer.

A Call the is Accessible() method of Schema. DescribeFieldResult to verify field level read permission

B. Call the IsAccessible() method of Schema. DescribeSObjectResult to verify field level read permission

C. Call the is Readable() method of Schema SObjectResult to verify field level read permission

D. Call the isViewable() method of Schema. DescribeField Result to verify field level read permission

A

✔️A Call the is Accessible() method of Schema. DescribeFieldResult to verify field level read permission

The is Accessible() method of Schema. Describe FieldResult class can be used to determine if the current user has read access to a specific field.

The isAccessible() method on the Schema.DescribeSObjectResult class is used to determine if the current user has access to a specific object. The isViewable() and is Readable() methods do not exist

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

A developer has declared and initialized a variable named ‘s’ of type String[] to store multiple sObject types. He uses the code below to get describe metadata information for the sObject types.

Schema. DescribeSobjectResult[] r = Schema.describeSObjects(s):

Which method of the DescribeSObjectResult class can be used to determine whether an sObject appears as ‘Account’ in the user interface?

A. getName()

B. isLabel()

C. isName()

D. getLabel()

A

✔️D. getLabel()

The getLabel() method of the DescribeSObjectResult class returns the object’s label, which may or may not match the object name.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

To determine whether an sObject appears as ‘Account’ in the user interface, you can use the getLabel() method of the DescribeSObjectResult class. This method returns the display name of the sObject as it appears in the user interface.

Here is how you can use it:

apex
Copiar código
Schema.DescribeSObjectResult[] r = Schema.describeSObjects(s);
for (Schema.DescribeSObjectResult dr : r) {
if (dr.getLabel() == ‘Account’) {
// This sObject appears as ‘Account’ in the UI
}
}
In this example, the getLabel() method checks if the sObject’s label matches “Account”. If it does, it means that this sObject appears as “Account” in the user interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is true regarding the Salesforce multitenant environment?

Choose 2 answers.

A. All customizations are specified as metadata, allowing for easy upgrades

B. All customers share the same code base, but have their own database

C. Metadata includes configuration but not code

D. Automatic upgrades are applied during the year according to the Salesforce release schedule to all customers

A

Choose 2 answers.

✔️A. All customizations are specified as metadata, allowing for easy upgrades

✔️D. Automatic upgrades are applied during the year according to the Salesforce release schedule to all customers

All standard and custom configurations, functionality, and code in an org are metadata. These customizations are separated in a special metadata layer, so upgrades can easily be performed. These uprcades are released automatically three times a year for all customers.

In Salesforce’s multitenant environment, users share the same code base and database. Hence, governor limits are strictly imposed.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can a developer check the maximum number of digits for an integer field?

Choose 1 answer.

A. Use the getLength() method of the DescribeField Result Class

B. Use the getSize() method of the DescribeField Result Class

C Use the getDigits() method of the DescribeFieldResult Class

D. Use the getScale() method of the DescribeField Result Class

A

✔️C Use the getDigits() method of the DescribeFieldResult Class

The getDigits() method returns the maximum number of digits specified for the field. This method is only valid with Integer fields.

The getScale() method returns the number of digits to the right of the decimal point on Double fields.

The getSize() method does not exist in the DescribeField Result class.

The getLength() method returns the maximum size of the field in Unicode characters.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Cosmic Solutions has a custom object called Weekly Employee Summary, which stores a summary of employee data that is tracked in Salesforce, such as hours worked and wage totals. An autolaunched flow has been built to calculate this information and create a new Weekly Employee Summary record for each employee every time it is run. Currently, a Salesforce Administrator needs to run this flow manually once a week. They would like this type of operation to be run automatically in the future. Which solutions would meet this requirement?

Choose 2 answers

A. Invoke the flow from a schedule-triggered flow.

B. Invoke the flow from an Apex job that runs weekly.

C. Configure the flow on the ‘Scheduled Jobs’ page in Setup.

D. Use an existing Process Builder process to run the flow weekly.

A

✔️A. Invoke the flow from a schedule-triggered flow.

✔️B. Invoke the flow from an Apex job that runs weekly.

A declarative solution is to invoke the autolaunched flow from a schedule-triggered flow using the Subflow element in Flow Builder. Schedule-triggered flows can be configured to start on a specified date and time, with several frequency options. The scheduling configuration is available on the flow’s Start element. The Subflow element is added that references the autolaunched flow to invoke.

A programmatic solution is to invoke the flow from an Apex class that implements the Schedulable interface, which enables the Apex class to run on a scheduled basis. To invoke a flow from Apex, the Flow.Interview class is used.

Process Builder cannot be used to invoke autolaunched flows in scheduled intervals or timings. An auto-launched flow cannot be configured on the ‘Scheduled Jobs’ page in Setup.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Cosmic Solutionsm uses a third party platform for managing their employees’ compensation plans. It needs to be integrated with its Salesforce org. For example, when the third party platform sends a request for a particular resource to the org, the org should respond to the request by serxding data in JSON format. In addition, when certain records are changed.in the ong, the third party platform should be automatically notified of the change. Which of the following should be used to meet the requirement?

Choose 2 Answers

A. Bulk API

B. Streaming API

C. SOAP API

D. REST API

A

B. Streaming API

D. REST API

Both REST API and SOAP API can be used to integrate a Salesforce org with an external system. However, while REST API supports both XML, and 150 data formats, SOAP API only supports XML Streaming API which uses the publish subscribe model, is used for setting up notifications that can be triggered when record changes are made in the Salesforce org. For example the external system can subscribe to a platform event in the org and receive a notification when a specific data change occurs hulk Aptuned for loading or deleting large sets of data in the org.

Olajective: Developer Fundamentals
Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

A developer is required to ensure that a reason is entered if an opportunity stage is updated to ‘Closed Lost. What is the best way to meet this requirement?

Choose 1 answer.

A. Required field

B. Apex trigger

C. Validation rule

D. Formula field

A

C. Validation rule

A validation rule can be used to check both the stage and reason fields of an opportunity during the update. If the stage is set to ‘Closed Lost’ and the reason field is empty, then the validation rule can display the wror message.

The requirement can be met using a declarative tool, so there is no need to use an Apex trigger. A formula field is used for displaying values, for example, based on data from the current record or related records. Setting the field to ‘Required’ will require that field to be always populated regardless of the opportunity stage.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields. and roll-up summaries.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Phone Factory uses a custom object named Phone Inventory which has a Geolocation field named Storage Location. A developer is writing a trigger that needs to update Storage Location when certain conditions are met. What is the proper syntax for accessing and modifying this field in Apex?

Choose 1 answer.

A. Phone_Inventory_c.Storage_Location_c.latitude_s AND/OR Phone_Inventory_c.Storage_Location_c.longitude_s

B. Phone_Inventory_c.Storage_Location_c.latitude AND/OR Phone_Inventory_c.Storage_Location_c.longitude

C. Phone_Inventory_c.Storage_Location_latitude_s AND/OR Phone_Inventory_c.Storage_Location_longitude_s

D. Phone_Inventory_c.Storage_Location_c

A

✔️ C. Phone_Inventory_c.Storage_Location_latitude_s AND/OR Phone_Inventory_c.Storage_Location_longitude_s

Geolocation is a compound data type and can’t be directly accessed. To modify a Geolocation field’s data, remove the ‘_c’ from the field name and append ‘_latitude_s’ or ‘_longitude_s’ to access the relevant components.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Which of the following correctly describes how the Salesforce platform features map to the MVC software design pattern?

Choose 1 answer.

A. Model: JavaScript; View: Visualforce Pages; Controller: Custom Apex Class

B. Model: Standard and Custom Objects; View: JavaScript, Controller: Standard and Custom Controllers

C. Model: Apex Classes; View: Pages and Components; Controller: Standard and Custom Objects

D. Model: Standard and Custom Objects; View: Pages and Components; Controller: Standard and Custom Controllers

A

D. Model: Standard and Custom Objects; View: Pages and Components; Controller: Standard and Custom Controllers

The ‘Model’ component in the MVC pattern represents data structure, which is defined using standard and custom objects in Salesforce. The ‘View’ component comprises pages and components, such as Visualforce pages and Lightning components.

The ‘Controller’ includes any custom controller logic written in Apex and standard controllers containing standard behavior for each object implemented by the Salesforce platform.

The ‘Controller’ may also represent JavaScript code in the form of a client-side controller.

Objective: Developer Fundamentals

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is true regarding accessing sharing programmatically?

Choose 3 answers.

A. Objects on the detail side of a master-detail relationship do not have a sharing object

B. Programmatic sharing can only give record access to one individual user at a time

C. CustomObject_Share is the sharing object for a custom object

D. Account__Share is the sharing object for the Account object

E. AccountShare is the sharing object for the Account object

A

✔️A. Objects on the detail side of a master-detail relationship do not have a sharing object.

✔️C. CustomObject__Share is the sharing object for a custom object

✔️E. AccountShare is the sharing object for the Account object

To access sharing programmatically, the sharing object associated with the standard or custom object should be used.

To determine the name of the share object associated with a standard object, the suffix “Share” is added to its name. For example, the share objects for the Account, Case, and Contact objects are AccountShare, CaseShare, and ContactShare respectively. As for custom objects, the “__Share” suffix is used instead. For example, the sharing object for MyCustomObject (or MyCustomObject__c) is MyCustomObject__Share.

Objects on the detail side of a master-detail relationship do not have an associated sharing object, and access to the detail records is determined by the master object sharing object and the sharing setting of the relationship.

Record access can be granted to users or groups with programmatic sharing.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

A developer would like to return the developer name of a particular record type using a method of the ‘RecordTypeInfo’ class. Which method is available for this use case?

Choose 1 answer.

A. getDeveloper Name()

B. getRecordTypeInfos By Developer Name()

C. getName()

D. getRecord TypeInfosByName()

A

✔️ A. getDeveloper Name()

The getDeveloperName() method of the Record TypeInfo class can be used to return the developer name of a particular record type. The getName() method returns the Ul label of a record type. Both getRecordTypeInfos By DeveloperName() and getRecord TypeInfosByName() are methods of the DescribeSObjectResult class. The former is used to return a map that matches developer osByD names to their associated record type. The latter is used to return a map that matches record labels to their associated record type.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

There is a requirement to rate all accounts daily based on the values of the opportunities closed in the current year, the number of open opportunities, and the opportunity close rates. The account with the highest aggregated result should be rated number 1, and so on until the account with the lowest rating is updated. How could this requirement be achieved?

Choose 1 answer.

A. Use an Apex trigger on the Account object and schedule it to run each night.

B. Use a Batch Apex job and schedule it to run each night.

C. Use a platform event-triggered flow to run scheduled nightly updates.

D. Use Process Builder and schedule an action to run each night to sort and rate accounts.

A

✔️B. Use a Batch Apex job and schedule it to run each night.

Processes or triggers cannot be configured to run periodically at fixed timings or intervals. A scheduled Apex job would be suitable for this requirement since it can be scheduled to run at regular intervals and is very capable of performing the required logic. Platform event-triggered flows cannot be scheduled. A scheduled flow may also be used in the above scenario, but if the logic is too complex, Apex should be used. Furthermore, batch Apex has much higher governor limits compared to scheduled flows.

A batch Apex job can be used to process all the account records daily. An Apex class that implements the ‘Database.Batchable’ interface can be created for the batch Apex job. Another Apex class

that implements the ‘Schedulable’ interface can be created to execute the batch Apex job at regular intervals.

The ‘Schedule Apex’ page in the Salesforce user interface or the ‘System.schedule’ method can be used to specify the schedule. The Apex class defined for the batch Apex job must use the following syntax:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

A sales user needs to track customer preferences and product interests. Which of the following options falls under the Model layer of Salesforce’s MVC architecture?

Choose 1 answer.

A. Creating a custom field

B. Creating a Visualforce page

C. Defining a page layout

D. Defining an Apex controller

A

✔️A. Creating a custom field

In Salesforce, a data model is built by creating custom fields, custom objects, etc. The data model falls under the ‘Model’ layer of the MVC architecture. The other options fall under the “View’ and ‘Controller layers.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

A developer would like to create a new sObject with default values using the describe information of a similar sObject. Which of the following can be used to obtain information about the type of sObject from an sObject describe result?

Choose 1 answer.

A. getType()

B.getSObjectName()

C. getSObject()

D. getSObjectType()

A

✔️D. getSObjectType()

The getSObject Type() method of the DescribeSObjectResult class returns the SObject Type object for the sObject, which can be used to create a similar sObject using the newSObject() method. Note the DescribeFieldResult class also has a getSObject Type() method which can be used to immediately determine the SObject Type related to the describe field result

The getSObject(), getSObjectName(), and getType() methods do not exist.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

El método getSObjectType() de la clase DescribeSObjectResult en Salesforce es utilizado para obtener el tipo de objeto SObject al que se refiere un DescribeSObjectResult. Esto puede ser útil cuando estás trabajando con descripciones dinámicas de objetos en Apex y necesitas manipular instancias de un objeto basado en su tipo dinámico.

Sintaxis:

public SObjectType getSObjectType()

¿Qué devuelve?
Este método devuelve un valor de tipo SObjectType, que representa el tipo del objeto de Salesforce al que se refiere el DescribeSObjectResult.

Ejemplos prácticos de uso:
1. Obtener el tipo de un objeto SObject dinámicamente:
Este ejemplo muestra cómo puedes usar getSObjectType() para obtener el tipo de un objeto en tiempo de ejecución.

// Describir el objeto Account
Schema.DescribeSObjectResult accountDescribe = Account.sObjectType.getDescribe();

// Obtener el tipo del SObject
SObjectType sObjectType = accountDescribe.getSObjectType();

// Imprimir el nombre del tipo de SObject
System.debug('El tipo de objeto es: ' + sObjectType);

En este caso, obtendrás una salida que indica que el tipo de objeto es Account.

  1. Uso en conjunto con otros objetos SObject:
    Puedes usar getSObjectType() para crear nuevas instancias de SObjects dinámicamente, sin conocer su tipo de antemano.
// Describir el objeto Contact
Schema.DescribeSObjectResult contactDescribe = Contact.sObjectType.getDescribe();

// Obtener el tipo de objeto SObject dinámicamente
SObjectType sObjectType = contactDescribe.getSObjectType();

// Crear una nueva instancia de este SObject
SObject newContact = sObjectType.newSObject();
newContact.put('FirstName', 'John');
newContact.put('LastName', 'Doe');

// Insertar el contacto
insert newContact;

En este ejemplo, usamos getSObjectType() para obtener el tipo del objeto Contact y luego creamos una nueva instancia de un contacto dinámicamente, sin hacer referencia directa a la clase Contact.

  1. Comparar el tipo de objeto con otro SObjectType:
    Es posible comparar el tipo de objeto con otro SObjectType para verificar si un SObject pertenece a un tipo específico.
// Describir el objeto Lead
Schema.DescribeSObjectResult leadDescribe = Lead.sObjectType.getDescribe();
SObjectType leadType = leadDescribe.getSObjectType();

// Comprobar si el objeto es de tipo Lead
if (leadType == Lead.sObjectType) {
    System.debug('Este es un objeto de tipo Lead');
} else {
    System.debug('No es un objeto de tipo Lead');
}
  1. Obtener el tipo de objeto en función de una cadena (String):
    Puedes usar getSObjectType() en combinación con un nombre de objeto en formato String para trabajar dinámicamente con diferentes tipos de objetos.
// Obtener el nombre de un objeto en formato String
String objectName = 'Opportunity';

// Obtener el tipo de objeto basado en el nombre
SObjectType sObjectType = Schema.getGlobalDescribe().get(objectName).getSObjectType();

// Crear una nueva instancia del objeto
SObject newOpportunity = sObjectType.newSObject();
newOpportunity.put('Name', 'New Business Deal');

// Insertar la nueva oportunidad
insert newOpportunity;

Casos prácticos:
Automatización y reutilización del código: En escenarios donde el tipo de objeto es dinámico, como en integraciones externas, el uso de getSObjectType() te permite trabajar con múltiples tipos de objetos sin codificar sus nombres de manera rígida.
Creación dinámica de objetos: Si necesitas crear registros de diferentes tipos de objetos basándote en algún tipo de lógica condicional, puedes usar getSObjectType() para obtener y trabajar con esos tipos dinámicamente.
Resumen:
El método getSObjectType() te permite acceder al tipo del objeto SObject en forma dinámica.
Es útil para crear objetos de forma dinámica y manipular tipos de objetos sin tener que referenciar explícitamente sus nombres.
Permite construir aplicaciones más flexibles y reutilizables que pueden trabajar con diferentes tipos de objetos de Salesforce.
Este método es esencial cuando trabajas con código genérico y dinámico, lo que facilita el manejo de varios tipos de objetos SObject en Apex.

21
Q

How can a developer get all picklist values of a specific field via Apex?

Choose 1 answer.

A. Use the global Picklist method

B. Use the describePicklist method

C. Use the getPicklist Values method

D. Use the field Picklist method

A

C. Use the getPicklist Values method

The getDescribe() method is used to obtain information on the field iad then the getPicklist Values method is used to retrieve the picklist values.

Salesforce Reference Link

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

Schema.DescribeFieldResult fieldResult = Contact.Salutation.getDescribe();

List<Schema.PicklistEntry> picklistValues = fieldResult.getPicklistValues();

for (Schema.PicklistEntry picklistValue : picklistValues) {
    System.debug('Picklist Label: '+ picklistValue.getLabel());
    System.debug('Picklist Value: '+ picklistValue.getValue());
}
22
Q

Which of the following options represent the controller layer in the MVC architecture of a Salesforce application?

Choose 2 answers.

A. Apex Controller

B. List View

C. Lightning App page

D. Visualforce Controller

A

✔️A. Apex Controller
✔️D. Visualforce Controller

The controller layer in the Model-View-Controller architecture includes business logic that can be declarative (such as validation rules and escalation rules) or programmatic (such as Visualforce controllers or Apex controllers). The controller is responsible for responding to user input received from the view layer (Lightning App page, Visualforce page, list view, etc.) and interacting with the necessary data model object. For example, the controller validates input received from the view layer and then performs a save operation that modifies the state of the data model in the

database.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

23
Q

How can a developer check if the current user is able to view a particular field?

Choose 1 antwer

A. Use the isAccessible() method of the DescribeFieldResult Class

B. Use the is Accessible() method of the DescribeField Class

C. Use the isViewable() method of the DescribeField Result Class

D. Use the isViewable method of the DescribeField Class

A

A. Use the isAccessible() method of the DescribeFieldResult Class

The isAccessible() method of the DescribeFieldResult class returns true if the current user can see the field

DescribeField is an invalid class name, and is Viewable() is not a method of the DescribeFieldResult class.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

El método isAccessible() de la clase DescribeFieldResult en Salesforce devuelve un valor booleano que indica si un campo es accesible para el usuario actual. Este método es útil para verificar si el campo es visible o si el usuario tiene permiso para acceder a él.

Ejemplo:

// Obtener los metadatos de un campo específico
SObjectField field = Account.Name;

// Usar el método describe para obtener los detalles del campo
DescribeFieldResult fieldResult = field.getDescribe();

// Verificar si el campo es accesible para el usuario actual
Boolean isFieldAccessible = fieldResult.isAccessible();

// Imprimir el resultado
System.debug(‘El campo es accesible: ‘ + isFieldAccessible);
Ejemplo práctico en un controlador de Apex:
Imagina que tienes un formulario que los usuarios rellenan en una Visualforce Page, y quieres asegurarte de que solo muestres los campos que son accesibles para el usuario actual.

public class AccountController {
    
    public List<String> getAccessibleFields() {
        List<String> accessibleFields = new List<String>();
        
        // Obtener la lista de todos los campos de la cuenta
        Map<String, SObjectField> fieldMap = Schema.SObjectType.Account.fields.getMap();
        
        // Iterar sobre los campos y comprobar su accesibilidad
        for (String fieldName : fieldMap.keySet()) {
            DescribeFieldResult fieldResult = fieldMap.get(fieldName).getDescribe();
            if (fieldResult.isAccessible()) {
                accessibleFields.add(fieldName);
            }
        }
        
        return accessibleFields;
    }
}

En este ejemplo, el método getAccessibleFields devuelve una lista de todos los campos accesibles para el objeto Account, lo que permite que una página Visualforce o Lightning Component muestre solo los campos a los que el usuario tiene acceso.

Uso típico:
Personalización de UI: Asegurarse de que solo se muestren los campos a los que el usuario tiene permiso.
Validación de seguridad: Evitar acceso o manipulación de campos sensibles por usuarios sin privilegios adecuados.
Generación dinámica de formularios: Crear formularios dinámicos basados en permisos de campo.

24
Q

Which of the following are valid considerations that a new developer should be aware of when developing in a multi-tenant environment?

Choose 2 answers.

A. Restrictions are enforced on code that can be deployed into a production environment

B. Governor limits ensure that the amount of CPU time is monitored and limited per customer over a defined time period to ensure that performance in one org is not impacted by another

C. The number of API calls allowed is unlimited

D. Many customers share the same instance, so queries need to ensure the correct organization id is referenced to return the correct organizational data

A

A. Restrictions are enforced on code that can be deployed into a production environment

B. Governor limits ensure that the amount of CPU time is monitored and limited per customer over a defined time period to ensure that performance in one org is not impacted by another

Although many customers share the same instance, it is not possible for one customer query to return data from another customer. Each row in the table that stores application data includes identifying fields, such as the organization that owns the row (OrgID).

The total API requests (calls) per 24-hour period is limited for an org. Governor limits monitor and limit various factors such as CPU time and DML statements to ensure that one org does not impact another. Code cannot be deployed into production unless test code coverage is achieved.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

25
Q

A service manager wants to send an email reminder to customers who have failed their energy audit to schedule another audit after they have completed the required modification manager wants the reminders to be sent weekly for all the records that still have a failed audit status. How can a Salesforce administrator easily fulfill this requirement?

Choose 1 answer.

A. Create a validation rule to verify failed audit status of records and use an email action to send the email reminders.

B. Create an auto-response rule to send an email reminder for the set of records with a failed audit status.

C. Create a scheduled flow for the set of records with a failed audit status to send an email.

D. Create a batch Apex job for the records that failed the energy audit and use scheduled Apex to schedule the emails.

A

✔️C. Create a scheduled flow for the set of records with a failed audit status to send an email.

Using a scheduled flow, a set of records can be selected based on specified criteria and have the operation run weekly. A ‘send email’ action can be added to the flow to send email reminders to customers who have failed their energy audits.

A solution can also be implemented using Batch Apex to handle the processing and email sending, and Scheduled Apex to run the jobs regularly. However, this approach is not necessary since a declarative option is available, which doesn’t require coding skills and can easily be implemented and maintained by a Salesforce administrator. An auto-response rule is not suitable for this requirement as it is used for providing immediate acknowledgment to case or lead submissions, notifying users that their inquiries have been received. Validation rules are used to validate field values when a record is saved.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up summaries.

26
Q

How can a dynamic SOQL query the created at runtime singinput from an end user?

Choose 1 awwer

A. Use the 50)Lexecute(string) with a query specified in the string

B. Use the Database.search(string) with a query specified in the string

C. Use the Database.query(string) with a query specified in the string

D. Use the Database execute(string) with a query specified in the string

A

C. Use the Database.query(string) with a query specified in the string

The Database query(string) method can be used to return a single or list of Objects

The SOQL execute, Database execute, and Database search methods do not exist

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, felds, relationships, and external IDs

27
Q

What constitutes the Model layer in the Model-View-Controller architecture?

Choose 2 answers.

A Visualforce Pages

B. Standard Pages

C. Custom Objects

D. Standard Objects

A

C. Custom Objects

D. Standard Objects

The Model component constitutes the elements that define the structure of the data. In Salesforce context, they are, for example, the standard and custom objects.

Standard pages and Visualforce pages belong to the presentation or “View” layer of the Model-View-Controller architecture.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

28
Q

Cosmic Containers requires that when saving an opportunity record, a check is performed to determine if the opportunity amount is the highest value amongst all the opportunities created in the current year. If so, a checkbox on the opportunity record should be marked, and an email should be sent to the record owner’s manager. Which Salesforce feature should be recommended to handle this requirement?

Choose 1 answer.

A. Apex Trigger

B. Formula Field

C. Process Builder

D. Flow Builder

A

✔️D. Flow Builder

A record-triggered flow, which runs in system context, can be launched when a record is saved. For example, a ‘Get Records’ element can be used to retrieve an opportunity with an amount that is greater than the amount on the current record. If no result is found, then the current record contains the highest amount. So, its checkbox field should be set and the checkbox field of the previous record with the highest amount, if any, should be unset. An Action element can be added to the flow for sending emails.

An Apex trigger can also meet the requirement, but the best practice is to build a declarative solution when possible. Process Builder and formula fields cannot be used to query records.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up summaries.

29
Q

There is a requirement that when an opportunity is closed, commission records should be created automatically for each member of the related opportunity team. The ‘Commission’ custom object has a currency field whose value is calculated based on the role of the opportunity team member and the Type and Amount of the related opportunity. Which automation tool should be used to meet this requirement?

Choose 1 answer.

A. Flow Builder

B. Process Builder

C. Approval Process

D. Apex Trigger

A

✔️A. Flow Builder

A record-triggered flow can be created to run when the opportunity is closed. It can perform the logic required to compute the commission values and create the commission records.

Approval processes are used for approving records and are not capable of creating records except tasks. Although Process Builder can be used to create a record, it is not capable of creating multiple records dynamically. An Apex trigger is not needed as the requirement can be met using a declarative solution.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up summaries.

30
Q

What is a valid consideration regarding development in a multi-tenant environment?

Choose 1 answer.

A. Salesforce upgrades are automatic and cannot be scheduled on a particular date

B. Although Salesforce runs in the cloud, client software is still required

C. Salesforce upgrades sandbox environments at the same time as production environments

D. Salesforce organizations can choose to accept upgrades, so different organizations may be on different releases

A

✔️A. Salesforce upgrades are automatic and cannot be scheduled on a particular date

Salesforce updates automatically 3 times a year and cannot be scheduled. No client software is required, apart from a browser to access the internet. Sandboxes are upgraded prior to production environments so that the changes can be previewed and tested.

Salesforce Reference Link

Objective: Developer Fundamentals.

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

31
Q

A developer is creating a custom Lightning page with multiple Aura components and wants certain components to refresh when the information in other components changes. The components causing the change and the components that need to be refreshed may or may not be in the same parent component. How can this be accomplished?

Choose 1 answer.

A. Use an application event to notify other components of the change and give them a chance to handle it

B. Use the reRender attribute and an onchange event handler

C. Use viewstate to detect changes in components and update other components accordingly

D. Use a component event to notify other components of the change and give them a chance to handle it

A

✔️A. Use an application event to notify other components of the change and give them a chance to handle it

The Lightning framework uses event-driven programming, so an event is the appropriate solution. Application events allow all components on a page, regardless of the containing component, to respond to an event. Component events can only be handled by components in the firing component’s containment hierarchy. Since, in the given scenario, components may reside in the same or different containers, an application event is the correct approach.

Salesforce Reference Link

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

En Lightning, un Application Event se utiliza para comunicar eventos entre componentes que no tienen relación directa entre sí, como componentes que no comparten una jerarquía de padre e hijo. Los eventos de aplicación son útiles cuando necesitas que varios componentes, potencialmente en diferentes áreas de la aplicación, respondan a un evento.

A continuación, te explico cómo puedes usar un Application Event en una página personalizada de Lightning (Lightning App Page) con un ejemplo práctico.

Pasos para usar un Application Event en una página Lightning personalizada

  1. Crear el Application Event.
  2. Disparar el evento desde un componente.
  3. Escuchar el evento en otro componente.
  4. Agregar los componentes a una página personalizada de Lightning.

Paso 1: Crear el Application Event

Primero, necesitas definir el evento. Los eventos en Lightning se definen en un archivo .evt dentro de la carpeta aura.

Ejemplo de un evento CustomAppEvent.evt:

<aura:event>
<aura:attribute></aura:attribute>
</aura:event>

Este evento tiene un atributo message de tipo String, que será enviado con el evento.

Paso 2: Disparar el evento desde un componente

En un componente Lightning, puedes disparar este evento usando fire().

Ejemplo de un componente que dispara el evento: EventSender.cmp:

<aura:component>
<aura:registerEvent></aura:registerEvent>

<lightning:button></lightning:button>
</aura:component>

Controlador del componente EventSenderController.js:

({
fireEvent : function(component, event, helper) {
var appEvent = $A.get(“e.c:CustomAppEvent”);
appEvent.setParams({
“message” : “¡Evento de aplicación disparado!”
});
appEvent.fire();
}
})

Aquí, el componente EventSender dispara el evento CustomAppEvent cuando se hace clic en el botón.

Paso 3: Escuchar el evento en otro componente

Ahora, necesitas crear un componente que escuche este evento. Puedes hacer esto registrando el evento en el componente.

Ejemplo de un componente que escucha el evento: EventReceiver.cmp:

<aura:component>
<aura:handler></aura:handler>

<lightning:formattedText></lightning:formattedText>
</aura:component>

Controlador del componente EventReceiverController.js:

({
handleEvent : function(component, event, helper) {
var message = event.getParam(“message”);
component.set(“v.message”, message);
}
})

Este componente escucha el evento y muestra el mensaje enviado desde el EventSender.

Paso 4: Agregar los componentes a una Lightning Page personalizada

Puedes agregar estos componentes en una Lightning App Page personalizada utilizando App Builder, o puedes crearlo en código.

Creación de la Lightning Page personalizada:

  1. Ve a Setup.
  2. Busca Lightning App Builder en el menú de búsqueda rápida.
  3. Crea una nueva página de aplicación.
  4. Arrastra tus componentes personalizados (EventSender y EventReceiver) a la página.

O con el siguiente código (si es una página programática):

<aura:application>
<c:EventSender></c:EventSender>
<c:EventReceiver></c:EventReceiver>
</aura:application>

Flujo completo:

  1. El usuario hace clic en el botón en EventSender.
  2. EventSender dispara el evento CustomAppEvent.
  3. EventReceiver escucha el evento y maneja la acción, mostrando el mensaje en la página.

Conclusión

Los Application Events son una forma poderosa de comunicación en aplicaciones Lightning cuando necesitas que varios componentes se comuniquen sin estar relacionados directamente. En una página Lightning personalizada, puedes disparar un evento desde un componente y escuchar ese evento en otros componentes de la misma página o incluso en diferentes áreas de la aplicación. Este patrón ayuda a desacoplar la lógica entre componentes, mejorando la modularidad de la aplicación.

32
Q

There is a requirement to validate that the country code of an account field is a valid ISO code. There are over 200 codes. What could be used for this validation?

Choose 1 answer.

A. Formula field

B. Apex trigger

C. Validation rule

D. Geolocation field

A

✔️C. Validation rule

A validation rule can be used to ensure that the code entered is valid. In this particular scenario, the validation rule’s formula field can contain a list of ISO codes with which to verify the country code.

An Apex trigger is not necessary since a declarative tool can meet the requirement. Formula fields are used for displaying values, for example, based on data from the current record or related records. Geolocation fields are used for storing longitude and latitude values.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up

33
Q

A Salesforce developer is building a Lightning Aura component and is refactoring code to create a common function that will be reused by several other JavaScript functions in the component. Which file in the component bundle should contain the common function?

Choose 1 answer.

A. The component file

B. The controller file

C. The helper file

D. The design file

A

✔️C. The helper file

Functions added in a helper file can be called from any JavaScript code in the Lightning component bundle and, hence, should be used in the above scenario. The component resource contains the markup of the Aura component, while the controller file contains functions that are, for example, invoked by event handlers. The design resource can be used to expose component attributes whose values can be modified in Lightning App Builder.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

34
Q

What is correct in respect to the Salesforce MVC paradigm?

Choose 1 answer.

A. Standard pages are part of MVC

B. Visualforce pages are part of MVC

C. Custom Objects are part of MVC

D. All Statements are true

A

✔️D. All Statements are true

Standard and custom objects are part of the model layer in MVC. Standard pages (Lightning record page, etc.) and Visualforce pages are part of the View layer.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

35
Q

Eric was told that Visualforce is part of the MVC paradigm. In this context, what does MVC stand for?

Choose 1 answer.

A. Model View Controller

B. Master Class Variable

C. Model Variable Controller

D. Master Control Variable

A

A. Model View Controller

Visualforce uses the traditional model view-controller (MVC) paradigm, with the option to use auto-generated controllers for database objects, providing simple and tight integration with the database

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework

36
Q

What method can be used to obtain metadata information about all the sObjects in an organization?

Choose 1 answer.

A describeObjects()

B. getGlobalDescribe()

C. describeSObjects()

D.getGlobalSObjects()

A

B. getGlobalDescribe()

The getGlobal Describe() method can be used to return a map of all sObject names (keys) to sObject tokens (values) of the standard and custom objects in an org

The describeSObjects() method is used to obtain metadata, such as the object properties and field list, of a single sObject or multiple sObjects. To return the metadata of multiple objects, the sObject names need to be specified in the method parameter. A describeObjects() or getGlobalSObjects() method does not exist.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs.

La función getGlobalDescribe() en Apex es una herramienta poderosa que se utiliza para obtener descripciones globales de los objetos en Salesforce. Más específicamente, esta función devuelve un mapa de todos los objetos estándar y personalizados en la organización de Salesforce, donde las claves del mapa son los nombres de los objetos y los valores son instancias de la clase SObjectType. Esta clase, a su vez, permite acceder a metadatos sobre el objeto, como sus campos, tipos de registros, etc.

Sintaxis

Map<String, Schema.SObjectType> globalDescribeMap = Schema.getGlobalDescribe();

¿Qué hace la función?

Devuelve un mapa: El resultado es un Map<String, Schema.SObjectType>. Las claves del mapa son los nombres de los objetos, como Account, Contact, o cualquier objeto personalizado como Custom_Object__c.

Acceso a los objetos de Salesforce: Permite obtener los objetos estándar y personalizados disponibles en la organización.

Permite obtener metadatos: A partir de los valores del mapa (que son instancias de Schema.SObjectType), puedes acceder a metadatos como los campos del objeto, los tipos de registros, entre otros.

Ejemplo básico

Este ejemplo muestra cómo se utiliza getGlobalDescribe() para obtener una lista de todos los objetos disponibles en la organización.

Map<String, Schema.SObjectType> globalDescribeMap = Schema.getGlobalDescribe();

for (String objectName : globalDescribeMap.keySet()) {
    System.debug('Nombre del objeto: ' + objectName);
}

Salida esperada: Esto imprimirá una lista de todos los objetos disponibles, como Account, Contact, CustomObject__c, etc.

Ejemplo práctico: Obtener campos de un objeto específico

Map<String, Schema.SObjectType> globalDescribeMap = Schema.getGlobalDescribe();

// Obtener el objeto Account
Schema.SObjectType accountObj = globalDescribeMap.get('Account');

// Obtener la descripción de los campos del objeto Account
Map<String, Schema.SObjectField> fieldsMap = accountObj.getDescribe().fields.getMap();

// Imprimir los nombres de los campos de la cuenta
for (String fieldName : fieldsMap.keySet()) {
    System.debug('Campo de Account: ' + fieldName);
}

Salida esperada: Este ejemplo imprimirá todos los campos del objeto Account, como Name, Industry, BillingCity, etc.

Ejemplo práctico: Validar si un objeto existe

Supongamos que necesitas validar si un objeto existe en el sistema antes de hacer alguna operación sobre él.

String objectName = 'Custom_Object\_\_c';  // Objeto que queremos validar
Map<String, Schema.SObjectType> globalDescribeMap = Schema.getGlobalDescribe();

if (globalDescribeMap.containsKey(objectName)) {
    System.debug('El objeto ' + objectName + ' existe en la organización.');
} else {
    System.debug('El objeto ' + objectName + ' no existe en la organización.');
}

Salida esperada:

Si el objeto Custom_Object__c existe en la organización, imprimirá: “El objeto Custom_Object__c existe en la organización.”

Si no existe, imprimirá: “El objeto Custom_Object__c no existe en la organización.”

Ejemplo práctico: Validar si un campo existe en un objeto

String objectName = 'Account';
String fieldName = 'Custom_Field\_\_c';

Map<String, Schema.SObjectType> globalDescribeMap = Schema.getGlobalDescribe();

if (globalDescribeMap.containsKey(objectName)) {
    Schema.SObjectType objType = globalDescribeMap.get(objectName);
    Map<String, Schema.SObjectField> fieldsMap = objType.getDescribe().fields.getMap();
    
    if (fieldsMap.containsKey(fieldName)) {
        System.debug('El campo ' + fieldName + ' existe en el objeto ' + objectName + '.');
    } else {
        System.debug('El campo ' + fieldName + ' no existe en el objeto ' + objectName + '.');
    }
} else {
    System.debug('El objeto ' + objectName + ' no existe en la organización.');
}

Salida esperada:

Si el campo Custom_Field__c existe en el objeto Account, imprimirá: “El campo Custom_Field__c existe en el objeto Account.”

Si no existe, imprimirá: “El campo Custom_Field__c no existe en el objeto Account.”

Conclusión

getGlobalDescribe() es muy útil para obtener dinámicamente información sobre los objetos y sus campos en Salesforce. Se usa comúnmente en situaciones donde se requiere una flexibilidad dinámica, como aplicaciones personalizadas, integración con sistemas externos, o para evitar escribir código específico para cada objeto o campo.

37
Q

A requirement has been given to display the average value of won opportunities on the Account page layout. How can this be best achieved?

Choose 1 amwer.

A. Use a trigger on the opportunity object

B. Use a trigger on the account object

C. Use a rol-up summary field with the average function

D. Use roll-up summary fields and a formula field

A

D. Use roll-up summary fields and a formula field

Correct This requirement can be met by the completing the following configuration. A roll-up summary field is created that counts the number of won opportunities. Second, another roll-up summary held is created that sums the amount of won opportunities. Third, a new formula fheld is created that calculates the average. For example, Total Won Amount c/Total Won Count c

Roll up summary fields have the Count, Sum. Min and Max functions, but do not support the Average function

It is possible to create a trigger on the Account object, but it is not the best solution since the requirement can be achieved using declarative tools

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identity common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll up summaries

38
Q

Global Insurance would like users to be able to enter policy and advisor details on a screen. When a user clicks the ‘Next’ button on the screen, the advisor commission related to the details entered by the user should be displayed on the next screen. What would be the recommended solution for this requirement?

Choose 1 answer.

A. Create an approval process

B. Create an Apex Class

C. Create a Visualforce wizard

D. Create a flow with Flow Builder

A

D. Create a flow with Flow Builder

A screen flow can be created in Flow Builder to build a wizard-like interface where details can be entered on one screen and a calculation displayed on the next screen.

Using Visualforce is not necessary as the requirement can be met using a declarative solution. Similarly, An Apex class alone cannot be used for this requirement, and using it along with Visualforce, for example, is unnecessary. Also, approval processes cannot be used for building interfaces

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up summaries.

39
Q

Because Apex runs in a multitenant environment, the Apex runtime engine enforces governor limits to ensure that Apex code or processes don’t monopolize shared resources. What are valid examples of these lumits?

Choose 3 answers.

A. Maximum execution time for a DML, operation

B. Total number of records retrieved by SOQL queries

C. Time executing a 50QL query

D. CPU time per transaction

E. Maximum number of records that can be stored

A

B. Total number of records retrieved by SOQL queries

C. Time executing a 50QL query

D. CPU time per transaction
The runtime engine enforces limits of how long SOQL query can run, how many records can be returned in a query and the maximum ammount of CPU time a transaction can take The maximum number of records that can be stored in an object is dependent on the storage available and is not subject to a governor limit.

Unlike SOQL queries, there is no maximum execution time for DML statements. There is, however, a limit for the total number of DML statements that can be executed in an Apex transaction.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework

40
Q

A developer has created a custom Lightning component, but the component isn’t showing up in Lightning App Bullder. Why is this happening?

Choose 1 answer.

A My Domain has not been defined and deployed tis the org

The lightning component has not been activated

C. The component has not been defined as public

D. The org doesn’t support the use of custom Lightning components

A

✔️A My Domain has not been defined and deployed tis the org

My domain must be confugured and deployed to the org in order to use custom Lightning components. Lightning components do not need to be activated after being deployed to the org. Lightning components are defined as public by default

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework

41
Q

Which of the following are part of the model layer in the MVC model?
Choose 3 answers

A Relationships

B. Tabs

C. Objects

D. Fields

E. Page Layouts

A

✔️A Relationships
✔️C. Objects
✔️ D. Fields

The model layer includes fields, objects, and relationships, whereas tabs and page layouts are part of the view layer.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework

42
Q

Which of the following use cases are valid for using declarative customization?

Choose 3 answers.

A. Displaying the discount amount on an opportunity using a roll-up summary field that uses cross-object formula fields

B. Meeting high-performance batch processing requirements in an org with a large data volume

C. Calculating the number of days until an opportunity closes and displaying the value on a report

D Displaying the number of employees of the account related to an opportunity on the Opportunity page layout

E. Determining a lead rating that is based on the value of three fields on the lead record

A

✔️C. Calculating the number of days until an opportunity closes and displaying the value on a report

✔️D. Displaying the number of employees of the account related to an opportunity on the Opportunity page layout

✔️E. Determining a lead rating that is based on the value of three fields on the lead record

The NumberOfEmployees field on the Account object can be displayed in the related Opportunity object using a cross-object formula field. The TODAY() function and an Opportunity’s Close Date field can be used in a formula to determine the number of days left leading to its close date in a custom field or row level formula field in a report, Fields, functions, and operators can be used in a formula to generate certain output such as lead rating

Apex should be used to meet high-performance batch processing requirements Cross object formula fieich cannot be used intoll-up summary helds.

✔️C. Calcular la cantidad de días hasta el cierre de una oportunidad y mostrar el valor en un informe

✔️D. Mostrar la cantidad de empleados de la cuenta relacionada con una oportunidad en el diseño de la página Oportunidad

✔️E. Determinar una calificación de cliente potencial basada en el valor de tres campos en el registro de cliente potencial

El campo NumberOfEmployees en el objeto Cuenta se puede mostrar en el objeto Oportunidad relacionado mediante un campo de fórmula entre objetos. La función TODAY() y el campo Fecha de cierre de una oportunidad se pueden usar en una fórmula para determinar la cantidad de días restantes hasta su fecha de cierre en un campo personalizado o un campo de fórmula de nivel de fila en un informe. Los campos, las funciones y los operadores se pueden usar en una fórmula para generar ciertos resultados, como la calificación de cliente potencial

Apex se debe usar para cumplir con los requisitos de procesamiento por lotes de alto rendimiento. El archivo de fórmula entre objetos no se puede usar en los resúmenes de pedidos.

43
Q

Cosmic Luxio is a company that manufactures and sells luxury watches. Customers can purchase products from the company’s website or by visiting an authorized retail store. Each retail store uses a custom weh application for managing sales orders. The application supports making custom HTTP POST requests to external endpoints. Salesforce is used by the employees who work at the company’s headquarters. When a new sales order is created by a retail store, certain users in Salesforce should be notifed and a record of a custom object should be created automatically. A platform event with several custom fields has been defined by a developer for this use case. Which approach should be utilized to publish a platform event message using the custom web application for this requirement?

Choose 1 answer

A. Use REST API to send a POST request with a platform event message to a Salesforce endpoint.

B. Use SOAP API to send a POST request with a platform event message to a Salesforce endpoint

C. Use EMP Connector to create a custom client that can publish platform event messages to the event bus.

D. Use a flow to publish a platform event message to the event bus

A

✔️A. Use REST API to send a POST request with a platform event message to a Salesforce endpoint.

In this scenario, since the external application supports making HTTP POST requests, REST API can be used to publish platform event messages. If ‘Sales Order Event e’ is the name of the platform event associated with the creation of sales orders, a POST request can be sent to publish an event message using the following endpoint URL format: /hervices/data/ API Version XXX>/sobjects/Sales Order Event_e/

In Salesforce, a flow, process, or Apex trigger can be used to subscribe to the platform event. When an event message is received, it can send an email to the users and create a record of a custom object automatically

In order to publish event messages using SOAP API, the create() call is used instead of a POST request. Flow is an automation tool in Salesforce that cannot be used to publish event messages from an external application. EMP Connector is used to subscribe to platform event messages.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, determine, create, and access the appropriate data model including objects, fields, relationships, and external IDs

44
Q

Cosmic Electronics uses Salesforce to manage opportunities. The company also uses an external order management application to manage orders, Sales users use the application to create orders manually after winning sales deals. However, the sales director would like to automate this process. When an opportunity is won, the external application should receive a notification and create the associated Order record automatically based on the details in the notification. A developer of the company has decided to use a platform event for this use case. Which of the following should be utilized when using a platform event to meet this requirement?

Choose 3 answers.

A Platform event definition with custom fields

B. Apex trigger, flow, or process that publishes an event message

C. Apex class that subscribes to the platform event channel

D. CometD client that subscribes to the platform event channel

E. Custom object definition with custom fields

A

✔️A. Platform event definition with custom fields

✔️B. Apex trigger, flow, or process that publishes an event message

✔️D. CometD client that subscribes to the platform event channel

In order to meet this requirement, a platform event object can be defined in ‘Platform Events in Setup which also supports custom fields. The custom fields added to the platform event can contain data that should be sent in the event message. Salesforce can publish the platform event message and the external application can act as the subscriber.

An Apex trigger, flow, or process on the Opportunity object can be used to publish a platform event message automatically when the stage of an opportunity changes to ‘Closed Won: For example, when using an Apex trigger, the event message can be published using the EventBus publish() method. The external application can subscribe to the event channel using a custom Comet) client or EMP Connector and receive event messages.

When a message is received, the external application can create an order automatically based on the field values in the message

A custom object definition is not required to set up a platform event. An Apex class is also not required to subscribe to the platform event from the external system

Obiective: Ravelonien Fundamentals

✔️A. Definición de evento de plataforma con campos personalizados

✔️B. Activador, flujo o proceso de Apex que publica un mensaje de evento

✔️D. Cliente CometD que se suscribe al canal de eventos de plataforma

Para cumplir con este requisito, se puede definir un objeto de evento de plataforma en ‘Eventos de plataforma en Configuración’ que también admita campos personalizados. Los campos personalizados agregados al evento de plataforma pueden contener datos que se deben enviar en el mensaje de evento. Salesforce puede publicar el mensaje de evento de plataforma y la aplicación externa puede actuar como suscriptor.

Se puede usar un activador, flujo o proceso de Apex en el objeto Oportunidad para publicar un mensaje de evento de plataforma automáticamente cuando la etapa de una oportunidad cambia a ‘Cerrada ganada’: por ejemplo, cuando se usa un activador de Apex, el mensaje de evento se puede publicar usando el método publish() de EventBus. La aplicación externa puede suscribirse al canal de eventos usando un cliente Comet personalizado o EMP Connector y recibir mensajes de eventos.

Cuando se recibe un mensaje, la aplicación externa puede crear un pedido automáticamente en función de los valores de campo del mensaje

No se requiere una definición de objeto personalizada para configurar un evento de plataforma. Tampoco se requiere una clase Apex para suscribirse al evento de plataforma desde el sistema externo

Objetivo: Fundamentos de Ravelonien

45
Q

Which of the following are true regarding developing in the Salesforce multi-tenant environment?

Choose 2 answers.

A. it is not possible to index application data as each tenant stores different types of data in the same application table

B. Queries should be selective in terms of the number of records returned

C. Salesforce uses and optimizes different database technologies to implement polyglot persistence

D. The custom domain feature ensures that different customers do not access each other’s data

A

✔️B. Queries should be selective in terms of the number of records returned

✔️C. Salesforce uses and optimizes different database technologies to implement polyglot persistence

Force.com integrates and optimizes several different data persistence technologies to deliver polyglot persistence. Only a single API needs to be coded to, no matter which type of persistence is optimal for a given situation. The platform monitors queries and DML operations and throws a runtime exception if they exceed governor limits.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.

46
Q

A Salesforce developer wants to build a custom user interface for internal users. The interface will contain fields pulled from different Salesforce objects, some of which are most suitable solution in the given options?

Choose 1 answes

A Develop an application using Heroku and embed it in the Salesforce org

B Build a custom page layout in Salesforce containing the required information

C. Build a page using Dynamic Forms and Field Section Lightning components

D. Develop a Visualforce page to display helds from the different objects

A

D. Develop a Visualforce page to display helds from the different objects

Since the custom user interface is for internal use only and needs to pull in Salesforce data from different objects, a programmatic solution such as a Visualforce page or custom Lightning componerit is r

A page layout cannot display fields from urirelated objects. Heroku is best used for customer-facing sites. Dynamic Forms and Field Section Lightning components are supported in Lightning record pages only and support fields that are related to the primary record.

Objective: Developer Fundamentals

Detailed Objective: Given a scenario, identify common use cases and best practices for declarative versus programmatic customizations, including governor limits, formula fields, and roll-up summaries

47
Q

A Salesforce Developer working for Cosmic Traders would like to create a custom Lightning App page in Lightning App Builder to meet a particular business requirement. Which of the following can be added to the Lightning page?

Choose 2 answers

A: Object-specific actions

B. Global actions

C Standard components

D. Primary components

A

B. Global actions

C. Standard components

Standard, custom, and third-party components can be added to the Lightning page. Global actions can be added via the Actions attribute of the Lightning App page properties, which is only possible for this Lightning page tpe. The other Lightning page types derive their actions from the object and global page layouts.

There are only standard, custom, and third-party Lightning components. There are no “primary” components. Object specific actions are only supported on Lightning Record pages

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework,

48
Q

Coumic Innovation is considering the use of the Lightning Component Framework to build a custom application for managing the company’s products. Which of the following are valid capabilities of the framework that would be useful for understanding how to develop and provide access to the custom application?

Choose 3 antwers

A. The framework uses JavaScript on the client-side and Apex on the server-side.

B. The framework utilizes stateless client and stateful server, which improves efficiency and responsiveness.

C. The components built using the framework offer cross-browser compatibility but not device awareness

D. The framework provides two programming models for development, namely, Aura Components and Lightning Web Components.

E. The components built using the framework can be added as custom tabs on the navigation bar

A

✔️A. The framework uses JavaScript on the client-side and Apex on the server-side.

✔️D. The framework provides two programming models for development, namely, Aura Components and Lightning Web Components.

✔️ E. The components built using the framework can be added as custom tabs on the navigation bar

The Lightning Component Framework is a Ul framework that allows building single-page web apps with dynamic and responsive user interfaces in Salesforce. It uses JavaScript on the client side and Apex on the server-side. Lightning components can be built using the Aura Components or Lightning Web Components model. They can coexist and interoperate on a page

The framework offers features such as device awareness and cross-browser compatibility, allows using various out-of-the-box components for faster development, and enables customizing Lightning Experience and communities. It utilizes a stateful client (using JavaScript) and a stateless server (Apex). The client calls the server only when absolutely necessary, which results in fewer calls to the server and more responsive and efficient apps. Lightning components can be used in many different contexts. For example, they can be added as custom tabs in Lightning Experience and the Salesforce mobile app.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework

49
Q

Cosmic Finance Solutions has recently switched to Lightning Experience. The Salesforce Administrator of the company would like to make use of Lightning components to enhance the user experience. Which of the following can be created using the Lightning App Builder?

Choose 3 answers

A Single-page apps

B. Tabs

C. Custom record pages

D. Custom page layouts

E. Custom home pages

A

✔️A Single-page apps
✔️C. Custom record pages
✔️E. Custom home pages

App pages, record pages, home pages, and email application panes can be built using Lightning App Builder.

Page layouts can be created in the Object Manager page of an object. Lightning tabs can be created in the Tabs page in Setup.

Objective: Developer Fundamentals

Detailed Objective: Understand multi-tenant concepts and design frameworks, such as MVC architecture and Lightning Component Framework.