Guest Post

Guest Post sfdcpoint

Guest Post to sfdcpoint.com Want to contribute an article to sfdcpoint.com? Please share your post to dureja.ankush90@gmail.com. Purpose of sfdcpoint.com is to share knowledge with salesforce community. So all of you are welcome to post your article on sfdcpoint.com.

Here are some of tips for post:

  • Article Quality : Try to write an article with more than 300 words.
  • Screenshot: Sometime image speaks more than words. So its advisable to add some screenshot.
  • Video: If possible, add some video for demo. Its not necessary.

Send your article to dureja.ankush90@gmail.com with subject line sfdcpoint guest post. We will review your post. Once approved we will post your article to sfdcpoint with your name. You will also be rewarded with some goodies.

Good Luck 🙂

 

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/guest-post/

Modal/Popup Lightning Component Salesforce

Modal/Popup Lightning Component Salesforce

Modal/Popup Lightning Component Salesforce

In this post, We will simply create a custom Lightning Modal/Popup Box in the salesforce lightning component.

What is Modal in Salesforce Lightning Experience ?

Modals/Popup Box are used to display content in a layer above the app. This paradigm is used in cases such as the creation or editing of a record, as well as various types of messaging and wizards.

Modal/Popup Lightning Component Salesforce looks like following image

Modal Popup Lightning Component Salesforce

Modal Popup Lightning Component Salesforce

 

ModalPopupExample1 Lightning  Component

In this code we are first declaring ‘isModalOpen’ attribute and setting its default value as false. Then using aura:if we are conditionally displaying modal/popup on click of button. For more details about aura:if, please refer my previous post aura:if in lightning component example

Also code has following three main part

  • section
  • header
  • footer

Details are explained in code comment.

Following is expected markup

Expected markup in in modal/popup

  • Modal has role="dialog"
  • When the modal is open, everything behind it has HTML attribute aria-hidden="true", so assistive technology won’t read out the underlying page. The best way to do this is to give the modal and the page separate wrapper elements and toggle aria-hidden="true"/aria-hidden="false" on the main page’s wrapper depending on whether or not the modal is open.
  • Modal contains an HTML heading
  • Modal has an aria-labelledby attribute whose value is the id of the modal’s heading

 

<aura:component>
    <!--Boolean attribute to indicate if modal is open or not 
       default value is false as modal is closed when page is loaded 
    --> 
    <aura:attribute name="isModalOpen" type="boolean" default="false"/>
    
    <div class="slds-m-around_xx-large">
        <lightning:button variant="brand"
                          label="What is Modal/PopUp Box?"
                          title="What is Modal/PopUp Box?"
                          onclick="{! c.openModel }" />
        <!--Use aura:if tag to display/hide popup based on isModalOpen value-->   
        <aura:if isTrue="{!v.isModalOpen}">
            
            <!-- Modal/Popup Box starts here--> 
            <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
                <div class="slds-modal__container">
                    <!-- Modal/Popup Box Header Starts here-->
                    <header class="slds-modal__header">
                        <lightning:buttonIcon iconName="utility:close"
                                              onclick="{! c.closeModel }"
                                              alternativeText="close"
                                              variant="bare-inverse"
                                              class="slds-modal__close"/>
                        <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Modal/PopUp Box</h2>
                    </header>
                    <!--Modal/Popup Box Body Starts here-->
                    <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                        <p><b>Modals/Popup Box are used to display content in a layer above the app. This paradigm is used in cases such as the creation or editing of a record, as well as various types of messaging and wizards.
                            </b>
                        </p>
                    </div>
                    <!--Modal/Popup Box Footer Starts here-->
                    <footer class="slds-modal__footer">
                        <lightning:button variant="neutral" 
                                          label="Cancel"
                                          title="Cancel"
                                          onclick="{! c.closeModel }"/>
                        <lightning:button variant="brand" 
                                          label="OK"
                                          title="OK"
                                          onclick="{!c.submitDetails}"/>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
        </aura:if>
    </div>
</aura:component>

Lightning Component Controller

({
   openModel: function(component, event, helper) {
      // Set isModalOpen attribute to true
      component.set("v.isModalOpen", true);
   },
 
   closeModel: function(component, event, helper) {
      // Set isModalOpen attribute to false  
      component.set("v.isModalOpen", false);
   },
 
   submitDetails: function(component, event, helper) {
      // Set isModalOpen attribute to false
      //Add your code to call apex method or do some processing
      component.set("v.isModalOpen", false);
   },
})

Lightning component App ModalPopupExampleApp1

<aura:application extends="force:slds">
	<c:ModalPopupExample1/>
</aura:application>

More details about lightning modal/popup

Modals always have an equal amount of space at the top and bottom to account for the height of the close button.

Modals grow according to how much content is within, but once the modal reaches full height (including the previously mentioned space on top and bottom), the content area will begin to scroll. (This scrolling is currently not available in Salesforce1 Mobile.)

For more details about modal in lightning, please refer to modal lightning

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/modal-popup-lightning-component-salesforce/

Salesforce admin interview questions

Salesforce admin interview questions and answers

Salesforce admin interview questions and answers.

Here is list of all Salesforce admin interview questions:

  • What is Salesforce?
  • What is Cloud computing?
  • What is CRM?
  • What are some CRM provider
  • What are different types of cloud computing?
  • What is PaaS?
  • What is SaaS?
  • What is IaaS?
  • What are different Salesforce Editions?
  • What is difference between Salesforce.com and Force.com?
  • What is Database.com?
  • What is App in Salesforce?
  • What is an object in Salesforce?
  • Different types of object in Salesforce.com?
  • How many relationship types are in Salesforce?
  • What is Master-detail  relationship?
  • What is Many-to-many relationship?
  • What is External lookup?
  • What is Indirect lookup?
  • What is Hierarchical relationship?
  • What is a roll-up summary field?
  • What are different Levels of data access in Salesforce?
  • What is Organization-wide defaults?
  • What is role hierarchy?
  • What are the difference between a Role and Profile?
  • What are Sharing Rules?
  • What is Manual sharing?
  • What is Profile?
  • What are standard profiles?
  • What is Permission Set?
  • What is “View all” and “Modify all” permission?
  • Is it possible to restrict permission for users using permission set?
  • If a user does not have access to a specific record type, will they be able to see the records that have that record type?
  • What are Salesforce Reports?
  • What are the different Report Formats?
  • What is Tabular Report?
  • What is Summary Report?
  • What is Matrix Report?
  • What is Joined Report?
  • What is Conditional Highlighting in Salesforce report?
  • What is Bucket Field?
  • Which field type does Bucketing field support?
  • What are Dashboards?
  • What are the different Dashboard Component?
  • What is Workflow?
  • What are the types of Workflow actions?
  • What is Time-dependent Workflow?
  • What is Approval Process?
  • What are Assignment Rules?
  • What are Queues?
  • What are Auto-Response Rules?
  • What is Escalation Rules?
  • What is Chatter in Salesforce?

 

