Newer Version Available

This content describes an older version of this product. View Latest

Creating a Form

Work with user input for server-side use, such as creating or updating a record. Or get user input to update the user interface, such as displaying or hiding components.

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

The Aura Components Basics Trailhead module walks you through building a form for creating an expense record.

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.

Here’s a list of form controls for entering an input value and their corresponding base components.

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.

1<aura:application access="GLOBAL" extends="force:slds" controller="ContactController"> 
2    <aura:attribute name="salutationOptions" type="List" default="[
3        {'label': 'Mr.', 'value': 'Mr.'},
4        {'label': 'Ms.', 'value': 'Ms.'},
5        {'label': 'Mrs.', 'value': 'Mrs.'},
6        {'label': 'Dr.', 'value': 'Dr.'},
7        {'label': 'Prof.', 'value': 'Prof.'},
8    ]"/>
9    <aura:attribute name="newContact" type="Contact"
10        default="{ 'sobjectType': 'Contact',
11                   'Title': '',
12                   'FirstName': '',
13                   'LastName': '',
14                   'Email': '',
15                   'Description': '' }" />
16    <aura:attribute name="message" type="String" default=""/>
17    
18    <lightning:card iconName="standard:contact" title="Add a Contact">
19        <div class="slds-p-around_medium">
20            <lightning:layout>
21                <lightning:layoutItem size="4" padding="around-small">
22                    <lightning:inputName aura:id="contact"
23                                         label="Contact Name"
24                                         firstName="{!v.newContact.FirstName}"
25                                         lastName="{!v.newContact.LastName}"
26                                         salutation="{!v.newContact.Title}"
27                                         options="{!v.salutationOptions}"
28                                         required="true"/>
29                </lightning:layoutItem> 
30                <lightning:layoutItem size="8" padding="around-small">
31                    <lightning:input aura:id="contact" label="Email" type="email" value="{!v.newContact.Email}"/>
32                    <lightning:textarea aura:id="contact" label="Comments" value="{!v.newContact.Description}"/>
33                    <lightning:button label="Create Contact" onclick="{!c.handleCreateContact}" variant="brand" class="slds-m-top_medium"/>
34                </lightning:layoutItem>
35            </lightning:layout>
36            <p>{!v.message}</p>
37        </div>
38    </lightning:card>
39</aura:application>

The client-side controller submits the user data to the Apex controller and updates the v.message attribute when the contact is created successfully.

1({
2    handleCreateContact: function(component, event) {
3        var saveContactAction = component.get("c.createContact");
4            saveContactAction.setParams({
5                "contact": component.get("v.newContact")
6            });
7        
8        // Configure the response handler for the action
9        saveContactAction.setCallback(this, function(response) {
10            var state = response.getState();
11            if(state === "SUCCESS") {
12                component.set("v.message", "Contact created successfully");
13            }
14            else if (state === "ERROR") {
15                console.log('Problem saving contact, response state: ' + state);
16            }
17            else {
18                console.log('Unknown problem, response state: ' + state);
19            }
20        });
21
22        // Send the request to create the new contact
23        $A.enqueueAction(saveContactAction);
24    },
25})

The Apex controller uses the upsert DML operation to create a contact record.

1public with sharing class ContactController {
2    
3    @AuraEnabled
4    public static Contact createContact(Contact contact){
5        upsert contact;
6        return contact;
7    }
8}

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.