Newer Version Available
Creating a Form
If you’re creating a form to work with Salesforce data, use the lightning:recordForm, lightning:recordEditForm, lightning:recordViewForm, or force:recordData base components as they are built on Lightning Data Service. Otherwise, you must wire up the fields to the Salesforce object yourself and use Apex to process the user input as shown in the next section.
Example
Implement a Basic Form
Before proceeding, we recommend that you have working knowledge of web forms, as the rest of the topic builds on that concept.
You can collect data in fields that accept different types of user input, such as a checkbox, date, email, file, password, number, phone, radio, or text. Most user input can be collected by using lightning:input.
Here’s a list of form controls for option selection and their corresponding base components.
- Button: lightning:button (and lightning:buttonIcon and so on)
- Checkbox: lightning:checkboxGroup
- Dropdown menu for single selection: lightning:combobox
- Dropdown menu for single selection using the HTML <select>: lightning:select
- Dual listbox for multiple selection: lightning:dualListbox
- Radio button: lightning:radioGroup
Here’s a list of form controls for entering an input value and their corresponding base components.
- Input field: lightning:input
- Address compound field: lightning:inputAddress
- Geolocation compound field: lightning:inputLocation
- Name compound field: lightning:inputName
- Rich text field: lightning:inputRichText
- Input range for number selection: lightning:slider
- Text input (multi-line): lightning:textarea
When you use the base components, the <label> and <input> elements are automatically configured for you. For form styling, you get the Salesforce Lightning Design System (SLDS) styling. You can also use SLDS utility classes to customize the layout of your form.
Let’s say we want a form that collects a contact’s name, email address, and comments.
In this example, we are using lightning:inputName, lightning:input, and lightning:textarea in a standalone app. To create a grid layout for the fields, use lightning:layout.
The client-side controller submits the user data to the Apex controller and updates the v.message attribute when the contact is created successfully.
The Apex controller uses the upsert DML operation to create a contact record.
Notice that the form allows you to submit empty fields without any user interaction. The field-level errors for required fields that you leave empty are displayed only after you interact with the fields. Also, if you enter an invalid email format, the email field displays an error.
Customize the submission behavior to prevent invalid fields from getting submitted. For more information, see Validating Fields.