Here is list of all Salesforce admin interview questions and answers:

CRM and Cloud Computing basics Salesforce admin interview questions

What is Salesforce?

Salesforce is the world’s #1 customer relationship management (CRM) platform. Salesforce provides cloud-based, CRM applications for sales, service, marketing, and more.

Salesforce has essentially changed how enterprise software is delivered and used. Its software is cloud-based and hence doesn’t need IT experts to set up anything. Salesforce has defined the ideal way as how to connect with customers. Building meaningful and lasting bond with the customers, identifying their needs, address problems faster and deploy apps that are customer focused is all possible through Salesforce.

Salesforce Technologies is one of the leading and very hot Technology in IT industry. Through Salesforce.com Technology thousands of Job opportunity are created for Salesforce developers and Salesforce Administration Job Seekers. As per Forbes magazine, nearly 55% of enterprises predict cloud computing will enable new business model in three years. So Salesforce is one of the Cloud Computing Technology which have bright future in the upcoming years. Salesforce provides different enterprise cloud computing applications to all size industries and businesses.

Salesforce applications are provided on subscription basis primarily through direct sales effort and indirectly through partners.

What is Cloud computing?

Cloud computing is a kind of outsourcing of computer programs. Using cloud computing, users are able to access software and applications from wherever they are; the computer programs are being hosted by an outside party and reside in the cloud. This means that users do not have to worry about things such as storage and power, they can simply enjoy the end result.

Cloud computing is shared pools of configurable computer system resources and higher-level services that can be rapidly provisioned with minimal management effort, often over the Internet. Cloud computing relies on sharing of resources to achieve coherence and economies of scale, similar to a public utility.

What is CRM?

CRM means “Customer Relationship Management “. We can understand from the full form where CRM is an application used to automate Sales and marketing functions by a using a Software called CRM Software. By using CRM Software every Company / Organization plans to increase their revenues and profits. This strategy of increasing revenue is done mainly by attracting Customers, clients, Sales etc.

Salesforce Admin Interview questions

Salesforce Admin Interview questions

More Salesforce admin interview questions

What are some CRM provider

  • Salesforce CRM.
  • Microsoft Dynamics CRM.
  • Oracle CRM.
  • SAP CRM.
  • Sage CRM.
  • NetSuite CRM.
  • Oracle CRM on Demand.
  • SugarCRM.

 

What are different types of cloud computing?

  • Infrastructure as a Service (IaaS)
  • Software as a Service (SaaS)
  • Platform as a Service (PaaS)

 

What is PaaS?

Platform as a Service (PaaS)

The branch of cloud computing that allows users to develop, run, and manage applications without having to get caught up in code, storage, infrastructure and so on.

There are several types of PaaS. Every PaaS option is either public, private, or a hybrid mix of the two. Public PaaS is hosted in the cloud, and its infrastructure is managed by the provider. Private PaaS, on the other hand, is housed in onsite servers or private networks and is maintained by the user. Hybrid PaaS uses elements from both public and private and is capable of executing applications from multiple cloud infrastructures.

What is SaaS?

Software as a Service (SaaS)

Using the cloud, software such as an internet browser or application is able to become a usable tool.

What is IaaS?

Infrastructure as a Service (IaaS)

A third party hosts elements of infrastructure, such as hardware, software, servers, and storage, also providing backup, security, and maintenance.

What are different Salesforce Editions?

  • Essentials: Designed for small businesses that want to get started with a CRM system quickly. It includes intuitive walkthroughs and a setup assistant to get started, an easy-to-use UI, and administration tools to customize your deployment as you grow.
  • Professional: Designed for businesses requiring full-featured CRM functionality. It includes straightforward and easy-to-use customization, integration, and administration tools to facilitate any small to midsize deployment.
  • Enterprise: Meets the needs of large and complex businesses. It gives you advanced customization and administration tools, in addition to all the functionality available in Professional Edition, that can support large-scale deployments. Enterprise Edition also includes access to Salesforce APIs, so you can easily integrate with back-office systems.
  • Unlimited: Maximizes your success and extends it across the entire enterprise through the Lightning Platform. It gives you new levels of platform flexibility for managing and sharing all your information on demand. Includes all Enterprise Edition functionality, Premier Support, full mobile access, unlimited custom apps, increased storage limits, and other features.
  • Developer: Provides access to the Lightning Platform and APIs. It lets developers extend Salesforce, integrate with other applications, and develop new tools and applications. Developer Edition also provides access to many of the features available in Enterprise Edition.

What is difference between Salesforce.com and Force.com?

Salesforce.com and fore.com are relatively same but they are different in their functionality. Salesforce.com is used to develop CRM functionality based application where force.com is used to customize our data model, business logic and User interface.

What is Database.com?

Database.com is a type of service provided by Salesforce.com to enhance the power of Salesforce.com CRM applications. Database.com provides “Data as a Service” to subscribers.

What is App in Salesforce?

App means an Application. In Salesforce an Application consists a group of tabs which are designed to work as a single function. We have number of applications in Salesforce.com some of them are sales, marketing, chatter, site.com, work.com etc.

We can create new application and also customization for the existing apps in Salesforce.com. To create new app in sfdc go to Setup=>Build=>Create=>App.

Fields and Objects Salesforce Admin Interview questions

What is an object in Salesforce?

An Objects is represented as a database table which stores organization data . Objects consists of set of fields and we store data against that field. To view data Salesforce provided  TABS.

To create custom fields go to Setup=>Build=>Create=>Object.

Different types of object in Salesforce.com? 

In Salesforce.com we have two types of objects. They are

  • Standard Objects :- Standard objects are called so because they are created and provided by Salesforce.com.
  • Custom Objects :- Custom objects are those which are created by an User in salesforce.com.

 

