When you enter text into the form and press Submit, you want to create a new expense record and save it in the model. This
action is wired up to the button component via the press attribute.
Create ExpenseController.apxc
First, create an Apex controller that saves or updates the records and then add the logic to update the counters dynamically.
- Click File > New > Apex Class.
- Enter
ExpenseController
in the New Class window. This creates a new Apex class,ExpenseController.apxc
. - In
ExpenseController.apxc
, enter this code.
Replace namespace with the name of your registered namespace.
The custom controller enables you to insert or update an expense record.
Update form.cmp
In form.cmp, add the controller attribute to the aura:component tag.
Replace namespace with the name of your registered namespace.<aura:component model="namespace.ExpenseModel" controller="namespace.ExpenseController">
Create newExpense JS Controller
Create the controller-side actions to create a new expense record when the Submit button is pressed. In formController.js, add this code after the doInit action.
Note: Add a coma “,” after doInit
if it’s missing.
Code Highlights
newExpense
validates the amount field using the default error handling, which appends the error message to the field.- Notice that you’re passing in the arguments to a helper function
createExpense
, which then triggers the Apex classsaveExpense
. - A helper function is a resource for storing code that you want to reuse in your component bundle.
Create createExpense Helper
Create the helper function to handle the record creation and dynamically update the counters.
- Click HELPER to create a new resource,
formHelper.js
- Enter this code.
Code Highlights
component.get("c.saveExpense");
createExpense defines an instance of the saveExpense server-side action and sets the expense object as a parameter.action.setCallback(this, function(a) {
The callback is executed after the server-side action returns, which updates the model, view, and counters.$A.enqueueAction(action)
Adds the server-side action to the queue of actions to be executed.
In updateTotal, you are retrieving the actual data in the value object, e
, using e.unwrap().amount
.
Update doInit Controller
In formController.js, update the doInit
function to update the counters on initialization.
Test The App
- Save your changes and reload your browser.
- Test your form by entering Breakfast, 10, ABC Co., Breakfast, Apr 30, 2014 9:00:00 AM.
- Click the Submit button. Notice that the record is added to both your view and model, and the counters are updated.