How many relationship types are in Salesforce?

  • Master-detail 
  • Many-to-many
  • Lookup
  • External lookup
  • Indirect lookup
  • Hierarchical

 

What is Master-detail  relationship?

Master-detail closely links objects together such that the master record controls certain behaviors of the detail and subdetail record. For example, you can define a two-object master-detail relationship, such as Account—Expense Report, that extends the relationship to subdetail records, such as Account—Expense Report—Expense Line Item. You can then perform operations across the master—detail—subdetail relationship.

What is Many-to-many relationship?

Many-to-many You can use master-detail relationships to model many-to-many relationships between any two objects. A many-to-many relationship allows each record of one object to be linked to multiple records from another object and vice versa. For example, you create a custom object called “Bug” that relates to the standard case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs.

Lookup Links two objects together. Lookup relationships are similar to master-detail relationships, except they do not support sharing or roll-up summary fields. With a lookup relationship, you can:

  • Link two different objects.
  • Link an object with itself (with the exception of the user object; see Hierarchical). For example, you might want to link a custom object called “Bug” with itself to show how two different bugs are related to the same problem.

 

What is External lookup? 

External lookup An external lookup relationship links a child standard, custom, or external object to a parent external object. When you create an external lookup relationship field, the standard External ID field on the parent external object is matched against the values of the child’s external lookup relationship field. External object field values come from an external data source.

What is Indirect lookup?

Indirect lookup An indirect lookup relationship links a child external object to a parent standard or custom object. When you create an indirect lookup relationship field on an external object, you specify the parent object field and the child object field to match and associate records in the relationship. Specifically, you select a custom unique, external ID field on the parent object to match against the child’s indirect lookup relationship field, whose values come from an external data source.

What is Hierarchical relationship?

Hierarchical A special lookup relationship available for only the user object. It lets users use a lookup field to associate one user with another that does not directly or indirectly refer to itself. For example, you can create a custom hierarchical relationship field to store each user’s direct manager.

For more details, please refer to this link Object Relationships Overview

 

What is a roll-up summary field?

A roll-up summary field calculates values from related records, such as those in a related list. You can create a roll-up summary field to display a value in a master record based on the values of fields in a detail record. The detail record must be related to the master through a master-detail relationship. For example, you want to display the sum of invoice amounts for all related invoice custom object records in an account’s Invoices related list. You can display this total in a custom account field called Total Invoice Amount. 

For more details refer official link roll-up summary field

Security related Salesforce Admin Interview Questions

What are different Levels of data access in Salesforce?

Organization level security

For your whole org, you can maintain a list of authorized users, set password policies, and limit logins to certain hours and locations.

Object level security

Access to object-level data is the simplest thing to control. By setting permissions on a particular type of object, you can prevent a group of users from creating, viewing, editing, or deleting any records of that object. For example, you can use object permissions to ensure that interviewers can view positions and job applications but not edit or delete them.

Field level security

You can restrict access to certain fields, even if a user has access to the object. For example, you can make the salary field in a position object invisible to interviewers but visible to hiring managers and recruiters.

Record level security

You can allow particular users to view an object, but then restrict the individual object records they’re allowed to see. For example, an interviewer can see and edit her own reviews, but not the reviews of other interviewers. You can manage record-level access in these four ways.

  • Organization-wide defaults
  • Role hierarchies
  • Sharing rules
  • Manual sharing

 

What is Organization-wide defaults?

Organization Wide Defaults(OWD) in salesforce is the baseline level of access that the most restricted user should have. Organizational Wide Defaults are used to restrict access. You grant access through other means like(sharing rules, Role Hierarchy, Sales Teams and Account teams, manual sharing, Apex Sharing ). In simple words Organization Wide Defaults(OWD) specify the default level of access users have to each other’s records.

For more details please level to below post Organization Wide Defaults(OWD) in salesforce

What is role hierarchy?

It give access for users higher in the hierarchy to all records owned by users below them in the hierarchy. Role hierarchies don’t have to match your organization chart exactly. Instead, each role in the hierarchy should represent a level of data access that a user or group of users needs.

What are the difference between a Role and Profile?

Roles are one of the ways you can control access to records. They also impact reports (e.g. “My Teams” filter). Roles come into play if your security model (OWDs) are set to private.

Profiles help determine record privileges. Assuming the User can see the record, Profiles determine what the User can do, view or edit on that record. Profiles control other system privileges as well (mass email, export data, etc)

In simple words, Roles are one of the ways you can control access to records and Profiles determine what the User can do, view or edit on that record.

What are Sharing Rules?

Sharing Rules are automatic exceptions to organization-wide defaults for particular groups of users, so they can get to records they don’t own or can’t normally see. Sharing rules, like role hierarchies, are only used to give additional users access to records. They can’t be stricter than your organization-wide default settings.

What is Manual sharing?

It allows owners of particular records to share them with other users. Although manual sharing isn’t automated like org-wide sharing settings, role hierarchies, or sharing rules, it can be useful in some situations, such as when a recruiter going on vacation needs to temporarily assign ownership of a job application to someone else.

What is Profile?

Each user has a single profile that controls which data and features that user has access to. A profile is a collection of settings and permissions. Profile settings determine which data the user can see, and permissions determine what the user can do with that data.
  • The settings in a user’s profile determine whether she can see a particular app, tab, field, or record type.
  • The permissions in a user’s profile determine whether she can create or edit records of a given type, run reports, and customize the app.

Profiles usually match up with a user’s job function (for example, system administrator, recruiter, or hiring manager), but you can have profiles for anything that makes sense for your Salesforce org. A profile can be assigned to many users, but a user can have only one profile at a time.

What are standard profiles?

  • Read Only
  • Standard User
  • Marketing User
  • Contract Manager
  • System Administrator

 

What is Permission Set?

A permission set is a collection of settings and permissions that give users access to various tools and functions. The settings and permissions in permission sets are also found in profiles, but permission sets extend users’ functional access without changing their profiles.

Permission sets make it easy to grant access to the various apps and custom objects in your org, and to take away access when it’s no longer needed.

Users can have only one profile, but they can have multiple permission sets.

What is “View all” and “Modify all” permission?

View all and Modify all permissions are usually given to system administrator. When you grant “View All” or “Modify All” for an object on a profile or permission set, you grant any associated users access to all records of that object regardless of the sharing and security settings.

In essence, the “View All” and “Modify All” permissions ignore the sharing model, role hierarchy, and sharing rules that the “Create,” “Read,” “Edit,” and “Delete” permissions respect. Furthermore, “Modify All” also gives a user the ability to mass transfer, mass update, and mass delete records of that specific object, and approve such records even if the user is not a designated approver.

These tasks are typically reserved for administrators, but because “View All” and “Modify All” let us selectively override the system, responsibilities that are usually reserved for the administrator can be delegated to other users in a highly controlled fashion.

 

Is it possible to restrict permission for users using permission set?

No, Permission Set always extends the permission. It does not restrict permission to users.

If a user does not have access to a specific record type, will they be able to see the records that have that record type?

Yes, Record type controls only visibility of record on UI but not its access to users. If user does not have access to record type then user will not be able to create records for that record type using UI. But user will we able to see records if they have appropriate permission to do so.

For more details about security questions for Salesforce admin interview questions, refer to my previous post Salesforce security interview questions

Report and Dashboard related Salesforce Admin Interview Questions

What are Salesforce Reports?

A Reports is a set of records displayed in the form of rows and columns.
Reports data can be filtered, grouped, and displayed graphically as a chart. Reports are stored in Folder – which controls who has access.

What are the different Report Formats?

Tabular Reports, Summary Reports, Matrix Reports, Joined Reports.

What is Tabular Report?

It is the simplest and fastest report formats. It displays the rows as records and fields are listed as columns just like a spreadsheet. It supports sorting of records.

What is Summary Report?

This report allows the user to group rows of data, summarize the field value which also supports sorting and display subtotals.

What is Matrix Report?

In this report, records are summarized in a grid format. It allows the records to be grouped by both columns and rows.

What is Joined Report?

In this type of report, User can create multiple report blocks that provide different different views of your data. In this format of report, we organize the data in the form of block. You can add upto 5 blocks in a single report. Each block is defined as a Sub-report(Report Type). It can have its own field, columns, sorting and filtering.

What is Conditional Highlighting in Salesforce report?

Conditional Highlighting is a powerful way to show values in report within given
limits. Using Conditional Highlighting, We can specify colours for different ranges of values in reports.

What is Bucket Field?

Bucketing lets you quickly categorize report records, without having to create a formula or a custom field.

Which field type does Bucketing field support?

It supports the field type of Picklist, Number, Text.

What are Dashboards?

Salesforce Dashboard is the visual representation of snapshots that are generated from Salesforce reports data. Using Salesforce Dashboard components, you can convert business requirements in Graphical representation using Sales force reports. Like reports, Dashboard are also stored in Folders.

What are the different Dashboard Component?

Scatter Chart, Line Chart, Funnel Chart, Vertical Bar Chart, Donut Chart, Horizontal Bar Chart, Pie Chart, Gauge, Metric, Table, Visual force Pages.

Other Salesforce admin interview questions

What is Workflow? 

Workflow rules are the automated process used in business process to send Email Alerts, Assign a Task, Update a field on rule criteria or action based criteria requirements.

What are the types of Workflow actions?

  • Task – Assign a Task
  • Email Alert: Send an Email.
  • Field update: Update a Field.
  • Outbound Message: Send an Outbound Message to External System.

What is Time-dependent Workflow?

The workflow that are scheduled to happen at a later time.

What is Approval Process?

Approval Process are used in the business process to Approve or Reject the record.
It involves Approval or Rejection of records, where one person creates the record and
submits that record for Approval.

What are Assignment Rules?

Assignment Rules automatically assign incoming Leads & Cases to specific agents so that the right people work on the right leads and cases.

What are Queues?

Queues allow the group of users to manage a shared workload more efficiently It prioritize your support team’s workload by creating lists from which specific agents can jump in to solve certain types of cases.

What are Auto-Response Rules?

Auto Response Rules Automatically send personalized email templates for new cases and new leads from your website.

What is Escalation Rules?

Escalation Rules ,  Automatically escalate cases to the right people when the cases aren’t solved by a certain time.

What is Chatter in Salesforce?

Chatter is a Salesforce real-time collaboration application that lets your users work together, talk to each other, and share information.

If you have any question related to Salesforce admin interview questions, please add your comments

I will keep adding more questions to Salesforce admin interview questions.

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-admin-interview-questions/

Lightning Datatable example salesforce

Lightning Datatable example salesforce

Lightning Datatable example salesforce

In this blog post, I am going to explain how to use salesforce lightning:datatable component and its features. A lightning:datatable component displays tabular data where each column can be displayed based on the data type. lightning:datatable also supports inline editing. lightning:datatable is not supported on mobile devices. Following are some main features of lightning:datatable

  • Displaying and formatting of columns with appropriate data types
  • Infinite scrolling of rows
  • Inline editing for some data types
  • Header-level actions
  • Row-level actions
  • Resizing of columns
  • Selecting of rows
  • Sorting of columns by ascending and descending order
  • Text wrapping and clipping
  • Row numbering column
  • Cell content alignment

 

Tables can be populated during initialization using the data, columns, and keyField attributes. The keyField attribute is required for correct table behavior. It will associate each row with a unique identifier. The below code shows how to use the lightning: datatable to initialize the data and columns which are passed by using attributes.

In this example, we will simply display list of account using lightning:datatable.

Apex class AccountController

public class AccountController{
    @AuraEnabled
    public static List <Account> fetchAccounts() {
        //Qyery 10 accounts
        List<Account> accList = [SELECT Id, Name, BillingState, 
                                    Website, Phone, Industry, Type from Account LIMIT 10];
        //return list of accounts
        return accList;
    }
}

Lightning Component LightningDatatableExample

<aura:component controller="AccountController">
    
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"/>
    
</aura:component>

Lightning Component LightningDatatableExample Controller

({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, helper);
    }
})

Lightning Component LightningDatatableExample Helper

({
	fetchAccHelper : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
                {label: 'Industry', fieldName: 'Industry', type: 'text'},
                {label: 'Phone', fieldName: 'Phone', type: 'Phone'},
                {label: 'Website', fieldName: 'Website', type: 'url '}
            ]);
        var action = component.get("c.fetchAccounts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})

Lightning Application LightningDatatableExample

<aura:application extends="force:slds">
    <c:LightningDatatableExample/>
</aura:application>

 

Lightning Datatable example Output

Lightning Datatable example salesforce output

Lightning Datatable example salesforce output

 

Use the following column properties to customize the behavior and visual aspects of your columns.

PROPERTYTYPEDESCRIPTION
actionsobjectAppends a dropdown menu of actions to a column. You must pass in a list of label-name pairs.
cellAttributesobjectProvides additional customization, such as horizontal alignment or appending an icon to the output. For more information about alignment, see Aligning Data in a Column. For more information about adding icons, see Appending an Icon to Column Data.
editablebooleanSpecifies whether a column supports inline editing. The default is false.
fieldNamestringRequired. The name that binds the columns properties to the associated data. Each columns property must correspond to an item in the data array.
fixedWidthintegerSpecifies the width of a column in pixels and makes the column non-resizable.
iconNamestringThe Lightning Design System name of the icon. Names are written in the format standard:opportunity. The icon is appended to the left of the header label.
initialWidthintegerThe width of the column when it's initialized, which must be within the minColumnWidth and maxColumnWidth values, or within 50px and 1000px if they are not provided.
labelstringRequired. The text label displayed in the column header.
sortablebooleanSpecifies whether the column can be sorted. The default is false.
typestringRequired. The data type to be used for data formatting. For more information, see Formatting with Data Types.
typeAttributesobjectProvides custom formatting with component attributes for the data type. For example, currencyCode for the currency type. For more information, see Formatting with Data Types.

For more details please refer below official link lightning datatable

Happy Coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/lightning-datatable-example-salesforce/

Difference between WhoId and WhatId

Difference between WhoId and WhatId

What is difference between WhoId and WhatId?

Difference between WhoId and WhatId

  • WhoID in Salesforce refers to people things. So that would be typically a Lead ID or a Contact ID. The WhoId represents a human such as a lead or a contact. WhoIds are polymorphic. Polymorphic means a WhoId is equivalent to a contact’s ID or a lead’s ID. The label is Name.

 

  • WhatID in Salesforce refers to object type things.  That would typically be an Account ID or an Opportunity ID. The WhatId represents nonhuman objects such as accounts, opportunities, campaigns, cases, or custom objects. WhatIds are polymorphic. Polymorphic means a WhatId is equivalent to the ID of a related object. The label is Related To.

 

Please check below image for the object diagram:

Difference between WhoId and WhatId

Difference between WhoId and WhatId

 

These fields are available on Task and Event Object. In SOQL query these fields can simply be queries similar to other fields.

For more details refer to below link https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_erd_activities.htm

Happy Coding:)

 

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/difference-between-whoid-and-whatid/

Use Lightning Components in Visualforce Pages

Use Lightning Components in Visualforce Pages

Use Lightning Components in Visualforce Pages

How To Display Lightning Component In Visualforce Page

In this post, we will see how we can use Lightning Components in Visualforce Pages or how to display Lightning Component In Visualforce Page. Even though the use of lightning is growing day by day, still some customers are using salesforce classic because of many reasons. Sometimes there is a requirement to use lightning component in visualforce page.

Lightning Components for Visualforce is based on Lightning Out, a powerful and flexible feature that lets you embed Lightning components into almost any web page. When used with Visualforce, some of the details become simpler. For example, you don’t need to deal with authentication, and you don’t need to configure a Connected App.

In this example, we will see a very basic example of the lightning component and then display lightning component in the visualforce page.

Lightning Component LightExample1

<aura:component>
    <div>
        <h1> This is lightning component for visualforce page</h1>
    </div>
</aura:component>

Lightning App LightExampleApp1

Here important point is that ltng:outApp needs to be extended in app.

ltng:outApp adds SLDS resources to the page to allow our Lightning components to be styled with the Salesforce Lightning Design System. If we don’t want SLDS resources added to the page, we need to extend from ltng:outAppUnstyled instead.

<aura:application extends="ltng:outApp" access="GLOBAL">
    <aura:dependency resource="c:LightExample1" />
</aura:application>

Visualforce page LightningExampleVF1

<apex:page showHeader="false" sidebar="false">
    <apex:includeLightning />    
    <apex:includeScript value="/lightning/lightning.out.js" />
    <div id="LightningComponentid" />    
    <script>
    $Lightning.use("c:LightExampleApp1", function() {
        $Lightning.createComponent("c:LightExample1",
          { 
          },
          "LightningComponentid",
          function(cmp) {
             console.log('Display Lightning component in visualforce page');
          });
    });
    </script>
</apex:page>

Use Lightning Components in Visualforce Pages output

Use Lightning Components in Visualforce Pages output

Use Lightning Components in Visualforce Pages output

 

In the above Visualforce page, apex:includeLightning tag imports necessary dependencies and scripts to enable Visualforce to act as Lightning component container.

We can use $Lightning.use() method in JavaScript to refer to Lightning Application which extends ltng:outApp.

We can use $Lightning.createComponent create Lightning Component dynamically.

We can call $Lightning.use() multiple times on a page, but all calls must reference the same Lightning dependency app.

Other Useful links:

We can also pass parameters from visualforce page to lightning component. Check wrapper class in lightning component salesforce link.

For more details please refer the official documentation link

Please check Salesforce lightning link for more posts related to lightning.

Permanent link to this article: http://www.sfdcpoint.com/salesforce/use-lightning-components-in-visualforce-pages/

wrapper class in lightning component salesforce

wrapper class in lightning component salesforce

wrapper class in lightning component salesforce

A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members. In this post we will see how we can use wrapper class in lightning component to display data in lightning component. For details about how we can use wrapper class in visualforce page  check wrapper class in Apex

Let’s see an example of wrapper class in lightning component salesforce. In this example, we will create AcoountContactWrapper and will display account and contact details and display on lightning component.

Apex class controller with the wrapper class

AccountContactController.cls

public class AccountContactController{
    
    @AuraEnabled
    public static AccountContactListWrapper getAccountWithContacts(String accountId){
        AccountContactListWrapper accWrapper = new AccountContactListWrapper();
        List<Account> accList = [SELECT Id, Name, BillingState, Website, Phone,
                                    (SELECT Id, FirstName, LastName, Email From Contacts)
                                    FROM Account WHERE Id =: accountId];
        if(!accList.isEmpty()){
            accWrapper.accRecord = accList[0];
            accWrapper.contactList = accList[0].Contacts;
            accWrapper.contactCount = accList[0].Contacts.size();
        }
        return accWrapper;
    }
    
    // wrapper class with @AuraEnabled and {get;set;} properties 
    public class AccountContactListWrapper{
        @AuraEnabled 
        public Account accRecord{get;set;}
        @AuraEnabled 
        public List<Contact> contactList{get;set;}
        @AuraEnabled 
        public Integer contactCount{get;set;}
    }
}

Lightning component AccountContactWrapperExample

<aura:component controller="AccountContactController" implements="force:hasRecordId">  
    <aura:handler name="init" value="{!this}" action="{!c.initData}"/>
    <!-- Attributes declaration-->  
    <aura:attribute name="accountContactWrapper" type="object"/>
    <aura:attribute name="recordId" type="Id" />
    
    <div class="slds-p-around--large">
        <h1 style="font-size:25px;">{!v.accountContactWrapper.accRecord.Name}</h1> 
        <br/>
        <p style="color:red">Total Contacts = {!v.accountContactWrapper.contactCount}</p>
        
    <table class="slds-table slds-table--bordered slds-table--cell-buffer">
        <thead>
            <tr class="slds-text-title--caps">
                <th scope="col">
                    <div class="slds-truncate" title="First Name">First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="First Name">Last Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Email">Email</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <aura:iteration items="{!v.accountContactWrapper.contactList }" var="con">
                <tr>
                    <th scope="row">
                        <div class="slds-truncate" title="{!con.FirstName}">{!con.FirstName}</div>
                    </th>
                    <th scope="row">
                        <div class="slds-truncate" title="{!con.LastName}">{!con.LastName}</div>
                    </th>
                    <th scope="row">
                        <div class="slds-truncate" title="{!con.Email}">{!con.Email}</div>
                    </th>
                </tr>
            </aura:iteration>
        </tbody>
    </table>
  </div>
</aura:component>

Javascript controller for lightning component AccountContactWrapperExample

({
    initData: function(component, event, helper) {
        console.log('***In controller');
        helper.getAccountContactWrapperhelper(component, event, helper);
    },
})

Helper for lightning component AccountContactWrapperExample

({
    getAccountContactWrapperhelper: function(component, event, helper) {
      console.log('***In helper');
      var a= component.get("v.recordId");
      console.log('***In helper'+a);
      //call apex class method
      var action = component.get('c.getAccountWithContacts');
        action.setParams({
            accountId : component.get("v.recordId")
        });
      action.setCallback(this, function(response) {
        //store state of response
        var state = response.getState();
        if (state === "SUCCESS") {
          //set response value in wrapperList attribute on component.
          component.set('v.accountContactWrapper', response.getReturnValue());
        }
      });
      $A.enqueueAction(action);
    },
})

Lightning App AccountContactWrapperExampleApp

<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="c:AccountContactWrapperExample"/>
</aura:application>

Visualforce page AccountContactWrapperExampleVF

<apex:page showHeader="false">
    <apex:includeLightning />    
    <apex:includeScript value="/lightning/lightning.out.js" />
    
    <div id="accountContactWrapperId" >
    </div>
    
    <script>
    $Lightning.use("c:AccountContactWrapperExampleApp", function() {
        $Lightning.createComponent("c:AccountContactWrapperExample",{ 
        recordId :"{!$CurrentPage.Parameters.id}"
        },
        "accountContactWrapperId",
        function(cmp) {
        console.log('Display Lightning component in visualforce page');
        });
    });
    </script>

</apex:page>

Testing visualforce page by passing record id in parameter. In my case URL is:

https://pointnew-dev-ed–c.visualforce.com/apex/AccountContactWrapperExampleVF?Id=0011t000008gSnI

Output will be like this:

wrapper class in lightning component salesforce output

wrapper class in lightning component salesforce output

 

Important: Previously it was possible to use inner wrapper class attribute like this:

<aura:attribute name="accountContactWrapper" type="AccountContactController.AccountContactListWrapper"/>

Problem is Lightning components can’t use inner classes as attribute type when the org has setup a namespace. For more details refer below known issue link.

https://success.salesforce.com/issues_view?id=a1p3A0000001CBeQAM

But now it does not work and we have to use Object as type.

<aura:attribute name="accountContactWrapper" type="object"/>

Happy Coding:)

Permanent link to this article: http://www.sfdcpoint.com/salesforce/wrapper-class-in-lightning-component-salesforce/

Salesforce Integration Interview questions and answers

Salesforce Integration Interview questions and answers

In this post I am going to share Salesforce Integration Interview questions and answers

Salesforce Integration Interview questions and answers

What is Integration?

Integration is a process of connecting two applications. A typical enterprise uses many applications, many or most of which are not designed to work with one another out of the box. Integrating separate but related apps helps organizations achieve greater levels of operational consistency, efficiency, and quality. Each application can have data, business logic, presentation, and security layers, all of which are possible targets for integration. This page is an overall launch point for exploring the various integration options related to Force.com and other Salesforce platform technologies.

What are possible Ways to Integrate with Salesforce Force.com?

  • User Interface Integration: Combine the UIs of two or more apps to create composite apps with little or no rework on the UI of each individual app. One example is using force.com Canvas
  • Business Logic Integration: It uses Apex Web Services for Inbound and Apex Callouts for Outbound. It typically handles a scenario where business logic is spread across several applications to implement the complete end-to-end business process. An example would be building complex logic on the data received before committing it into Salesforce.
  • Data Integration:It uses SOAP APIs and REST APIs. It typically handles data synchronization requirements, where one application in an enterprise acts as the primary source for a particular business object, like Account.

 

What is webservices?

Webservices is a functionality or code which helps to us to do integration. Web services are open standard (XML, SOAP, HTTP, etc.) based web applications that interact with other web applications for the purpose of exchanging data. Web services can convert your existing applications into web applications.

What is Protocal ?

Protocal is a set of mutually accepted and implemented rules at both ends of the communications channel for the proper exchange of information.

How many types of API’s avaliable in salesforce?

  • REST API
  • SOAP API
  • Bulk API
  • Streaming API
  • Metadata API
  • Chatter REST API
  • User Interface API
  • Analytics REST API
  • Apex REST API
  • Apex SOAP API
  • Tooling API

 

When to Use REST API

REST API provides a powerful, convenient, and simple REST-based web services interface for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice of technology for use with mobile applications and web projects. For certain projects, you may want to use REST API with other Salesforce REST APIs. To build UI for creating, reading, updating, and deleting records, including building UI for list views, actions, and dependent picklists, use User Interface API. To build UI for Chatter, communities, or recommendations, use Chatter REST API. If you have many records to process, consider using Bulk API, which is based on REST principles and optimized for large sets of data.

When to Use SOAP API

SOAP API provides a powerful, convenient, and simple SOAP-based web services interface for interacting with Salesforce. You can use SOAP API to create, retrieve, update, or delete records. You can also use SOAP API to perform searches and much more. Use SOAP API in any language that supports web services.

For example, you can use SOAP API to integrate Salesforce with your org’s ERP and finance systems. You can also deliver real-time sales and support information to company portals and populate critical business systems with customer information.

When to Use Chatter REST API

Use Chatter REST API to display Chatter feeds, users, groups, and followers, especially in mobile applications. Chatter REST API also provides programmatic access to files, recommendations, topics, notifications, Data.com purchasing, and more. Chatter REST API is similar to APIs offered by other companies with feeds, such as Facebook and Twitter, but it also exposes Salesforce features beyond Chatter.

Use Chatter REST API to display Chatter feeds, users, groups, and followers, especially in mobile applications. Chatter REST API also provides programmatic access to files, recommendations, topics, notifications, Data.com purchasing, and more. Chatter REST API is similar to APIs offered by other companies with feeds, such as Facebook and Twitter, but it also exposes Salesforce features beyond Chatter.

When to Use Streaming API

Use Streaming API to receive near-real-time streams of data that are based on changes in Salesforce records or custom payloads. For Salesforce record changes, Salesforce publishes notifications when the changes occur. For custom notifications, you can publish event messages. Subscribers can receive notifications using CometD—an implementation of the Bayeux protocol that simulates push technology. Clients can subscribe to some types of events with Apex triggers or declaratively with Process Builder and flows.

When to Use Apex REST API

Use Apex REST API when you want to expose your Apex classes and methods so that external applications can access your code through REST architecture. Apex REST API supports both OAuth 2.0 and Session ID for authorization.

When to Use Apex SOAP API

Use Apex SOAP API when you want to expose Apex methods as SOAP web service APIs so that external applications can access your code through SOAP.

Apex SOAP API supports both OAuth 2.0 and Session ID for authorization.

When to Use Tooling API

Use Tooling API to integrate Salesforce metadata with other systems. Metadata types are exposed as sObjects, so you can access one component of a complex type. This field-level access speeds up operations on complex metadata types. You can also build custom development tools for Force.com applications. For example, use Tooling API to manage and deploy working copies of Apex classes and triggers and Visualforce pages and components. You can also set checkpoints or heap dump markers, execute anonymous Apex, and access logging and code coverage information.

What is Call In and Call Out?

Call In is used to exposing our webservices to another system.
Call out enables you to tightly integrate your Apex with an external service by making a call to an external Web service or sending a HTTP request from Apex code and then receiving the response.

What is WSDL ?

WSDL (Web Services Description Language) is an XML document that describes a web service. WSDL is derived from Microsoft’s Simple Object Access Protocol (SOAP) and IBM’s Network Accessible Service Specification Language (NASSL). WSDL replaces both NASSL and SOAP as the means of expressing business services in the UDDI registry. It is used in combination with SOAP and XML Schema to provide web services over the Internet. A client program connecting to a web service can read the WSDL to determine what functions are available on the server. Any special datatypes used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL. There are two types of WSDL in  Salesforce:

  • Enterprise WSDL
  • Partner WSDL

What is difference between Enterprise WSDL and Partner WSDL?

Enterprise WSDL

  • The Enterprise WSDL is strongly typed.
  • The Enterprise WSDL is tied (bound) to a specific configuration of Salesforce (ie. a specific organization’s Salesforce configuration).
  • The Enterprise WSDL changes if modifications (e.g custom fields or custom objects) are made to an organization’s Salesforce configuration.

Partner WSDL

  • The Partner WSDL is loosely typed.
  • The Partner WSDL can be used to reflect against/interrogate any configuration of Salesforce (ie. any organization’s Salesforce configuration).
  • The Partner WSDL is static, and hence does not change if modifications are made to an organization’s Salesforce configuration.

How SOAP can be accessed ?

SOAP can be communicate through WSDL file, without WSDL file we can’t do integration.
Message format in SOAP is XML

How to generate WSDL file?

  • Go to Setup -> Develop  -> apex classes
  • Click on Apex class
  • Click on Generate WSDL button
  • Generate WSDL code from class
  • Save as .wsdl file in your system

 

How to consume external WSDL file

  1. In the application, from Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
  2. Click Generate from WSDL.
  3. Click Browse to navigate to a WSDL document on your local hard drive or network, or type in the full path. This WSDL document is the basis for the Apex class you are creating.
  4. Click Parse WSDL to verify the WSDL document contents. The application generates a default class name for each namespace in the WSDL document and reports any errors. Parsing fails if the WSDL contains schema types or constructs that aren’t supported by Apex classes, or if the resulting classes exceed the 1 million character limit on Apex classes. For example, the Salesforce SOAP API WSDL cannot be parsed.
  5. Modify the class names as desired. While you can save more than one WSDL namespace into a single class by using the same class name for each namespace, Apex classes can be no more than 1 million characters total.
  6. Click Generate Apex. The final page of the wizard shows which classes were successfully generated, along with any errors from other classes. The page also provides a link to view successfully generated code.

What is remote site settings ?

Remote site settings is used to authorize the endpoint and allow us to whom integrate(end user)

How manys ways to XML parsing ?

They are two ways of XML parsing
1. XML streams
2. XML DOM

How to read root element in XML DOM ?

getroot element

How to read child element in XML DOM ?

getchild element

How to read all child elements in XML DOM ?

getchild elements

How to read text between tags ?

gettext

How SOAP and REST will Communicate ?

SOAP will communicate through WSDL file.
REST will communicate through HTTP protocol.

What are methods in REST

  • HTTPGET : Retrieve data identified by a URL.
  • HTTPPOST : Create a resource or post data to the server.
  • HTTPDELETE : Delete a resource identified by a URL.
  • HTTPPUT : Create or replace the resource sent in the request body.

 

What is difference between SOAP and REST?

SOAP API: The Simple Object Access Protocol (SOAP) is an attempt to define a standard for creating web service APIs. It is a pattern, a web service architecture, which specifies the basic rules to be considered while designing web service platforms. It typically uses HTTP as a layer 7 protocol, although this is not mandatory.

The SOAP message itself consists of an envelope, inside of which are the SOAP headers and body, the actual information we want to send. It is based on the standard XML format, designed especially to transport and store structured data. SOAP may also refer to the format of the XML that the envelope uses. SOAP is a mature standard and is heavily used in many systems, but it does not use many of the functionality build in HTTP. While some consider it slow, it provides a heavy set of functionality which is a necessity in many cases. It might now be the best solution for browser-based clients, due to its custom format.

  • Supports data in the form of XML only and not JSON.
  • Requires WSDL for the integration
  • Use SOAP API in any language that supports Web services.

 

REST API: The Representational State Transfer (REST) is another architectural pattern (resource-oriented), an alternative to SOAP. Unlike SOAP, RESTful applications use the HTTP build-in headers (with a variety of media-types) to carry meta information and use the GET, POST, PUT and DELETE verbs to perform CRUD operations. REST is resource-oriented and uses clean URLs (or RESTful URLs).

  • Supports both XML and JSON format
  • Preferred for mobile and web apps since JSON being Lighter the app runs smoother and faster

What is JSON ?

JSON stands for JavaScript Object Notation. JSON is light weighted than XML.  When exchanging data between a browser and a server, the data can only be text. JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.

 

Other Useful links for Salesforce Integration interview questions and answers

https://developer.salesforce.com/page/Integration

Apex Integration Services Trailhead

Other posts related to salesforce interview questions

Salesforce Lightning interview Questions

Salesforce Certified Integration Architecture Designer Exam

I will keep adding more questions to Salesforce Integration Interview questions and answers.

Please add your comments or questions to Salesforce Integration Interview questions and answers.

 

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-integration-interview-questions-and-answers/

salesforce email service

salesforce email service

Salesforce Email service is automated process that use Apex class to process inbound email. When we set up an email service, we need to generate a special email address in which salesforce will receive your emails. We also need to create one apex class to implement Messaging.InboundEmailHandler interface . The email services will then invoke a handleInboundEmail method on the Apex class whenever an email is received on the email address.

salesforce email service example

Lets create very simple email service which will create contact when an email is sent to salesforce.

Steps to create email service

  1. First of all we need to create Apex class that implement the Messaging.InboundEmailHandler interface. Its necessary to implement Messaging.InboundEmailHandler interface. Using the handleInboundEmail method in that class, you can access an InboundEmail object to retrieve the contents, headers, and attachments of inbound email messages, as well as perform many functions. This class will handle email message.
    global class CreateContactFrmEmail implements Messaging.InboundEmailHandler {
        global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email,
                                                        Messaging.InboundEnvelope envelope) {
            Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
            String subToCompare = 'Create Contact';
            List<Attachment> attachmentList = new List<Attachment>();
            if(email.subject.equalsIgnoreCase(subToCompare)) {
                Contact c = new Contact();
                c.LastName = email.plainTextBody;
                insert c;
                
                // Save attachments, if any
                if(email.textAttachments!=null) {
                    for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
                        Attachment attachment = new Attachment();
                        attachment.Name = tAttachment.fileName;
                        attachment.Body = Blob.valueOf(tAttachment.body);
                        attachment.ParentId = c.Id;
                        attachmentList.add(attachment);
                    }
                }
    
                //Save any Binary Attachment
                if(email.binaryAttachments!=null){
                    for (Messaging.Inboundemail.BinaryAttachment bAttachment : email.binaryAttachments) {
                        Attachment attachment = new Attachment();
                        attachment.Name = bAttachment.fileName;
                        attachment.Body = bAttachment.body;
                        attachment.ParentId = c.Id;
                        attachmentList.add(attachment);
                    }
                }
    
                if(!attachmentList.isEmpty()){
                    insert attachmentList;
                }
            }
            result.success = true;
            return result;
        }
    }
    

     

  2. Create email service:
    Go to setup -> Email Service -> New Email Service. Add following details as per this imagesalesforce email service

    Click on Save or Save and New email address.

  3. Generate an email address from email service record
    Create new email address and add all details as per this image:salesforce email service email address

     

    Click on save. New email address will be created in related list. We need to send email to generated email address to test email service. You can copy email address from email service related list so that we can use it for testing.

  4. Testing email service by sending email:
    For testing send an email to this email id with subject ‘Create Contact’ and add some body which will be saved in last name. We can also add attachment(its optional) in email. As contact last name is required field on contact object, so it is necessary to enter text body in email.

For more details about email service please this link from salesforce.

Happy coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/salesforce-email-service/

System.NullPointerException: Attempt to de-reference a null object

System.NullPointerException: Attempt to de-reference a null object

How to solve System.NullPointerException: Attempt to de-reference a null object error

System.NullPointerException: Attempt to de-reference a null object is very common error in apex class.  It occurs when your variable (sobject, list, set or any other data type) is not initialized (allocated memory). In order to use the non primitive data type in the code we need to initialize the memory first. If we don’t do that it may result in Attempt to de-reference a null object error. This error may occur in Apex classes, Visualforce pages with Apex controller, Test classes, Apex Triggers.

For Example if I use like this:

Account acc;
acc.Name = 'sfdcpoint';

It will result in attempt to de-reference a null object error.

We should use it like this:

Account acc = new Account();
acc.Name = 'sfdcpoint';

When we use list or set then also we need to allocate memory to list or set like this

List<Account> accList = new List<Account>();
Set<String> strSet= new Set<String>();

Same way this error can occur when we get null result from map and we try to use it in our code. For example we have accountMap with Id as key and Account as value:

Account accRecord = accountIdAccountMap.get(accId);
System.debug('*****accRecord.Name'+accRecord.Name);

Above code will also result in error. Here in above code accountIdAccountMap or  accRecord can be null. So we should do null check before using it like this.

if(accountIdAccountMap != null){
    Account accRecord = accountIdAccountMap.get(accId);
    if(accRecord != null){
        System.debug('*****accRecord.Name'+accRecord.Name);
    }
}

It is also very good practice to use isEmpty() method like this:

if(!accList.isEmpty()){
     //Do your dml or other operations here
}

As a best practice we should always do exception handling in our code like this

try{
    //Code here
}catch(Exception e){
    //Handle exception here
}

If you get System.NullPointerException. Its advisable to use System.debug to debug line of code which is resulting in this error and then fix it.

Happy coding 🙂

Permanent link to this article: http://www.sfdcpoint.com/salesforce/system-nullpointerexception-attempt-to-de-reference-a-null-object/