Lightning Components Developer Guide: Version 42.0, Spring '18
Lightning Components Developer Guide: Version 42.0, Spring '18
Lightning Components Developer Guide: Version 42.0, Spring '18
Developer Guide
Version 42.0, Spring ’18
@salesforcedocs
Last updated: March 23, 2018
© Copyright 2000–2018 salesforce.com, inc. All rights reserved. Salesforce is a registered trademark of salesforce.com, inc.,
as are other names and marks. Other marks appearing herein may be trademarks of their respective owners.
CONTENTS
force:recordPreview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
force:recordView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
forceChatter:feed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
forceChatter:fullFeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
forceChatter:publisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
forceCommunity:appLauncher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
forceCommunity:navigationMenuBase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
forceCommunity:notifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
forceCommunity:routeLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
forceCommunity:waveDashboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
lightning:accordion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
lightning:accordionSection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
lightning:avatar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
lightning:badge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
lightning:breadcrumb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
lightning:breadcrumbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
lightning:button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
lightning:buttonGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
lightning:buttonIcon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
lightning:buttonIconStateful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
lightning:buttonMenu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
lightning:buttonStateful . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
lightning:card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
lightning:carousel (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
lightning:checkboxGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
lightning:clickToDial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
lightning:combobox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
lightning:container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
lightning:datatable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
lightning:dualListbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
lightning:dynamicIcon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
lightning:fileCard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
lightning:fileUpload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
lightning:flexipageRegionInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
lightning:flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
lightning:formattedAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
lightning:formattedDateTime (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
lightning:formattedEmail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
lightning:formattedLocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
lightning:formattedName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
lightning:formattedNumber (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
lightning:formattedPhone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
lightning:formattedRichText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
lightning:formattedText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
Contents
lightning:formattedTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
lightning:formattedUrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
lightning:helptext . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
lightning:icon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
lightning:input (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
lightning:inputAddress . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
lightning:inputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
lightning:inputLocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
lightning:inputName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
lightning:inputRichText (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
lightning:layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
lightning:layoutItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
lightning:listView . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
lightning:menuItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
lightning:omniToolkitAPI (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
lightning:outputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
lightning:path (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
lightning:picklistPath (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
lightning:pill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
lightning:pillContainer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
lightning:progressBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
lightning:progressIndicator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
lightning:radioGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
lightning:recordEditForm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
lightning:recordViewForm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
lightning:relativeDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
lightning:select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
lightning:slider . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
lightning:spinner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
lightning:tab (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
lightning:tabset (Beta) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
lightning:textarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
lightning:tile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
lightning:tree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
lightning:treeGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
lightning:utilityBarAPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
lightning:verticalNavigation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
lightning:verticalNavigationItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
lightning:verticalNavigationItemBadge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
lightning:verticalNavigationItemIcon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
lightning:verticalNavigationOverflow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
lightning:verticalNavigationSection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
lightning:workspaceAPI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
ltng:require . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
Contents
ui:actionMenuItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
ui:button . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
ui:checkboxMenuItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
ui:inputCheckbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
ui:inputCurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
ui:inputDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
ui:inputDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
ui:inputDefaultError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
ui:inputEmail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
ui:inputNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
ui:inputPhone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 610
ui:inputRadio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
ui:inputRichText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
ui:inputSecret . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
ui:inputSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
ui:inputSelectOption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
ui:inputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
ui:inputTextArea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
ui:inputURL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
ui:menu . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
ui:menuItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
ui:menuItemSeparator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
ui:menuList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
ui:menuTrigger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
ui:menuTriggerLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 640
ui:message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
ui:outputCheckbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 642
ui:outputCurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
ui:outputDate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
ui:outputDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
ui:outputEmail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
ui:outputNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
ui:outputPhone . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
ui:outputRichText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
ui:outputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654
ui:outputTextArea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
ui:outputURL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
ui:radioMenuItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
ui:scrollerWrapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
ui:spinner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
wave:waveDashboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Messaging Component Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
lightning:notificationsLibrary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
lightning:overlayLibrary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
Contents
aura:doneWaiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
aura:locationChange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
aura:systemError . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
aura:valueChange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
aura:valueDestroy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704
aura:valueInit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
aura:valueRender . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
aura:waiting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
Supported HTML Tags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
Anchor Tag: <a> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708
INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
CHAPTER 1 What is the Lightning Component Framework?
In this chapter ... The Lightning Component framework is a UI framework for developing dynamic web apps for mobile
and desktop devices. It’s a modern framework for building single-page applications engineered for
• What is Salesforce growth.
Lightning?
The framework supports partitioned multi-tier component development that bridges the client and
• Why Use the
server. It uses JavaScript on the client side and Apex on the server side.
Lightning Component
Framework?
• Components
• Events
• Open Source Aura
Framework
• Browser Support
Considerations for
Lightning
Components
• Using the Developer
Console
• Online Content
1
What is the Lightning Component Framework? What is Salesforce Lightning?
2
What is the Lightning Component Framework? Components
Components
Components are the self-contained and reusable units of an app. They represent a reusable section of the UI, and can range in granularity
from a single line of text to an entire app.
The framework includes a set of prebuilt components. For example, components that come with the Lightning Design System styling
are available in the lightning namespace. These components are also known as the base Lightning components. You can assemble
and configure components to form new components in an app. Components are rendered to produce HTML DOM elements within the
browser.
A component can contain other components, as well as HTML, CSS, JavaScript, or any other Web-enabled code. This enables you to
build apps with sophisticated UIs.
The details of a component's implementation are encapsulated. This allows the consumer of a component to focus on building their
app, while the component author can innovate and make changes without breaking consumers. You configure components by setting
the named attributes that they expose in their definition. Components interact with their environment by listening to or publishing
events.
SEE ALSO:
Creating Components
Component Reference
Working with Base Lightning Components
Events
Event-driven programming is used in many languages and frameworks, such as JavaScript and Java Swing. The idea is that you write
handlers that respond to interface events as they occur.
A component registers that it may fire an event in its markup. Events are fired from JavaScript controller actions that are typically triggered
by a user interacting with the user interface.
There are two types of events in the framework:
• Component events are handled by the component itself or a component that instantiates or contains the component.
• Application events are handled by all components that are listening to the event. These events are essentially a traditional
publish-subscribe model.
You write the handlers in JavaScript controller actions.
SEE ALSO:
Communicating with Events
Handling Events with Client-Side Controllers
3
What is the Lightning Component Framework? Open Source Aura Framework
Lightning Experience is
Lightning Experience and Lightning-Based Features available in: Group,
The following table describes minimum browser version requirements for using Lightning Professional, Enterprise,
components within various features that are built with our next-generation user interface platform. Performance, Unlimited,
and Developer Editions
Microsoft® Microsoft® Google Mozilla® Apple®
Internet Edge Chrome™ Firefox® Safari®
Explorer®
Lightning IE 11 (EOL Windows 10 Latest Latest 10.x+
Experience December 21,
2020)1
4
What is the Lightning Component Framework? Browser Support Considerations for Lightning Components
1
LockerService is disabled for IE11. We recommend using supported browsers other than IE11 for enhanced security.
Important: Support for Internet Explorer 11 to access Lightning Experience is retiring beginning in Summer ’16.
• You can continue to use IE11 to access Lightning Experience until December 16, 2017.
• If you opt in to Extended Support for IE11, you can continue to use IE11 to access Lightning Experience and Communities until
December 31, 2020.
• IE11 has significant performance issues in Lightning Experience.
• This change doesn’t impact Salesforce Classic.
Note: The term “latest version” is defined by the browser vendors. Use the support for your browser(s) to understand what “latest
version” means.
SEE ALSO:
Salesforce Help: Supported Browsers
Salesforce Help: Recommendations and Requirements for All Browsers
LockerService Disabled for Unsupported Browsers
Content Security Policy Overview
5
What is the Lightning Component Framework? Using the Developer Console
For more information on the Developer Console, see The Developer Console User Interface.
SEE ALSO:
Salesforce Help: Open the Developer Console
Create Lightning Components in the Developer Console
Component Bundles
Online Content
This guide is available online. To view the latest version, go to:
6
What is the Lightning Component Framework? Online Content
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/
Go beyond this guide with exciting Trailhead content. To explore more of what you can do with Lightning Components, go to:
Trailhead Module: Lightning Components Basics
Link: https://trailhead.salesforce.com/module/lex_dev_lc_basics
Learn with a series of hands-on challenges on how to use Lightning Components to build modern web apps.
Quick Start: Lightning Components
Link: https://trailhead.salesforce.com/project/quickstart-lightning-components
Create your first component that renders a list of Contacts from your org.
Project: Build an Account Geolocation App
Link: https://trailhead.salesforce.com/project/account-geolocation-app
Build an app that maps your Accounts using Lightning Components.
Project: Build a Restaurant-Locator Lightning Component
Link: https://trailhead.salesforce.com/project/workshop-lightning-restaurant-locator
Build a Lightning component with Yelp’s Search API that displays a list of businesses near a certain location.
Project: Build a Lightning App with the Lightning Design System
Link: https://trailhead.salesforce.com/project/slds-lightning-components-workshop
Design a Lightning component that displays an Account list.
7
CHAPTER 2 Quick Start
In this chapter ... The quick start provides Trailhead resources for you to learn core Lightning components concepts, and
a short tutorial that builds a Lightning component to manage selected contacts in the Salesforce app
• Before You Begin and Lightning Experience. You’ll create all components from the Developer Console. The tutorial uses
• Trailhead: Explore several events to create or edit contact records, and view related cases.
Lightning
Components
Resources
• Create a Component
for Lightning
Experience and the
Salesforce Mobile
App
8
Quick Start Before You Begin
Note: For this quick start tutorial, you don’t need to create a Developer Edition organization or register a namespace prefix. But
you want to do so if you’re planning to offer managed packages. You can create Lightning components using the UI in Enterprise,
Performance, Unlimited, Developer Editions or a sandbox. If you don’t plan to use a Developer Edition organization, you can
go directly to Define a Custom Salesforce Domain Name.
9
Quick Start Create a Component for Lightning Experience and the
Salesforce Mobile App
10
Quick Start Create a Component for Lightning Experience and the
Salesforce Mobile App
Here’s how the component looks like in the Salesforce app. You’re creating two components, contactList and contacts, where
contactList is a container component that iterates over and displays contacts components. All contacts are displayed in
contactList, but you can select different lead sources to view a subset of contacts associated with the lead source.
11
Quick Start Create a Component for Lightning Experience and the
Salesforce Mobile App
Resource Description
Contacts Bundle
contactsController.js The client-side controller action that navigates to a contact record using the
force:navigateToSObject event
contactList Bundle
contactListController.js The client-side controller actions that call the helper resource to load contact data and handles the lead
source selection
12
Quick Start Load the Contacts
Resource Description
contactListHelper.js The helper function that retrieves contact data, displays a toast message on successful loading of contact
data, displays contact data based on lead source, and update the total number of contacts
Apex Controller
ContactController.apxc The Apex controller that queries all contact records and those records based on different lead sources
ContactController contains methods that return your contact data using SOQL statements. This Apex controller is wired
up to your component in a later step. getContacts() returns all contacts with the selected fields.
2. Click File > New > Lightning Component, and then enter contacts for the Name field in the New Lightning Bundle popup
window. This creates a component, contacts.cmp. Enter this code and then save.
<aura:component>
<aura:attribute name="contact" type="Contact" />
13
Quick Start Load the Contacts
</lightning:card>
</aura:component>
This component creates the template for your contact data using the lightning:card component, which simply creates a
visual container around a group of information. This template gets rendered for every contact that you have, so you have multiple
instances of a component in your view with different data. The onclick event handler on the lightning:button component
calls the goToRecord client-side controller action when the buton is clicked. Notice the expression {!v.contact.Name}?
v represents the view, which is the set of component attributes, and contact is the attribute of type Contact. Using this dot
notation, you can access the fields in the contact object, like Name and Email, after you wire up the Apex controller to the
component in the next step.
3. Click File > New > Lightning Component, and then enter contactList for the Name field in the New Lightning Bundle
popup window, which creates the contactList.cmp component. Enter this code and then save. If you’re using a namespace
in your organization, replace ContactController with myNamespace.ContactController. You wire up the Apex
controller to the component by using the controller="ContactController" syntax.
<aura:component implements="force:appHostable" controller="ContactController">
<!-- Handle component initialization in a client-side controller -->
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<!-- Page header with a counter that displays total number of contacts -->
<div class="slds-page-header slds-page-header_object-home">
<lightning:layout>
<lightning:layoutItem>
<lightning:icon iconName="standard:contact" />
</lightning:layoutItem>
<lightning:layoutItem class="slds-m-left_small">
<p class="slds-text-title_caps slds-line-height_reset">Contacts</p>
<h1 class="slds-page-header__title slds-p-right_x-small">Contact
Viewer</h1>
</lightning:layoutItem>
</lightning:layout>
<lightning:layout>
<lightning:layoutItem>
<p class="slds-text-body_small">{!v.totalContacts} Contacts • View
Contacts Based on Lead Sources</p>
</lightning:layoutItem>
</lightning:layout>
</div>
14
Quick Start Load the Contacts
<!-- Iterate over the list of contacts and display them -->
<aura:iteration var="contact" items="{!v.contacts}">
<!-- If you’re using a namespace, replace with myNamespace:contacts-->
<c:contacts contact="{!contact}"/>
</aura:iteration>
</lightning:layoutItem>
</lightning:layout>
</aura:component>
Let’s dive into the code. We added the init handler to load the contact data during initialization. The handler calls the client-side
controller code in the next step. We also added two attributes, contacts and totalContacts, which stores the list of contacts
and a counter to display the total number of contacts respectively. Additionally, the contactList component is an attribute
used to store the filtered list of contacts when an option is selected on the lead source dropdown menu. The lightning:layout
components simply create grids to align your content in the view with Lightning Design System CSS classes.
The page header contains the {!v.totalContacts} expression to dynamically display the number of contacts based on the
lead source you select. For example, if you select Referral and there are 30 contacts whose Lead Source fields are set to
Referral, then the expression evaluates to 30.
Next, we create a dropdown menu with the lightning:select component. When you select an option in the dropdown
menu, the onchange event handler calls your client-side controller to update the view with a subset of the contacts. You create
the client-side logic in the next few steps.
In case you’re wondering, the force:appHostable interface enables your component to be surfaced in Lightning Experience
and the Salesforce mobile app as tabs, which we are getting into later.
4. In the contactList sidebar, click CONTROLLER to create a resource named contactListController.js. Replace the
placeholder code with the following code and then save.
({
doInit : function(component, event, helper) {
// Retrieve contacts during component initialization
helper.loadContacts(component);
},
15
Quick Start Load the Contacts
k++;
}
}
else {
filter = contactList;
}
}
//Set the filtered list of contacts based on the selected option
component.set("v.contacts", filter);
helper.updateTotal(component);
}
})
The client-side controller calls helper functions to do most of the heavy-lifting, which is a recommended pattern to promote code
reuse. Helper functions also enable specialization of tasks, such as processing data and firing server-side actions, which is what we
are covering next. Recall that the onchange event handler on the lightning:select component calls the handleSelect
client-side controller action, which is triggered when you select an option in the dropdown menu. handleSelect checks the
option value that’s passed in using event.getSource().get("v.value"). It creates a filtered list of contacts by checking
that the lead source field on each contact matches the selected lead source. Finally, update the view and the total number of contacts
based on the selected lead source.
5. In the contactList sidebar, click HELPER to create a resource named contactListHelper.js. Replace the placeholder code
with the following code and then save.
({
loadContacts : function(cmp) {
// Load all contact data
var action = cmp.get("c.getContacts");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.contacts", response.getReturnValue());
cmp.set("v.contactList", response.getReturnValue());
this.updateTotal(cmp);
}
16
Quick Start Fire the Events
updateTotal: function(cmp) {
var contacts = cmp.get("v.contacts");
cmp.set("v.totalContacts", contacts.length);
}
})
During initialization, the contactList component loads the contact data by:
• Calling the Apex controller method getContacts, which returns the contact data via a SOQL statement
• Setting the return value via cmp.set("v.contacts", response.getReturnValue()) in the action callback,
which updates the view with the contact data
• Updating the total number of contacts in the view, which is evaluated in updateTotal
You must be wondering how your component works in Lightning Experience and the Salesforce app. Let’s find out next!
6. Make the contactList component available via a custom tab in Lightning Experience and the Salesforce app.
• Add Lightning Components as Custom Tabs in Lightning Experience
• Add Lightning Components as Custom Tabs in the Salesforce App
For this tutorial, we recommend that you add the component as a custom tab in Lightning Experience.
When your component is loaded in Lightning Experience or the Salesforce app, a toast message indicates that your contacts are loaded
successfully. Select a lead source from the dropdown menu and watch your contact list and the number of contacts update in the view.
Next, wire up an event that navigates to a contact record when you click a button in the contact list.
The onclick event handler in the following button component triggers the goToRecord client-side controller when the
button is clicked.
<lightning:button name="details" label="Details" onclick="{!c.goToRecord}" />
You set the parameters to pass into the events using the event.setParams() syntax. In this case, you’re passing in the Id of
the contact record to navigate to. There are other events besides force:navigateToSObject that simplify navigation within
17
Quick Start Fire the Events
Lightning Experience and the Salesforce app. For more information, see Events Handled in the Salesforce mobile app and Lightning
Experience.
2. To test the event, refresh your custom tab in Lightning Experience, and click the Details button.
The force:navigateToSObject is fired, which updates the view to display the contact record page.
We stepped through creating a component that loads contact data using a combination of client-side controllers and Apex controller
methods to create a custom UI with your Salesforce data. The possibilities of what you can do with Lightning components are endless.
While we showed you how to surface a component via a tab in Lightning Experience and the Salesforce app, you can take this tutorial
further by surfacing the component on record pages via the Lightning App Builder and even Communities. To explore the possibilities,
blaze the trail with the resources available at Trailhead: Explore Lightning Components Resources.
18
CHAPTER 3 Creating Components
In this chapter ... Components are the functional units of the Lightning Component framework.
A component encapsulates a modular and potentially reusable section of UI, and can range in granularity
• Create Lightning
Components in the
from a single line of text to an entire application.
Developer Console
• Component Markup
• Component
Namespace
• Component Bundles
• Component IDs
• HTML in Components
• CSS in Components
• Component
Attributes
• Component
Composition
• Component Body
• Component Facets
• Best Practices for
Conditional Markup
• Component
Versioning
• Components with
Minimum API Version
Requirements
• Using Expressions
• Using Labels
• Localization
• Providing
Component
Documentation
• Working with Base
Lightning
Components
• Working with UI
Components
19
Creating Components
• Supporting
Accessibility
20
Creating Components Create Lightning Components in the Developer Console
Select Developer Console from the Your Name or the quick access menu ( ).
Example:
21
Creating Components Lightning Bundle Configurations Available in the Developer
Console
IN THIS SECTION:
Lightning Bundle Configurations Available in the Developer Console
Configurations make it easier to create a component or application for a specific purpose, like a Lightning Page or Lightning
Communities Page, or a quick action or navigation item in Lightning Experience or Salesforce mobile app. The New Lightning Bundle
panel in the Developer Console offers a choice of component configurations when you create a Lightning component or application
bundle.
SEE ALSO:
Using the Developer Console
Lightning Bundle Configurations Available in the Developer Console
Using configurations is optional. You can use them in any combination, including all or none.
The following configurations are available in the New Lightning Bundle panel.
22
Creating Components Component Markup
Note: For details of the markup added by each configuration, see the respective documentation for those features.
SEE ALSO:
Create Lightning Components in the Developer Console
Interface Reference
Configure Components for Custom Tabs
Configure Components for Custom Actions
Configure Components for Lightning Pages and the Lightning App Builder
Configure Components for Lightning Experience Record Pages
Configure Components for Communities
Component Markup
Component resources contain markup and have a .cmp suffix. The markup can contain text or references to other components, and
also declares metadata about the component.
Let's start with a simple "Hello, world!" example in a helloWorld.cmp component.
<aura:component>
Hello, world!
</aura:component>
This is about as simple as a component can get. The "Hello, world!" text is wrapped in the <aura:component> tags, which appear
at the beginning and end of every component definition.
23
Creating Components Component Namespace
Components can contain most HTML tags so you can use markup, such as <div> and <span>. HTML5 tags are also supported.
<aura:component>
<div class="container">
<!--Other HTML tags or components here-->
</div>
</aura:component>
Note: Case sensitivity should be respected as your markup interacts with JavaScript, CSS, and Apex.
SEE ALSO:
aura:component
Using the Developer Console
Component Access Control
Create a Custom Renderer
Dynamically Creating Components
Component Namespace
Every component is part of a namespace, which is used to group related components together. If your organization has a namespace
prefix set, use that namespace to access your components. Otherwise, use the default namespace to access your components.
Another component or application can reference a component by adding <myNamespace:myComponent> in its markup. For
example, the helloWorld component is in the docsample namespace. Another component can reference it by adding
<docsample:helloWorld /> in its markup.
Lightning components that Salesforce provides are grouped into several namespaces, such as aura, ui, and force. Components
from third-party managed packages have namespaces from the providing organizations.
In your organization, you can choose to set a namespace prefix. If you do, that namespace is used for all of your Lightning components.
A namespace prefix is required if you plan to offer managed packages on the AppExchange.
If you haven’t set a namespace prefix for your organization, use the default namespace c when referencing components that you’ve
created.
24
Creating Components Using the Default Namespace in Organizations with No
Namespace Set
Note: Support for the c namespace in organizations that have set a namespace prefix is incomplete. The following items can
use the c namespace if you prefer to use the shortcut, but it’s not currently a recommended practice.
• References to components that you’ve created when used in Lightning markup, but not in expressions or JavaScript
• References to events that you’ve defined when used in Lightning markup, but not in expressions or JavaScript
• References to custom objects when used in component and event type and default system attributes, but not in
expressions or JavaScript
See Namespace Usage Examples and Reference on page 26 for examples of the preceding items.
25
Creating Components Creating a Namespace in Your Organization
Note: This button doesn’t appear if you’ve already configured your developer settings.
3. Review the selections that are required for configuring developer settings, and then click Continue.
4. Enter the namespace prefix you want to register.
5. Click Check Availability to determine if the namespace prefix is already in use.
6. If the namespace prefix that you entered isn’t available, repeat the previous two steps.
7. Click Review My Selections.
8. Click Save.
26
Creating Components Namespace Usage Examples and Reference
27
Creating Components Namespace Usage Examples and Reference
28
Creating Components Component Bundles
Component Bundles
A component bundle contains a component or an app and all its related resources.
CSS Styles sample.css Contains styles for the CSS in Components on page 31
component.
SVG File sample.svg Custom icon resource for Configure Components for
components used in the Lightning Pages and the
Lightning App Builder or Lightning App Builder on page
Community Builder. 124
29
Creating Components Component IDs
All resources in the component bundle follow the naming convention and are auto-wired. For example, a controller
<componentName>Controller.js is auto-wired to its component, which means that you can use the controller within the
scope of that component.
Component IDs
A component has two types of IDs: a local ID and a global ID. You can retrieve a component using its local ID in your JavaScript code. A
global ID can be useful to differentiate between multiple instances of a component or for debugging purposes.
Local IDs
A local ID is an ID that is only scoped to the component. A local ID is often unique but it’s not required to be unique.
Create a local ID by using the aura:id attribute. For example:
<lightning:button aura:id="button1" label="button1"/>
Note: aura:id doesn't support expressions. You can only assign literal string values to aura:id.
Find the button component by calling cmp.find("button1") in your client-side controller, where cmp is a reference to the
component containing the button.
find() returns different types depending on the result.
• If the local ID is unique, find() returns the component.
• If there are multiple components with the same local ID, find() returns an array of the components.
• If there is no matching local ID, find() returns undefined.
To find the local ID for a component in JavaScript, use cmp.getLocalId().
Global IDs
Every component has a unique globalId, which is the generated runtime-unique ID of the component instance. A global ID (1) is
not guaranteed to be the same beyond the lifetime of a component, so it should never be relied on. A global ID can be useful to
differentiate between multiple instances of a component or for debugging purposes.
To create a unique ID for an HTML element, you can use the globalId as a prefix or suffix for your element. For example:
<div id="{!globalId + '_footer'}"></div>
30
Creating Components HTML in Components
SEE ALSO:
Finding Components by ID
Which Button Was Pressed?
HTML in Components
An HTML tag is treated as a first-class component by the framework. Each HTML tag is translated into an <aura:html> component,
allowing it to enjoy the same rights and privileges as any other component.
For example, the framework automatically converts a standard HTML <div> tag to this component:
<aura:html tag="div" />
You can add HTML markup in components. Note that you must use strict XHTML. For example, use <br/> instead of <br>. You can
also use HTML attributes and DOM events, such as onclick.
Warning: Some tags, like <applet> and <font>, aren’t supported. For a full list of unsupported tags, see Supported HTML
Tags on page 707.
Unescaping HTML
To output pre-formatted HTML, use aura:unescapedHTML. For example, this is useful if you want to display HTML that is generated
on the server and add it to the DOM. You must escape any HTML if necessary or your app might be exposed to security vulnerabilities.
You can pass in values from an expression, such as in <aura:unescapedHtml value="{!v.note.body}"/>.
{!expression} is the framework's expression syntax. For more information, see Using Expressions on page 42.
SEE ALSO:
Supported HTML Tags
CSS in Components
CSS in Components
Style your components with CSS.
Add CSS to a component bundle by clicking the STYLE button in the Developer Console sidebar.
Note: You can’t add a <style> tag in component markup or when you dynamically create a component in JavaScript code.
This restriction ensures better component encapsulation and prevents component styling interfering with the styling of another
component. The <style> tag restriction applies to components with API version 42.0 or later.
For external CSS resources, see Styling Apps on page 248.
All top-level elements in a component have a special THIS CSS class added to them. This, effectively, adds namespacing to CSS and
helps prevent one component's CSS from overriding another component's styling. The framework throws an error if a CSS file doesn't
follow this convention.
31
Creating Components CSS in Components
<ul>
<li class="red">I'm red.</li>
<li class="blue">I'm blue.</li>
<li class="green">I'm green.</li>
</ul>
</aura:component>
CSS source
.THIS {
background-color: grey;
}
.THIS.white {
background-color: white;
}
.THIS .red {
background-color: red;
}
.THIS .blue {
background-color: blue;
}
.THIS .green {
background-color: green;
}
Output
The top-level elements, h2 and ul, match the THIS class and render with a grey background. Top-level elements are tags wrapped
by the HTML body tag and not by any other tags. In this example, the li tags are not top-level because they are nested in a ul tag.
The <div class="white"> element matches the .THIS.white selector and renders with a white background. Note that
there is no space in the selector as this rule is for top-level elements.
32
Creating Components Component Attributes
The <li class="red"> element matches the .THIS .red selector and renders with a red background. Note that this is a
descendant selector and it contains a space as the <li> element is not a top-level element.
SEE ALSO:
Adding and Removing Styles
HTML in Components
Component Attributes
Component attributes are like member variables on a class in Apex. They are typed fields that are set on a specific instance of a component,
and can be referenced from within the component's markup using an expression syntax. Attributes enable you to make components
more dynamic.
Use the <aura:attribute> tag to add an attribute to the component or app. Let’s look at the following sample,
helloAttributes.app:
<aura:application>
<aura:attribute name="whom" type="String" default="world"/>
Hello {!v.whom}!
</aura:application>
All attributes have a name and a type. Attributes may be marked as required by specifying required="true", and may also specify
a default value.
In this case we've got an attribute named whom of type String. If no value is specified, it defaults to "world".
Though not a strict requirement, <aura:attribute> tags are usually the first things listed in a component’s markup, as it provides
an easy way to read the component's shape at a glance.
Expressions
helloAttributes.app contains an expression, {!v.whom}, which is responsible for the component's dynamic output.
{!expression} is the framework's expression syntax. In this case, the expression we are evaluating is v.whom. The name of the
attribute we defined is whom, while v is the value provider for a component's attribute set, which represents the view.
Note: Expressions are case sensitive. For example, if you have a custom field myNamespace__Amount__c, you must refer
to it as {!v.myObject.myNamespace__Amount__c}.
SEE ALSO:
Supported aura:attribute Types
Using Expressions
33
Creating Components Component Composition
Component Composition
Composing fine-grained components in a larger component enables you to build more interesting components and applications.
Let's see how we can fit components together. We will first create a few simple components: c:helloHTML and
c:helloAttributes. Then, we’ll create a wrapper component, c:nestedComponents, that contains the simple components.
Here is the source for helloHTML.cmp.
<!--c:helloHTML-->
<aura:component>
<div class="white">
Hello, HTML!
</div>
<ul>
<li class="red">I'm red.</li>
<li class="blue">I'm blue.</li>
<li class="green">I'm green.</li>
</ul>
</aura:component>
CSS source
.THIS {
background-color: grey;
}
.THIS.white {
background-color: white;
}
.THIS .red {
background-color: red;
}
.THIS .blue {
background-color: blue;
}
.THIS .green {
background-color: green;
}
Output
34
Creating Components Component Composition
<!--c:nestedComponents-->
<aura:component>
Observe! Components within components!
<c:helloHTML/>
Output
Including an existing component is similar to including an HTML tag. Reference the component by its "descriptor", which is of the form
namespace:component. nestedComponents.cmp references the helloHTML.cmp component, which lives in the c
namespace. Hence, its descriptor is c:helloHTML.
Note how nestedComponents.cmp also references c:helloAttributes. Just like adding attributes to an HTML tag, you
can set attribute values in a component as part of the component tag. nestedComponents.cmp sets the whom attribute of
helloAttributes.cmp to "component composition".
Attribute Passing
You can also pass attributes to nested components. nestedComponents2.cmp is similar to nestedComponents.cmp,
except that it includes an extra passthrough attribute. This value is passed through as the attribute value for c:helloAttributes.
<!--c:nestedComponents2-->
<aura:component>
<aura:attribute name="passthrough" type="String" default="passed attribute"/>
Observe! Components within components!
<c:helloHTML/>
<c:helloAttributes whom="{#v.passthrough}"/>
</aura:component>
Output
35
Creating Components Component Body
Note: {#v.passthrough} is an unbound expression. This means that any change to the value of the whom attribute in
c:helloAttributes doesn’t propagate back to affect the value of the passthrough attribute in
c:nestedComponents2. For more information, see Data Binding Between Components on page 44.
<c:helloHTML/>
<c:helloAttributes whom="{#v.passthrough}"/>
Output
Component Body
The root-level tag of every component is <aura:component>. Every component inherits the body attribute from
<aura:component>.
The <aura:component> tag can contain tags, such as <aura:attribute>, <aura:registerEvent>,
<aura:handler>, <aura:set>, and so on. Any free markup that is not enclosed in one of the tags allowed in a component is
assumed to be part of the body and is set in the body attribute.
The body attribute has type Aura.Component[]. It can be an array of one component, or an empty array, but it's always an array.
In a component, use “v” to access the collection of attributes. For example, {!v.body} outputs the body of the component.
36
Creating Components Component Facets
<div>Body part</div>
<lightning:button label="Push Me" onclick="{!c.doSomething}"/>
<!--END BODY-->
</aura:component>
To set the value of an inherited attribute, use the <aura:set> tag. Setting the body content is equivalent to wrapping that free
markup inside <aura:set attribute="body">. Since the body attribute has this special behavior, you can omit <aura:set
attribute="body">.
The previous sample is a shortcut for this markup. We recommend the less verbose syntax in the previous sample.
<aura:component>
<aura:set attribute="body">
<!--START BODY-->
<div>Body part</div>
<lightning:button label="Push Me" onclick="{!c.doSomething}"/>
<!--END BODY-->
</aura:set>
</aura:component>
The same logic applies when you use any component that has a body attribute, not just <aura:component>. For example:
<lightning:tabset>
<lightning:tab label="Tab 1">
Hello world!
</lightning:tab>
</lightning:tabset>
SEE ALSO:
aura:set
Working with a Component Body in JavaScript
Component Facets
A facet is any attribute of type Aura.Component[]. The body attribute is an example of a facet.
37
Creating Components Best Practices for Conditional Markup
To define your own facet, add an aura:attribute tag of type Aura.Component[] to your component. For example, let's
create a new component called facetHeader.cmp.
<!--c:facetHeader-->
<aura:component>
<aura:attribute name="header" type="Aura.Component[]"/>
<div>
<span class="header">{!v.header}</span><br/>
<span class="body">{!v.body}</span>
</div>
</aura:component>
This component has a header facet. Note how we position the output of the header using the v.header expression.
The component doesn't have any output when you access it directly as the header and body attributes aren't set. Let’s create another
component, helloFacets.cmp, that sets these attributes.
<!--c:helloFacets-->
<aura:component>
See how we set the header facet.<br/>
<c:facetHeader>
Nice body!
<aura:set attribute="header">
Hello Header!
</aura:set>
</c:facetHeader>
</aura:component>
Note that aura:set sets the value of the header attribute of facetHeader.cmp, but you don’t need to use aura:set if
you’re setting the body attribute.
SEE ALSO:
Component Body
38
Creating Components Component Versioning
The <div> component and its contents are only created and rendered if the value of the isTrue expression evaluates to true. If
the value of the isTrue expression changes and evaluates to false, all the components inside the <aura:if> tag are destroyed.
The components are created again if the isTrue expression changes again and evaluates to true.
The general guideline is to use <aura:if> because it helps your components load faster initially by deferring the creation and
rendering of the enclosed element tree until the condition is fulfilled.
SEE ALSO:
aura:if
Conditional Expressions
Dynamically Creating Components
Component Versioning
Component versioning enables you to declare dependencies against specific revisions of an installed managed package.
By assigning a version to your component, you have granular control over how the component functions when new versions of a
managed package are released. For example, imagine that a <packageNamespace>:button is pinned to version 2.0 of a package.
Upon installing version 3.0, the button retains its version 2.0 functionality.
Note: The package developer is responsible for inserting versioning logic into the markup when updating a component. If the
component wasn’t changed in the update or if the markup doesn’t account for version, the component behaves in the context
of the most recent version.
Versions are assigned declaratively in the Developer Console. When you’re working on a component, click Bundle Version Settings
in the right panel to define the version. You can only version a component if you’ve installed a package, and the valid versions for the
component are the available versions of that package. Versions are in the format <major>.<minor>. So if you assign a component
version 1.4, its behavior depends on the first major release and fourth minor release of the associated package.
39
Creating Components Component Versioning
You can’t version any other types of resources in bundles. Unsupported types include:
• Styles (.css)
• Documentation (.doc)
• Design (.design)
• SVG (.svg)
Once you’ve assigned versions to components, or if you’re developing components for a package, you can retrieve the version in several
contexts.
You can use the retrieved version to add logic to your code or markup to assign different functionality to different versions. Here’s an
example of using versioning in an <aura:if> statement.
<aura:component>
<aura:if isTrue="{!Version > 1.0}">
<c:newVersionFunctionality/>
40
Creating Components Components with Minimum API Version Requirements
</aura:if>
<c:oldVersionFunctionality/>
...
</aura:component>
SEE ALSO:
Components with Minimum API Version Requirements
Don’t Mix Component API Versions
41
Creating Components Using Expressions
The minimum version for built-in components that are Generally Available (GA) won’t increase in future releases. (However, as with
Visualforce components, their behavior might change depending on the API version of the containing component.)
SEE ALSO:
Component Versioning
Don’t Mix Component API Versions
Using Expressions
Expressions allow you to make calculations and access property values and other data within component markup. Use expressions for
dynamic output or passing values into components by assigning them to attributes.
An expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. Method calls are
not allowed in expressions.
The expression syntax is: {!expression}
expression is a placeholder for the expression.
Anything inside the {! } delimiters is evaluated and dynamically replaced when the component is rendered or when the value is
used by the component. Whitespace is ignored.
The resulting value can be a primitive, such as an integer, string, or boolean. It can also be a JavaScript object, a component or collection,
a controller method such as an action method, and other useful results.
Note: If you're familiar with other languages, you may be tempted to read the ! as the "bang" operator, which negates boolean
values in many programming languages. In the Lightning Component framework, {! is simply the delimiter used to begin an
expression.
If you're familiar with Visualforce, this syntax will look familiar.
There is a second expression syntax: {#expression}. For more details on the difference between the two forms of expression
syntax, see Data Binding Between Components.
Identifiers in an expression, such as attribute names accessed through the view, controller values, or labels, must start with a letter or
underscore. They can also contain numbers or hyphens after the first character. For example, {!v.2count} is not valid, but
{!v.count} is.
Important: Only use the {! } syntax in markup in .app or .cmp files. In JavaScript, use string syntax to evaluate an expression.
For example:
var theLabel = cmp.get("v.label");
This renders {! in plain text because the aura:text component never interprets {! as the start of an expression.
IN THIS SECTION:
Dynamic Output in Expressions
The simplest way to use expressions is to output dynamic values.
42
Creating Components Dynamic Output in Expressions
Conditional Expressions
Here are examples of conditional expressions using the ternary operator and the <aura:if> tag.
Data Binding Between Components
When you add a component in markup, you can use an expression to initialize attribute values in the component based on attribute
values of the container component. There are two forms of expression syntax, which exhibit different behaviors for data binding
between the components.
Value Providers
Value providers are a way to access data. Value providers encapsulate related values together, similar to how an object encapsulates
properties and methods.
Expression Evaluation
Expressions are evaluated much the same way that expressions in JavaScript or other programming languages are evaluated.
Expression Operators Reference
The expression language supports operators to enable you to create more complex expressions.
Expression Functions Reference
The expression language contains math, string, array, comparison, boolean, and conditional functions. All functions are case-sensitive.
In this expression, v represents the view, which is the set of component attributes, and desc is an attribute of the component. The
expression is simply outputting the desc attribute value for the component that contains this markup.
If you're including literal values in expressions, enclose text values within single quotes, such as {!'Some text'}.
Include numbers without quotes, for example, {!123}.
For booleans, use {!true} for true and {!false} for false.
SEE ALSO:
Component Attributes
Value Providers
Conditional Expressions
Here are examples of conditional expressions using the ternary operator and the <aura:if> tag.
Ternary Operator
This expression uses the ternary operator to conditionally output one of two values dependent on a condition.
<a class="{!v.location == '/active' ? 'selected' : ''}" href="#/active">Active</a>
The {!v.location == '/active' ? 'selected' : ''} expression conditionally sets the class attribute of an HTML
<a> tag, by checking whether the location attribute is set to /active. If true, the expression sets class to selected.
43
Creating Components Data Binding Between Components
If the edit attribute is set to true, a ui:button displays. Otherwise, the text in the else attribute displays.
SEE ALSO:
Best Practices for Conditional Markup
{!v.parentAttr} is a bound expression. Any change to the value of the childAttr attribute in c:child also affects the
parentAttr attribute in c:parent and vice versa.
Now, let's change the markup from:
<c:child childAttr="{!v.parentAttr}" />
to:
<c:child childAttr="{#v.parentAttr}" />
{#v.parentAttr} is an unbound expression. Any change to the value of the childAttr attribute in c:child doesn’t affect
the parentAttr attribute in c:parent and vice versa.
Here’s a summary of the differences between the forms of expression syntax.
{#expression} (Unbound Expressions)
Data updates behave as you would expect in JavaScript. Primitives, such as String, are passed by value, and data updates for the
expression in the parent and child are decoupled.
44
Creating Components Data Binding Between Components
Objects, such as Array or Map, are passed by reference, so changes to the data in the child propagate to the parent. However,
change handlers in the parent aren’t notified. The same behavior applies for changes in the parent propagating to the child.
{!expression} (Bound Expressions)
Data updates in either component are reflected through bidirectional data binding in both components. Similarly, change handlers
are triggered in both the parent and child components.
Tip: Bi-directional data binding is expensive for performance and it can create hard-to-debug errors due to the propagation
of data changes through nested components. We recommend using the {#expression} syntax instead when you pass
an expression from a parent component to a child component unless you require bi-directional data binding.
Unbound Expressions
Let’s look at another example of a c:parentExpr component that contains another component, c:childExpr.
Here is the markup for c:childExpr.
<!--c:childExpr-->
<aura:component>
<aura:attribute name="childAttr" type="String" />
The c:parentExpr component uses an unbound expression to set an attribute in the c:childExpr component.
<c:childExpr childAttr="{#v.parentAttr}" />
When we instantiate childExpr, we set the childAttr attribute to the value of the parentAttr attribute in c:parentExpr.
Since the {#v.parentAttr} syntax is used, the v.parentAttr expression is not bound to the value of the childAttr
attribute.
The c:exprApp application is a wrapper around c:parentExpr.
<!--c:exprApp-->
<aura:application >
<c:parentExpr />
</aura:application>
In the Developer Console, click Preview in the sidebar for c:exprApp to view the app in your browser.
Both parentAttr and childAttr are set to “parent attribute”, which is the default value of parentAttr.
45
Creating Components Data Binding Between Components
Now, let’s create a client-side controller for c:childExpr so that we can dynamically update the component. Here is the source for
childExprController.js.
/* childExprController.js */
({
updateChildAttr: function(cmp) {
cmp.set("v.childAttr", "updated child attribute");
}
})
Let’s add a client-side controller for c:parentExpr. Here is the source for parentExprController.js.
/* parentExprController.js */
({
updateParentAttr: function(cmp) {
cmp.set("v.parentAttr", "updated parent attribute");
}
})
Warning: Don’t use a component’s init event and client-side controller to initialize an attribute that is used in an unbound
expression. The attribute will not be initialized. Use a bound expression instead. For more information on a component’s init
event, see Invoking Actions on Component Initialization on page 269.
Alternatively, you can wrap the component in another component. When you instantiate the wrapped component in the wrapper
component, initialize the attribute value instead of initializing the attribute in the wrapped component’s client-side controller.
Bound Expressions
Now, let’s update the code to use a bound expression instead. Change this line in c:parentExpr:
<c:childExpr childAttr="{#v.parentAttr}" />
to:
<c:childExpr childAttr="{!v.parentAttr}" />
46
Creating Components Data Binding Between Components
Notice the <aura:handler> tag with name="change", which signifies a change handler. value="{!v.childAttr}"
tells the change handler to track the childAttr attribute. When childAttr changes, the onChildAttrChange client-side
controller action is invoked.
Here is the client-side controller for c:childExpr.
/* childExprController.js */
({
updateChildAttr: function(cmp) {
cmp.set("v.childAttr", "updated child attribute");
},
47
Creating Components Value Providers
onclick="{!c.updateParentAttr}"/></p>
</aura:component>
SEE ALSO:
Detecting Data Changes with Change Handlers
Dynamic Output in Expressions
Component Composition
Value Providers
Value providers are a way to access data. Value providers encapsulate related values together, similar to how an object encapsulates
properties and methods.
The value providers for a component are v (view) and c (controller).
48
Creating Components Value Providers
All components have a v value provider, but aren't required to have a controller. Both value providers are created automatically when
defined for a component.
Note: Expressions are bound to the specific component that contains them. That component is also known as the attribute value
provider, and is used to resolve any expressions that are passed to attributes of its contained components.
$Label The $Label global value provider enables you to access Using Custom Labels
labels stored outside your code.
SEE ALSO:
Dynamic Output in Expressions
49
Creating Components Value Providers
$Browser
The $Browser global value provider returns information about the hardware and operating system of the browser accessing the
application.
Attribute Description
formFactor Returns a FormFactor enum value based on the type of hardware the browser is running on.
• DESKTOP for a desktop client
• PHONE for a phone including a mobile phone with a browser and a smartphone
• TABLET for a tablet client (for which isTablet returns true)
isAndroid Indicates whether the browser is running on an Android device (true) or not (false).
isIOS Not available in all implementations. Indicates whether the browser is running on an iOS device (true)
or not (false).
isIPad Not available in all implementations. Indicates whether the browser is running on an iPad (true) or not
(false).
isIPhone Not available in all implementations. Indicates whether the browser is running on an iPhone (true) or
not (false).
isPhone Indicates whether the browser is running on a phone including a mobile phone with a browser and a
smartphone (true), or not (false).
isTablet Indicates whether the browser is running on an iPad or a tablet with Android 2.2 or later (true) or not
(false).
isWindowsPhone Indicates whether the browser is running on a Windows phone (true) or not (false). Note that this
only detects Windows phones and does not detect tablets or other touch-enabled Windows 8 devices.
Example: This example shows usage of the $Browser global value provider.
<aura:component>
{!$Browser.isTablet}
{!$Browser.isPhone}
{!$Browser.isAndroid}
{!$Browser.formFactor}
</aura:component>
Similarly, you can check browser information in a client-side controller using $A.get().
({
checkBrowser: function(component) {
var device = $A.get("$Browser.formFactor");
alert("You are using a " + device);
}
})
50
Creating Components Value Providers
$Locale
The $Locale global value provider returns information about the current user’s preferred locale.
These attributes are based on Java’s Calendar, Locale and TimeZone classes.
labelForToday The label for the Today link on the date picker. “Today”
language The language code based on the language locale. "en", "de", "zh"
nameOfMonths The full and short names of the calendar months { fullName: “January”, shortName: “Jan” }
nameOfWeekdays The full and short names of the calendar weeks { fullName: “Sunday”, shortName: “SUN” }
51
Creating Components Value Providers
Similarly, you can check locale information in a client-side controller using $A.get().
({
checkDevice: function(component) {
var locale = $A.get("$Locale.language");
alert("You are using " + locale);
}
})
SEE ALSO:
Localization
$Resource
The $Resource global value provider lets you reference images, style sheets, and JavaScript code you’ve uploaded in static resources.
Using $Resource lets you reference assets by name, without worrying about the gory details of URLs or file paths. You can use
$Resource in Lightning components markup and within JavaScript controller and helper code.
52
Creating Components Value Providers
that’s all you need. To reference an item within an archive static resource, add the rest of the path to the item using string concatenation.
Here are a few examples.
<aura:component>
<!-- Stand-alone static resources -->
<img src="{!$Resource.generic_profile_svg}"/>
<img src="{!$Resource.yourNamespace__generic_profile_svg}"/>
Include CSS style sheets or JavaScript libraries into a component using the <ltng:require> tag. For example:
<aura:component>
<ltng:require
styles="{!$Resource.SLDSv2 + '/assets/styles/lightning-design-system-ltng.css'}"
scripts="{!$Resource.jsLibraries + '/jsLibOne.js'}"
afterScriptsLoaded="{!c.scriptsLoaded}" />
</aura:component>
Note: Due to a quirk in the way $Resource is parsed in expressions, use the join operator to include multiple $Resource
references in a single attribute. For example, if you have more than one JavaScript library to include into a component the scripts
attribute should be something like the following.
scripts="{!join(',',
$Resource.jsLibraries + '/jsLibOne.js',
$Resource.jsLibraries + '/jsLibTwo.js')}"
Note: Static resources referenced in JavaScript aren’t automatically added to packages. If your JavaScript depends on a resource
that isn’t referenced in component markup, add it manually to any packages the JavaScript code is included in.
$Resource Considerations
Global value providers in the Lightning Component framework are, behind the scenes, implemented quite differently from global
variables in Salesforce. Although $Resource looks like the global variable with the same name available in Visualforce, formula fields,
and elsewhere, there are important differences. Don’t use other documentation as a guideline for its use or behavior.
53
Creating Components Expression Evaluation
Here are two specific things to keep in mind about $Resource in the Lightning Component framework.
First, $Resource isn’t available until the Lightning Component framework is loaded on the client. Some very simple components
that are composed of only markup can be rendered server-side, where $Resource isn’t available. To avoid this, when you create a
new app, stub out a client-side controller to force components to be rendered on the client.
Second, if you’ve worked with the $Resource global variable, in Visualforce or elsewhere, you’ve also used the URLFOR() formula
function to construct complete URLs to specific resources. There’s nothing similar to URLFOR() in the Lightning Component framework.
Instead, use simple string concatenation, as illustrated in the preceding examples.
SEE ALSO:
Salesforce Help: Static Resources
Expression Evaluation
Expressions are evaluated much the same way that expressions in JavaScript or other programming languages are evaluated.
Operators are a subset of those available in JavaScript, and evaluation order and precedence are generally the same as JavaScript.
Parentheses enable you to ensure a specific evaluation order. What you may find surprising about expressions is how often they are
evaluated. The framework notices when things change, and trigger re-rendering of any components that are affected. Dependencies
are handled automatically. This is one of the fundamental benefits of the framework. It knows when to re-render something on the page.
When a component is re-rendered, any expressions it uses will be re-evaluated.
Action Methods
Expressions are also used to provide action methods for user interface events: onclick, onhover, and any other component
attributes beginning with "on".
Action methods must be assigned to attributes using an expression, for example {!c.theAction}. This expression assigns a
reference to the controller function that handles the action.
Assigning action methods via expressions allows you to assign them conditionally, based on the state of the application or user interface.
For more information, see Conditional Expressions on page 43.
<aura:component>
<aura:attribute name="liked" type="Boolean" default="true"/>
<lightning:button aura:id="likeBtn"
label="{!(v.liked) ? 'Like It' : 'Unlike It'}"
onclick="{!(v.liked) ? c.likeIt : c.unlikeIt}"
/>
</aura:component>
This button will show "Like It" for items that have not yet been liked, and clicking it will call the likeIt action method. Then the
component will re-render, and the opposite user interface display and method assignment will be in place. Clicking a second time will
unlike the item, and so on.
Note: The example demonstrates how attributes can help you control the state of a button. To create a button that toggles
between states, we recommend using the lightning:buttonStateful component.
54
Creating Components Expression Operators Reference
Arithmetic Operators
Expressions based on arithmetic operators result in numerical values.
- -v.exp Unary operator. Reverses the sign of the succeeding number. For
example if the value of expenses is 100, then -expenses
is -100.
Numeric Literals
Literal Usage Description
Integer 2 Integers are numbers without a decimal point or exponent.
Null null A literal null number. Matches the explicit null value and numbers
with an undefined value.
String Operators
Expressions based on string operators result in string values.
String Literals
String literals must be enclosed in single quotation marks 'like this'.
55
Creating Components Expression Operators Reference
Unicode '\u####' A Unicode code point. The # symbols are hexadecimal digits. A Unicode literal
requires four digits.
null null A literal null string. Matches the explicit null value and strings with an undefined
value.
Comparison Operators
Expressions based on comparison operators result in a true or false value. For comparison purposes, numbers are treated as the
same type. In all other cases, comparisons check both value and type.
1 != '1'
null != false
1 ne 2
56
Creating Components Expression Operators Reference
Logical Operators
Expressions based on logical operators result in a true or false value.
! !isRequired Unary operator. Returns true if the operand is false. This operator should not be confused
with the ! delimiter used to start an expression in {!. You can combine the expression
delimiter with this negation operator to return the logical negation of a value, for example,
{!!true} returns false.
Logical Literals
Logical values are never equivalent to non-logical values. That is, only true == true, and only false == false; 1 !=
true, and 0 != false, and null != false.
Conditional Operator
There is only one conditional operator, the traditional ternary operator.
57
Creating Components Expression Functions Reference
SEE ALSO:
Expression Functions Reference
Math Functions
The math functions perform math operations on numbers. They take numerical arguments. The Corresponding Operator column lists
equivalent operators, if any.
58
Creating Components Expression Functions Reference
String Functions
Function Alternative Usage Description Corresponding
Operator
concat add concat('Hello ', Concatenates the two +
'world') arguments.
add('Walk ', 'the dog')
Label Functions
Function Usage Description
format format($Label.np.labelName, Outputs a label and updates it.
v.attribute1 , v.attribute2) Replaces any parameter
format($Label.np.hello, v.name)
placeholders with
comma-separated attribute values.
Supports ternary operators in
labels and attributes.
Informational Functions
Function Usage Description
length myArray.length Returns the length of an array or a string.
59
Creating Components Expression Functions Reference
Comparison Functions
Comparison functions take two number arguments and return true or false depending on the comparison result. The eq and
ne functions can also take other data types for their arguments, such as strings.
Boolean Functions
Boolean functions operate on Boolean arguments. They are equivalent to logical operators.
60
Creating Components Using Labels
Conditional Function
Function Usage Description Corresponding Operator
if if(isEnabled, Evaluates the first argument as ?: (ternary)
'Enabled', 'Not a boolean. If true, returns the
enabled') second argument. Otherwise,
returns the third argument.
Using Labels
Labels are text that presents information about the user interface, such as in the header (1), input fields (2), or buttons (3). While you can
specify labels by providing text values in component markup, you can also access labels stored outside your code using the $Label
global value provider in expression syntax.
This section discusses how to use the $Label global value provider in these contexts:
• The label attribute in input components
• The format() expression function for dynamically populating placeholder values in labels
61
Creating Components Using Custom Labels
IN THIS SECTION:
Using Custom Labels
Custom labels are custom text values that can be translated into any language that Salesforce supports. To access custom labels in
Lightning components, use the $Label global value provider.
Input Component Labels
A label describes the purpose of an input component. To set a label on an input component, use the label attribute.
Dynamically Populating Label Parameters
Output and update labels using the format() expression function.
Getting Labels in JavaScript
You can retrieve labels in JavaScript code. Your code performs optimally if the labels are statically defined and sent to the client
when the component is loaded.
Getting Labels in Apex
You can retrieve label values in Apex code and set them on your component using JavaScript.
Setting Label Values via a Parent Attribute
Setting label values via a parent attribute is useful if you want control over labels in child components.
Note: Label expressions in markup are supported in .cmp and .app resources only.
SEE ALSO:
Value Providers
62
Creating Components Dynamically Populating Label Parameters
This example shows how to use labels using the label attribute on an input component.
<lightning:input type="number" name="myNumber" label="Pick a Number:" value="54" />
The label is placed on the left of the input field and can be hidden by setting variant="label-hidden", which applies the
slds-assistive-text class to the label to support accessibility.
Using $Label
Use the $Label global value provider to access labels stored in an external source. For example:
<lightning:input type="number" name="myNumber" label="{!$Label.Number.PickOne}" />
To output a label and dynamically update it, use the format() expression function. For example, if you have np.labelName set
to Hello {0}, the following expression returns Hello World if v.name is set to World.
{!format($Label.np.labelName, v.name)}
SEE ALSO:
Supporting Accessibility
Note: Always use the $Label global value provider to reference a label with placeholder parameters. You can't set a string
with placeholder parameters as the first argument for format(). For example, this syntax doesn't work:
{!format('Hello {0}', v.name)}
63
Creating Components Getting Labels in JavaScript
Static Labels
Static labels are defined in one string, such as "$Label.c.task_mode_today". The framework parses static labels in markup
or JavaScript code and sends the labels to the client when the component is loaded. A server trip isn’t required to resolve the label.
Use $A.get() to retrieve static labels in JavaScript code. For example:
var staticLabel = $A.get("$Label.c.task_mode_today");
component.set("v.mylabel", staticLabel);
You can also retrieve label values using Apex code and send them to the component via JavaScript code. For more information, see
Getting Labels in Apex.
Dynamic Labels
$A.get(labelReference) must be able to resolve the label reference at compile time, so that the label values can be sent to
the client along with the component definition.
If you must defer label resolution until runtime, you can dynamically create labels in JavaScript code. This technique can be useful when
you need to use a label, but which specific label isn’t known until runtime.
// Assume the day variable is dynamically generated
// earlier in the code
// THIS CODE WON’T WORK
var dynamicLabel = $A.get("$Label.c." + day);
If the label is already known on the client, $A.get() displays the label. If the value is not known, an empty string is displayed in
production mode, or a placeholder value showing the label key is displayed in debug mode.
Using $A.get()with a label that can't be determined at runtime means that dynamicLabel is an empty string, and won’t be
updated to the retrieved value. Since the label, "$Label.c." + day, is dynamically generated, the framework can’t parse it or
send it to the client when the component is requested.
There are a few alternative approaches to using $A.get() so that you can work with dynamically generated labels.
If your component uses a known set of dynamically constructed labels, you can avoid a server roundtrip for the labels by adding a
reference to the labels in a JavaScript resource. The framework sends these labels to the client when the component is requested. For
example, if your component dynamically generates $Label.c.task_mode_today and $Label.c.task_mode_tomorrow
label keys, you can add references to the labels in a comment in a JavaScript resource, such as a client-side controller or helper.
// hints to ensure labels are preloaded
// $Label.c.task_mode_today
// $Label.c.task_mode_tomorrow
If your code dynamically generates many labels, this approach doesn’t scale well.
If you don’t want to add comment hints for all the potential labels, the alternative is to use $A.getReference(). This approach
comes with the added cost of a server trip to retrieve the label value.
This example dynamically constructs the label value by calling $A.getReference() and updates a tempLabelAttr component
attribute with the retrieved label.
var labelSubStr = "task_mode_today";
var labelReference = $A.getReference("$Label.c." + labelSubStr);
cmp.set("v.tempLabelAttr", labelReference);
var dynamicLabel = cmp.get("v.tempLabelAttr");
64
Creating Components Getting Labels in Apex
$A.getReference() returns a reference to the label. This isn’t a string, and you shouldn’t treat it like one. You never get a string
label directly back from $A.getReference().
Instead, use the returned reference to set a component’s attribute value. Our code does this in cmp.set("v.tempLabelAttr",
labelReference);.
When the label value is asynchronously returned from the server, the attribute value is automatically updated as it’s a reference. The
component is rerendered and the label value displays.
Note: Our code sets dynamicLabel = cmp.get("v.tempLabelAttr") immediately after getting the reference.
This code displays an empty string until the label value is returned from the server. If you don’t want that behavior, use a comment
hint to ensure that the label is sent to the client without requiring a later server trip.
SEE ALSO:
Using JavaScript
Input Component Labels
Dynamically Populating Label Parameters
Custom Labels
Custom labels have a limit of 1,000 characters and can be accessed from an Apex class. To define custom labels, from Setup, in the Quick
Find box, enter Custom Labels, and then select Custom Labels.
In your Apex class, reference the label with the syntax System.Label.MyLabelName.
Note: Return label values as plain text strings. You can’t return a label expression using the $Label global value provider.
The component loads the labels by requesting it from the server, such as during initialization. For example, the label is retrieved in
JavaScript code.
({
doInit : function(component, event, helper) {
var action = component.get("c.getLabel");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.mylabel", response.getReturnValue());
}
// error handling when state is "INCOMPLETE" or "ERROR"
});
65
Creating Components Setting Label Values via a Parent Attribute
$A.enqueueAction(action);
}
})
Finally, make sure you wire up the Apex class to your component. The label is set on the component during initialization.
<aura:component controller="LabelController">
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="mylabel" type="String"/>
{!v.mylabel}
</aura:component>
You can also retrieve labels in JavaScript code, including dynamically creating labels that are generated during runtime. For more
information, see Getting Labels in JavaScript.
This inner component contains a text area component and a label attribute that’s set by the container component.
<aura:component>
<aura:attribute name="label" type="String"/>
<lightning:textarea aura:id="textarea"
name="myTextarea"
label="{!v.label}"/>
</aura:component>
66
Creating Components Localization
When the component is initialized, you’ll see a button and a text area with the label My Label. When the button in the container
component is clicked, the setLabel action updates the label value in the inner component. This action finds the label attribute
and sets its value to new label.
SEE ALSO:
Input Component Labels
Component Attributes
Localization
The framework provides client-side localization support on input and output components.
The following example shows how you can override the default timezone attribute. The output displays the time in the format
hh:mm by default.
<aura:component>
<ui:outputDateTime value="2013-10-07T00:17:08.997Z" timezone="Europe/Berlin" />
</aura:component>
minute="2-digit" second="2-digit"/>
</aura:component>
({
doInit : function(component, event, helper) {
var date = new Date();
component.set("v.datetime", date)
}
})
This example creates a JavaScript Date instance, which is rendered in the format MMM DD, YYYY HH:MM:SS AM.
67
Creating Components Providing Component Documentation
Additionally, you can use the global value provider, $Locale, to obtain the locale information. The locale settings in your organization
overrides the browser’s locale information.
Note: Single language organizations cannot change their language, although they can change their locale.
For example, setting the time zone on the Language & Time Zone page to (GMT+02:00) returns 28.09.2015 09:00:00
when you run the following code.
<ui:outputDateTime value="09/28/2015" />
Running $A.get("$Locale.timezone") returns the time zone name, for example, Europe/Paris. For more information,
see "Supported Time Zones" in the Salesforce Help.
Setting the currency locale on the Company Information page to Japanese (Japan) - JPY returns ¥100,000 when you
run the following code.
<ui:outputCurrency value="100000" />
Note: To change between using the currency symbol, code, or name, use lightning:formattedNumber instead. For
more information, see lightning:formattedNumber (Beta) .
Similarly, running $A.get("$Locale.currency") returns "¥" when your org’s currency locale is set to Japanese
(Japan) - JPY. For more information, see "Supported Currencies" in the Salesforce Help.
SEE ALSO:
Formatting Dates in JavaScript
68
Creating Components Providing Component Documentation
Note: DocDef is supported for components and applications. Events and interfaces support inline descriptions only.
<aura:documentation>
<aura:description>
<p>An <code>c:myComponent</code> component represents an element that executes an
action defined by a controller.</p>
<!--More markup here, such as <pre> for code samples-->
</aura:description>
<aura:example name="myComponentExample" ref="c:myComponentExample" label="Using the
c:myComponent Component">
<p>This example shows a simple setup of <code>myComponent</code>.</p>
</aura:example>
<aura:example name="mySecondExample" ref="c:mySecondExample" label="Customizing the
c:myComponent Component">
<p>This example shows how you can customize <code>myComponent</code>.</p>
</aura:example>
</aura:documentation>
Tag Description
<aura:documentation> The top-level definition of the DocDef
<aura:description> Describes the component using extensive HTML markup. To include code samples in the
description, use the <pre> tag, which renders as a code block. Code entered in the <pre> tag
must be escaped. For example, escape <aura:component> by entering
<aura:component>.
<aura:example> References an example that demonstrates how the component is used. Supports extensive HTML
markup, which displays as text preceding the visual output and example component source. The
example is displayed as interactive output. Multiple examples are supported and should be wrapped
in individual <aura:example> tags.
• name: The API name of the example
• ref: The reference to the example component in the format
<namespace:exampleComponent>
• label: The label of the title
The following is an example component that demonstrates how c:myComponent can be used.
69
Creating Components Providing Component Documentation
Note: The linked file is in the master branch of the open-source Aura project. The master branch is our current development
branch and is ahead of the current release of the Lightning Component framework. However, this file changes infrequently and
is the best place to see if a tag is supported now or in the near future.
Tag Example
<aura:component> <aura:component description="Represents a button element">
SEE ALSO:
Reference
70
Creating Components Working with Base Lightning Components
Container Components
The following components group related information together.
71
Creating Components Working with Base Lightning Components
Button Icon lightning:buttonIconStateful An icon-only button that retains state. Button Icons 41.0
(Stateful)
Navigation Components
The following components are based on buttons.
Tree lightning:tree Displays a structural hierarchy with nested items. Trees 41.0
72
Creating Components Working with Base Lightning Components
Visual Components
The following components provide informative cues, for example, like icons and loading spinners.
Data Table lightning:datatable A table that displays columns of data, Data Tables 41.0
formatted according to type.
List View lightning:listView Displays a list view of the specified object N/A 42.0
Path lightning:path Displays a path driven by a picklist field and Path 41.0
Path Setup metadata.
73
Creating Components Working with Base Lightning Components
Progress lightning:progressBar A horizontal progress bar from left to right Progress Bars 41.0
Bar to indicate the progress of an operation.
Progress lightning:progressIndicator Displays steps in a process to indicate what Progress Indicators 41.0
Indicator has been completed. Path
and Path
Field Components
The following components enable you to enter values in a form.
File Uploader lightning:fileUpload Enables file uploads to a record. File Selector 41.0
and Preview
lightning:fileCard Displays a representation of Files
uploaded content.
74
Creating Components Working with Base Lightning Components
Input Name lightning:inputName Represents a name compound field. Form Layout 42.0
Input Location lightning:inputLocation A geolocation compound field that Form Layout 41.0
(Geolocation) accepts a latitude and longitude
value.
Radio Group lightning:radioGroup Enables single selection on a group Radio Button 41.0
of options. Radio Button Group
Rich Text Area lightning:inputRichText A WYSIWYG editor with a Rich Text Editor
customizable toolbar for entering
rich text.
Formatted Components
The following components enable you to display read-only formatted values.
Output Field lightning:outputField Displays a label, help text, and value 41.0
for a field on a Salesforce object.
75
Creating Components Working with Base Lightning Components
Feature-Specific Components
The following components are usable only in the context of specific Salesforce features.
76
Creating Components Base Lightning Components Considerations
Warning: Don’t depend on the markup of a Lightning component as its internals can change in future releases. Reaching into
the component internals can also cause unrecoverable errors in the app. For example, using cmp.get("v.body") and
examining the DOM elements can cause issues in your code if the component markup change down the road.
With LockerService enforced, you can’t traverse the DOM for components you don't own. Instead of accessing the DOM tree, take
advantage of value binding with component attributes and use component methods that are available to you. For example, to get an
attribute on a component, use cmp.find("myInput").get("v.name") instead of
cmp.find("myInput").getElement().name. The latter doesn’t work if you don’t have access to the component, such as
a component in another namespace.
Many of the base Lightning components are still evolving and the following considerations can help you while you’re building your
apps.
lightning:buttonMenu (Beta)
This component contains menu items that are created only if the button is triggered. You can’t reference the menu items during
initialization or if the button isn’t triggered yet.
lightning:formattedDateTime (Beta)
This component provides fallback behavior in Apple Safari 10 and below. The following formatting options have exceptions when
using the fallback behavior in older browsers.
• era is not supported.
• timeZoneName appends GMT for short format, GMT-h:mm or GMT+h:mm for long format.
• timeZone supports UTC. If another timezone value is used, lightning:formattedDateTime uses the browser
timezone.
lightning:formattedNumber (Beta)
This component provides the following fallback behavior in Apple Safari 10 and below.
• If style is set to currency, providing a currencyCode value that’s different from the locale displays the currency code
instead of the symbol. The following example displays EUR12.34 in fallback mode and €12.34 otherwise.
<lightning:formattedNumber value="12.34" style="currency"
currencyCode="EUR"/>
• currencyDisplayAs supports symbol only. The following example displays $12.34 in fallback mode only if the
currencyCode matches the user’s locale currency and USD12.34 otherwise.
lightning:input (Beta)
Date pickers are available in the following components but they don’t inherit the Lightning Design System styling.
• <lightning:input type="date" />
• <lightning:input type="datetime-local" />
Fields for percentage and currency input must specify a step increment of 0.01 as required by the native implementation.
<lightning:input type="number" name="percentVal" label="Enter a percentage value"
formatter="percent" step="0.01" />
<lightning:input type="number" name="currencyVal" label="Enter a dollar amount"
formatter="currency" step="0.01" />
77
Creating Components Event Handling in Base Lightning Components
When working with checkboxes, radio buttons, and toggle switches, use aura:id to group and traverse the array of components.
Grouping them enables you to use get("v.checked") to determine which elements are checked or unchecked without
reaching into the DOM. You can also use the name and value attributes to identify each component during the iteration. The
following example groups three checkboxes together using aura:id.
<aura:component>
<form>
<fieldset>
<legend>Select your favorite color:</legend>
<lightning:input type="checkbox" label="Red"
name="color1" value="1" aura:id="colors"/>
<lightning:input type="checkbox" label="Blue"
name="color2" value="2" aura:id="colors"/>
<lightning:input type="checkbox" label="Green"
name="color3" value="3" aura:id="colors"/>
</fieldset>
<lightning:button label="Submit" onclick="{!c.submitForm}"/>
</form>
</aura:component>
In your client-side controller, you can retrieve the array using cmp.find("colors") and inspect the checked values.
When working with type="file", you must provide your own server-side logic for uploading files to Salesforce. Read the file
using the FileReader HTML object, and then encode the file contents before sending them to your Apex controller. In your Apex
controller, you can use the EncodingUtil methods to decode the file data. For example, you can use the Attachment object
to upload files to a parent object. In this case, you pass in the base64 encoded file to the Body field to save the file as an attachment
in your Apex controller.
Uploading files using this component is subject to regular Apex controller limits, which is 1 MB. To accommodate file size increase
due to base64 encoding, we recommend that you set the maximum file size to 750 KB. You must implement chunking for file size
larger than 1 MB. Files uploaded via chunking are subject to a size limit of 4 MB. For more information, see the Apex Developer Guide.
lightning:tab (Beta)
This component creates its body during runtime. You can’t reference the component during initialization. Referencing the component
using aura:id can return unexpected results, such as the component returning an undefined value when implementing
cmp.find("myComponent").
lightning:tabset (Beta)
When you load more tabs than can fit the width of the viewport, the tabset provides navigation buttons that scrolls horizontally to
display the overflow tabs.
SEE ALSO:
Component Reference
78
Creating Components Event Handling in Base Lightning Components
({
doSomething: function(cmp, event, helper) {
var button = event.getSource();
Retrieve a component attribute that’s passed to the event by using this syntax.
event.getSource().get("v.name")
({
handleClick: function(cmp, event, helper) {
//returns "new", "edit", or "delete"
var buttonName = event.getSource().get("v.name");
}
})
79
Creating Components Lightning Design System Considerations
</lightning:tabset>
</aura:component>
({
handleActive: function (cmp, event) {
var tab = event.getSource();
switch (tab.get('v.id')) {
case 'tab1':
//do something when tab1 is clicked
break;
case 'tab2':
//do something when tab2 is clicked
break;
}
}
})
Note: If you need a reference to the target component, use the onactive event handler instead.
80
Creating Components Lightning Design System Considerations
If you're using the components outside of the Salesforce app and Lightning Experience, such as in standalone apps and Lightning Out,
extend force:slds to apply Lightning Design System styling to your components. Here are several guidelines for using Lightning
Design System in base components.
The class you add is appended to other base classes that are applied to the component, resulting in the following markup.
<button class="slds-button slds-button_neutral slds-m-around_medium"
type="button" name="submit">Submit</button>
Similarly, you can create a custom class and pass it into the class attribute.
<lightning:badge label="My badge" class="myCustomClass"/>
You have the flexibility to customize the components at a granular level beyond the CSS scaffolding we provide. Let’s look at the
lightning:card component, where you can create your own body markup. You can apply the slds-p-horizontal_small
or slds-card__body_inner class in the body markup to add padding around the body.
<!-- lightning:card example using slds-p-horizontal_small class -->
<lightning:card>
<aura:set attribute="title">My Account</aura:set>
<aura:set attribute="footer">Footer</aura:set>
<aura:set attribute="actions">
<lightning:button label="New"/>
</aura:set>
<p class="slds-p-horizontal_small">
Card Body
</p>
</lightning:card>
81
Creating Components Lightning Design System Considerations
as they are CSS classes that are available by default in base components. You can also consider using tokens to ensure that your design
is consistent across your components. Specify values in the token bundle and reuse them in your components’ CSS resources.
Notice the success variant is not supported. However, you can add the slds-button_success class to achieve the same
result.
<lightning:button name="submit" label="Submit" class="slds-button_success"/>
Let’s look at another example. You can create a group of related information using the lightning:tile component. Although
this component doesn’t provide a variant attribute, you can achieve the Lightning Design System board variant by passing in the
slds-tile_board class.
<aura:component>
<ul class="slds-has-dividers_around-space">
82
Creating Components Lightning Design System Considerations
<li class="slds-item">
<lightning:tile label="Anypoint Connectors" href="/path/to/somewhere"
class="slds-tile_board">
<p class="slds-text-heading_medium">$500,000</p>
<p class="slds-truncate" title="Company One"><a href="#">Company One</a></p>
<p class="slds-truncate">Closing 9/30/2015</p>
</lightning:tile>
</li>
</ul>
</aura:component>
If you don’t see a variant you need, check to see if you can pass in a Lightning Design System class to the base component before creating
your own custom CSS class. Don’t be afraid to experiment with Lightning Design System classes and variants in base components. For
more information, see Lightning Design System.
SEE ALSO:
Styling Apps
Styling with Design Tokens
The following reference describes how variants in base components correspond to variants in Lightning Design System. Base components
that don’t have any visual styling, such as lightning:formattedDateTime, are not listed here. For more information on any
of these components, see the Component Library (Beta).
Accordion
A lightning:accordion component is a collection of vertically stacked sections with content areas, only one of which is expanded
at a time. This component does not support the variant attribute. lightning:accordion uses the styling from Accordion
in the Lightning Design System.
Avatar
A lightning:avatar component is an image that represents an object, such as an account or user. You can create avatars in
different sizes. lightning:avatar uses the styling from Avatar in the Lightning Design System.
83
Creating Components Lightning Design System Considerations
Badge
A lightning:badge component is a label containing a small amount of information. This component does not support the
variant attribute. lightning:badge uses the styling from Badges in the Lightning Design System.
Breadcrumb
A lightning:breadcrumbs component is a label containing a small amount of information. This component does not support
the variant attribute. lightning:breadcrumb uses the styling from Breadcrumbs in the Lightning Design System.
Button
A lightning:button component is a button that executes an action in a client-side controller. Buttons support icons to the left
or right of the text label. lightning:button uses the styling from Buttons in the Lightning Design System.
base slds-button A button without a border, which appears like a text link
Button Group
A lightning:buttonGroup component is a group of buttons that can be displayed together to create a navigational bar. You
can nest lightning:button and lightning:buttonMenu components in the group. Although the button group itself
doesn’t support the variant attribute, variants are supported for buttons and the button menu components. For example, you can
nest <lightning:button variant="inverse" label="Refresh" /> in a button group. If including
84
Creating Components Lightning Design System Considerations
lightning:buttonMenu, place it after the buttons and pass in the slds-button_last class to adjust the border.
lightning:buttonGroup uses the styling from Button Groups in the Lightning Design System.
Button Icon
A lightning:buttonIcon component is an icon-only button that executes an action in a client-side controller. You can create
button icons in different sizes. Only Lightning Design System utility icons are supported. lightning:buttonIcon uses the styling
from Button Icons in the Lightning Design System.
brand slds-button_icon-brand A button that uses the Salesforce blue background color
container slds-button_icon-container A 32px by 32px button that looks like a plain icon
border-filled slds-button_icon-border-filled A button that contains an icon with gray border and white background
bare-inverse slds-button_icon-inverse A button that contains a white icon without borders for a dark
background
border-inverse slds-button_icon-border-inverse A button that contains a white icon for a dark background
border-inverse slds-button_icon-border-inverse A button that contains a white icon for a dark background
85
Creating Components Lightning Design System Considerations
Button Menu
A lightning:buttonMenu component is a dropdown menu with a list of menu items, represented by lightning:menuItem
components. Menu items can be checked or unchecked, or execute an action in a client-side controller. You can create button menus
with icons in different sizes and position the dropdown menu in different positions relative to the button. The variant changes the
appearance of the button, and is similar to the variants on button icons. lightning:buttonMenu uses the styling from Menus
in the Lightning Design System.
container slds-button_icon-container A 32px by 32px button that looks like a plain icon
border-filled slds-button_icon-border-filled A button that contains an icon with gray border and white background
bare-inverse slds-button_icon-inverse A button that contains a white icon without borders for a dark
background
border-inverse slds-button_icon-border-inverse A button that contains a white icon for a dark background
Button (Stateful)
A lightning:buttonStateful component is a button that toggles between states. Stateful buttons can show a different label
and icon based on their states. Only Lightning Design System utility icons are supported. lightning:buttonStateful uses
the styling from Buttons in the Lightning Design System.
86
Creating Components Lightning Design System Considerations
text slds-button A button that contains an icon with gray border and white background
Card
A lightning:card component is a group of related information in an article HTML tag. lightning:card uses the
styling from Cards in the Lightning Design System.
Carousel
A lightning:carousel component is a collection of images that are displayed horizontally one at a time. The carousel doesn’t
support the variant attribute, and it uses the slds-carousel class on the outer element. lightning:carousel uses
the styling from Carousel in the Lightning Design System.
87
Creating Components Lightning Design System Considerations
Checkbox Group
A lightning:checkboxGroup component is a group of checkboxes that enables selection of single or multiple options. This
component is different from lightning:input of type="checkbox" as the latter is not suitable for grouping a set of
checkboxes together. Although the checkbox group doesn’t support the variant attribute, the slds-form-element class is
appended to the fieldset element that encloses the checkbox group. lightning:checkboxGroup uses the styling from
Checkbox in the Lightning Design System.
Combobox
A lightning:combobox component is an input element that enables single selection from a list of options. The result of the
selection is displayed as the value of the input. In a multi-select combobox, each selected option is displayed in a pill below the input
element. lightning:combobox uses the styling from Combobox in the Lightning Design System.
88
Creating Components Lightning Design System Considerations
Dual Listbox
A lightning:dualListbox component provides two list boxes, where you can move one or more options to the second list
box and reorder the selected options. lightning:dualListbox uses the styling from Dueling Picklist in the Lightning Design
System.
89
Creating Components Lightning Design System Considerations
Dynamic Icon
A lightning:dynamicIcon component represents various animated icons. The type attribute determines the animated icon
to display and corresponds to the dynamic icons in the Lightning Design System. lightning:dynamicIcon uses the styling
from Dynamic Icons in the Lightning Design System.
File Uploader
A lightning:fileUpload component enables file uploads to a record. The file uploader includes drag-and-drop functionality
and filtering by file types. Although it doesn’t support the variant attribute, the slds-file-selector class is appended to
the component. lightning:fileUpload uses the styling from FileSelector in the Lightning Design System.
Form Layout
A form layout represents a set of interactive controls to submit user input, which can include compound fields such as fields for addresses,
names, or geolocation. These components use the styling from Form Layout in the Lightning Design System.
lightning:inputAddress displays an address compound field.
90
Creating Components Lightning Design System Considerations
lightning:inputField displays an editable field with a label, help text, and value that correspond to a field on a Salesforce
object. This component must be nested in a lightning:recordEditForm component.
91
Creating Components Lightning Design System Considerations
Icon
A lightning:icon component is a visual element that provides context and enhances usability. Although all Lightning Design
System icons are supported, only utility icons support variants. You can create icons in different sizes. lightning:icon uses the
styling from Icons in the Lightning Design System.
Input
A lightning:input component is an interactive control, such as an input field or checkbox, which accepts user input.
lightning:input uses the styling from Input in the Lightning Design System.
92
Creating Components Lightning Design System Considerations
Layout
A lightning:layout component is a flexible grid system for arranging containers within a page or another container. Instead of
using the variant attribute, customization of the layout is controlled by horizontalAlign, verticalAlign, and
pullToBoundary. lightning:layout uses the styling from Grid in the Lightning Design System. For more information, see
the following resources.
• lightning:layout
• Lightning Design System Considerations
List View
A lightning:listView component represents a list view of records that you own or have read or write access to, and records
shared with you. Inline edit, row level actions, and the action bar are supported in Lightning Experience, the Salesforce app, and
communities only. On a desktop, this component renders a full list view. On all other form factors, such as a tablet or mobile devices,
the component renders a mobile-friendly alternative.
Pill
A lightning:pill component is a text label that’s wrapped by a rounded border and displayed with a remove button. Pills can
contain an icon or avatar next to the text label. This component does not support the variant attribute, but its content and other
attributes determine the styling applied to them. For example, a pill with hasError="true" displays as a pill with a red border
and error icon. lightning:pill uses the styling from Pills in the Lightning Design System.
Additionally, you can display pills in a container using the lightning:pillContainer component.
Progress Bar
A lightning:progressBar component displays a horizontal progress bar from left to right to indicate the progress of an
operation. It uses the styling from Progress Bar in the Lightning Design System.
93
Creating Components Lightning Design System Considerations
Additionally, lightning:path and lightning:picklistPath enables you to display the progress of a process on a record
based on a specified picklist field. lightning:path displays a path based on your Path Settings in Setup and
lightning:picklistPath displays a path derived from the picklistFieldApiName attribute.
shaded slds-progress_shade For type="base" only. Adds a shaded background to the current
step.
Radio Group
A lightning:radioGroup component is a group of radio that enables selection of a single option. The type attribute determines
if a group of radio options or buttons is displayed. lightning:radioGroup uses the styling from Radio Group in the Lightning
Design System.
94
Creating Components Lightning Design System Considerations
label-hidden slds-form_inline A group of radio options with a label that’s visually hidden
Select
A lightning:select component is a dropdown list that enables you to select a single option. lightning:select uses
the styling from Select in the Lightning Design System.
Slider
A lightning:slider component is a slider for specifying a value between two specified numbers. This component does not
support the variant attribute. The type attribute determines if a horizontal (default) or vertical slider is displayed.
lightning:slider uses the styling from Slider in the Lightning Design System.
95
Creating Components Lightning Design System Considerations
Spinner
A lightning:spinner component is a spinner that indicates data is loading. You can create spinners in different sizes.
lightning:spinner uses the styling from Spinners in the Lightning Design System.
Tabs
A lightning:tabset component is a list of tabs with corresponding content areas, represented by lightning:tab
components. lightning:tabset uses the styling from Tabs in the Lightning Design System.
vertical slds-vertical-tabs A list of tabs that are displayed vertically to the left of the content areas
96
Creating Components Lightning Design System Considerations
Textarea
A lightning:textarea component is an input field for multi-line text input. It uses the styling from Textarea in the Lightning
Design System.
Tile
A lightning:tile component is a group of related information. This component does not support variants, but you can pass in
the slds-tile_board class to create a board. Similarly, use a definition list in the tile body to create a tile with an icon or uses an
unordered list to create a list of tiles with avatars. lightning:tile uses the styling from Tiles in the Lightning Design System.
Tree
A lightning:tree component is a visualization of a structure hierarchy. A tree item, also known as a branch, can be expanded or
collapsed. Although this component does not support the variant attribute, it uses the styling from Trees in the Lightning Design
System.
Vertical Navigation
A lightning:verticalNavigation component is a list of links that are one level deep, with support for icons and overflow
sections that collapse and expand. Although this component does not support the variant attribute, you can use the compact
97
Creating Components Working with UI Components
and shaded attributes to achieve compact spacing and styling for a shaded background. lightning:verticalNavigation
uses the styling from Vertical Navigation in the Lightning Design System.
Note: If you are looking for components that apply the Lightning Design System styling, consider using the base lightning
components instead.
For all the components available, see the component reference at
https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the name of
your custom Salesforce domain.
Menu ui:menu A drop-down list with a trigger that controls its visibility
ui:checkboxMenuItem A menu item that supports multiple selection and can be used to
trigger an action
98
Creating Components Working with UI Components
Radio button ui:inputRadio A selectable option that supports only a single selection
Visual Components
The following components provides informative cues, for example, like error messages and loading spinners.
Field Components
The following components enables you to enter or display values.
99
Creating Components Event Handling in UI Components
Text Area ui:inputTextArea An input field for entering multiple lines of text
SEE ALSO:
Using the UI Components
Creating Components
Component Bundles
100
Creating Components Using the UI Components
Capture a UI event by defining its handler on the component. For example, you want to listen to the HTML DOM event, onblur, on a
ui:inputTextArea component.
The blur="{!c.handleBlur}" listens to the onblur event and wires it to your client-side controller. When you trigger the
event, the following client-side controller handles the event.
handleBlur : function(cmp, event, helper){
var elem = cmp.find("textarea").getElement();
//do something else
}
For all available events on all components, see the Component Library (Beta) on page 402.
The next example takes in numerical inputs and returns the sum of those numbers. The ui:inputNumber component listens to
the onkeyup browser event. When the value in this component changes on the keyup event, the value in the ui:outputNumber
component is updated as well, and returns the sum of the two values.
<aura:attribute name="number1" type="integer" default="1"/>
<aura:attribute name="number2" type="integer" default="2"/>
Note: The input fields return a string value and must be properly handled to accommodate numerical values. In this example,
both values are multiplied by 1 to obtain their numerical equivalents.
101
Creating Components Supporting Accessibility
Note: For all available component attributes and events, see the component reference at
https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the
name of your custom Salesforce domain .
To use input components in your own custom component, add them to your .cmp or .app resource. This example is a basic set up
of a text field and button. The aura:id attribute defines a unique ID that enables you to reference the component from your JavaScript
code using cmp.find("myID");.
<ui:inputText label="Name" aura:id="name" placeholder="First, Last"/>
<ui:outputText aura:id="nameOutput" value=""/>
<ui:button aura:id="outputButton" label="Submit" press="{!c.getInput}"/>
Note: All text fields must specify the label attribute to provide a textual label of the field. If you must hide the label from view,
set labelClass="assistiveText" to make the label available to assistive technologies.
The ui:outputText component acts as a placeholder for the output value of its corresponding ui:inputText component.
The value in the ui:outputText component can be set with the following client-side controller action.
getInput : function(cmp, event) {
var fullName = cmp.find("name").get("v.value");
var outName = cmp.find("nameOutput");
outName.set("v.value", fullName);
}
The following example is similar to the previous, but uses value binding without a client-side controller. The ui:outputText
component reflects the latest value on the ui:inputText component when the onkeyup browser event is fired.
<aura:attribute name="first" type="String" default="John"/>
<aura:attribute name="last" type="String" default="Doe"/>
Tip: To create and edit records in the Salesforce app, use the force:createRecord and force:recordEdit events
to utilize the built-in record create and edit pages.
Supporting Accessibility
When customizing components, be careful in preserving code that ensures accessibility, such as the aria attributes.
Accessible software and assistive technology enable users with disabilities to use and interact with the products you build. Aura
components are created according to W3C specifications so that they work with common assistive technologies. While we always
recommend that you follow the WCAG Guidelines for accessibility when developing with the Lightning Component framework, this
guide explains the accessibility features that you can leverage when using components in the ui namespace.
IN THIS SECTION:
Button Labels
Audio Messages
Forms, Fields, and Labels
102
Creating Components Button Labels
Events
Menus
Button Labels
Buttons can appear with text only, an icon and text, or an icon without text. To create an accessible button, use lightning:button
and set a textual label using the label attribute. For more information, see lightning:button .
Note: You can create accessible buttons using ui:button but they don’t come with Lightning Design System styling. We
recommend using lightning:button instead.
Button with text only:
<lightning:button label="Search" onclick="{!c.doSomething}"/>
The alternativeText attribute provides a text label that’s hidden from view and available to assistive technology.
This example shows the HTML generated by lightning:button:
<!-- Good: using span/assistiveText to hide the label visually, but show it to screen
readers -->
<button>
::before
<span class="slds-assistive-text">Settings</span>
</button>
Audio Messages
To convey audio notifications, use the ui:message component, which has role="alert" set on the component by default.
The "alert" aria role will take any text inside the div and read it out loud to screen readers without any additional action by the
user.
<ui:message title="Error" severity="error" closable="true">
This is an error message.
</ui:message>
103
Creating Components Events
If your code fails, check the label element during component rendering. A label element should have the for attribute and match the
value of input control id attribute, OR the label should be wrapped around an input. Input controls include <input>, <textarea>,
and <select>.
Here’s an example of the HTML generated by lightning:input.
<!-- Good: using label/for= -->
<label for="fullname">Enter your full name:</label>
<input type="text" id="fullname" />
SEE ALSO:
Using Labels
Events
Although you can attach an onclick event to any type of element, for accessibility, consider only applying this event to elements
that are actionable in HTML by default, such as <a>, <button>, or <input> tags in component markup. You can use an onclick
event on a <div> tag to prevent event bubbling of a click.
Menus
A menu is a dropdown list with a trigger that controls its visibility. You must provide the trigger, which displays a text label, and a list of
menu items. The dropdown menu and its menu items are hidden by default. You can change this by setting the visible attribute
on the ui:menuList component to true. The menu items are shown only when you click the ui:menuTriggerLink
component.
This example code creates a menu with several items:
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Opportunity Status"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<ui:actionMenuItem aura:id="item2" label="Open"
click="{!c.updateTriggerLabel}"/>
<ui:actionMenuItem aura:id="item3" label="Closed"
click="{!c.updateTriggerLabel}"/>
<ui:actionMenuItem aura:id="item4" label="Closed Won"
click="{!c.updateTriggerLabel}"/>
</ui:menuList>
</ui:menu>
Different menus achieve different goals. Make sure you use the right menu for the desired behavior. The three types of menus are:
Actions
Use the ui:actionMenuItem for items that create an action, like print, new, or save.
Radio button
If you want users to pick only one from a list several items, use ui:radioMenuItem.
104
Creating Components Menus
Checkbox style
If users can pick multiple items from a list of several items, use ui:checkboxMenuItem. Checkboxes can also be used to turn
one item on or off.
Note: To create a dropdown menu with a trigger that’s a button, use lightning:buttonMenu instead.
105
CHAPTER 4 Using Components
In this chapter ... You can use components in many different contexts. This section shows you how.
• Lightning Component
Bundle Design
Resources
• Use Lightning
Components in
Lightning Experience
and the Salesforce
Mobile App
• Get Your Lightning
Components Ready
to Use on Lightning
Pages
• Use Lightning
Components in
Community Builder
• Use Lightning
Components with
Flows
• Add Components to
Apps
• Integrate Your
Custom Apps into the
Chatter Publisher
• Use Lightning
Components in
Visualforce Pages
• Add Lightning
Components to Any
App with Lightning
Out (Beta)
106
Using Components Lightning Component Bundle Design Resources
design:component
This is the root element for the design resource. It contains the component’s design-time configuration for tools such as the App Builder
to use.
Attribute Description
label Sets the label of the component when it displays in the Lightning App Builder. When creating a
custom Lightning page template component, this text displays as the name of the template in the
Lightning App Builder new page wizard.
Note: Label expressions in markup are supported in .cmp and .app resources only.
design:attribute
To make a Lightning component attribute available for admins to edit in tools such as the App Builder, add a design:attribute
node for the attribute into the design resource. An attribute marked as required in the component definition automatically appears,
unless it has a default value assigned to it.
For Lightning page interfaces, the design resource supports only attributes of type Integer, String, or Boolean. To see which
attribute types the lightning:availableForFlowScreens interface supports, go to Considerations for Configuring Components for Flow
Screens.
Note: In a design:attribute node, the Cloud Flow Designer supports only the name, label, and description attributes.
The other attributes are ignored.
Attribute Description
datasource Renders a field as a picklist, with static values. Only supported for String attributes.
<design:attribute name="Name" datasource="value1,value2,value3" />
You can also set the picklist values dynamically using an Apex class. See Create Dynamic Picklists for
Your Custom Components on page 132 for more information.
Any String attribute with a datasource in a design resource is treated as a picklist.
107
Using Components Lightning Component Bundle Design Resources
Attribute Description
default Sets a default value on an attribute in a design resource.
<design:attribute name="Name" datasource="value1,value2,value3"
default="value1" />
max If the attribute is an Integer, this sets its maximum allowed value. If the attribute is a String,
this is the maximum length allowed.
min If the attribute is an Integer, this sets its minimum allowed value. If the attribute is a String,
this is the minimum length allowed.
name Required attribute. Its value must match the aura:attribute name value in the .cmp resource.
placeholder Input placeholder text for the attribute when it displays in the tool.
Note: Label expressions in markup are supported in .cmp and .app resources only.
Note: <sfdc:object> and <sfdc:objects> aren’t supported in Community Builder or the Cloud Flow Designer. They’re
also ignored when setting a component to use as an object-specific action or to override a standard action.
Here’s the same “Hello World” component’s design resource restricted to two objects.
<design:component label="Hello World">
<design:attribute name="subject" label="Subject" description="Name of the person you
want to greet" />
<design:attribute name="greeting" label="Greeting" />
<sfdc:objects>
<sfdc:object>Custom__c</sfdc:object>
<sfdc:object>Opportunity</sfdc:object>
</sfdc:objects>
</design:component>
If an object is installed from a package, add the namespace__ string to the beginning of the object name when including it in the
<sfdc:object> tag set. For example: objectNamespace__ObjectApiName__c.
SEE ALSO:
Configure Components for Lightning Pages and the Lightning App Builder
Tips and Considerations for Configuring Components for Lightning Pages and the Lightning App Builder
108
Using Components Use Lightning Components in Lightning Experience and the
Salesforce Mobile App
IN THIS SECTION:
Configure Components for Custom Tabs
Add the force:appHostable interface to a Lightning component to allow it to be used as a custom tab in Lightning Experience
or the Salesforce mobile app.
Add Lightning Components as Custom Tabs in Lightning Experience
Make your Lightning components available for Lightning Experience users by displaying them in a custom tab.
Add Lightning Components as Custom Tabs in the Salesforce App
Make your Lightning components available for Salesforce for Android, Salesforce for iOS, and Salesforce mobile web users by displaying
them in a custom tab.
Lightning Component Actions
Lightning component actions are custom actions that invoke a Lightning component. They support Apex and JavaScript and provide
a secure way to build client-side custom functionality. Lightning component actions are supported only in the Salesforce mobile
app and Lightning Experience.
Override Standard Actions with Lightning Components
Add the lightning:actionOverride interface to a Lightning component to enable the component to be used to override
a standard action on an object. You can override the View, New, Edit, and Tab standard actions on most standard and all custom
components. Overriding standard actions allows you to customize your org using Lightning components, including completely
customizing the way you view, create, and edit records.
</aura:component>
The appHostable interface makes the component available for use as a custom tab. It doesn’t require you to add anything
else to the component.
109
Using Components Add Lightning Components as Custom Tabs in Lightning
Experience
USER PERMISSIONS
To create Lightning
Component Tabs:
• Customize Application
<aura:component implements="force:appHostable">
110
Using Components Add Lightning Components as Custom Tabs in the Salesforce
App
3. Check your output by navigating to the App Launcher in Lightning Experience. Your custom app should appear in theApp Launcher.
Click the custom app to see the components you added.
USER PERMISSIONS
To create Lightning
Component Tabs:
• Customize Application
<aura:component implements="force:appHostable">
Note: You must create a custom Lightning component tab before you can add your component to the navigation menu.
Accessing your Lightning component from the full Salesforce site is not supported.
3. Check your output by going to Salesforce mobile web. Your new menu item should appear in the navigation menu.
111
Using Components Lightning Component Actions
Note: By default, Salesforce mobile web is turned on for your org. For more information on using mobile web, see the Salesforce
App Developer Guide.
IN THIS SECTION:
Configure Components for Custom Actions
Add the force:lightningQuickAction or force:lightningQuickActionWithoutHeader interface to a
Lightning component to enable it to be used as a custom action in Lightning Experience or the Salesforce mobile app. You can use
components that implement one of these interfaces as object-specific or global actions in both Lightning Experience and the
Salesforce app.
Configure Components for Record-Specific Actions
Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the
current record. The current record ID is useful if the component is used on a Lightning record page, as an object-specific custom
action or action override in Lightning Experience or the Salesforce app, and so on.
112
Using Components Lightning Component Actions
These interfaces are mutually exclusive. That is, components can implement either the force:lightningQuickAction interface
or the force:lightningQuickActionWithoutHeader interface, but not both. This should make sense; a component can’t
both present standard user interface elements and not present standard user interface elements.
<br/>
<lightning:button label="Add" onclick="{!c.clickAdd}"/>
</aura:component>
The component markup simply presents two input fields, and an Add button.
The component’s controller does all the real work.
/*quickAddController.js*/
({
clickAdd: function(component, event, helper) {
})
Retrieving the two numbers entered by the user is straightforward, though a more robust component would check for valid inputs,
and so on. The interesting part of this example is what happens to the numbers and how the custom action resolves.
The results of the add calculation are displayed in a “toast,” which is a status message that appears at the top of the page. The
toast is created by firing the force:showToast event. A toast isn’t the only way you could display the results, nor are actions
113
Using Components Lightning Component Actions
the only use for toasts. It’s just a handy way to show a message at the top of the screen in Lightning Experience or the Salesforce
app.
What’s interesting about using a toast here, though, is what happens afterward. The clickAdd controller action fires the
force:closeQuickAction event, which dismisses the action panel. But, even though the action panel is closed, the toast
still displays. The force:closeQuickAction event is handled by the action panel, which closes. The force:showToast
event is handled by the one.app container, so it doesn’t need the panel to work.
SEE ALSO:
Configure Components for Record-Specific Actions
Note: If your component implements force:hasRecordId, you don’t need to add a recordId attribute to the
component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a
runtime error.
• When your component is invoked in a record context in Lightning Experience or the Salesforce app, the recordId is set to the
ID of the record being viewed.
This behavior is different than you might expect for an interface in a programming language. This difference is because
force:hasRecordId is a marker interface. A marker interface is a signal to the component’s container to add the interface’s behavior
to the component.
The recordId attribute is set only when you place or invoke the component in an explicit record context. For example, when you
place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home. In all
other cases, such as when you invoke the component as a global action, or create the component programmatically inside another
component, recordId isn’t set, and your component shouldn’t depend on it.
114
Using Components Lightning Component Actions
<aura:component controller="QuickContactController"
implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">
115
Using Components Lightning Component Actions
value="{!v.newContact.LastName}" required="true"/>
</aura:component>
The component defines the following attributes, which are used as member variables.
• account—holds the full account record, after it’s loaded in the init handler
• newContact—an empty contact, used to capture the form field values
The rest of the component definition is a standard form that displays an error on the field if the required fields are empty or the
phone field doesn’t match the specified pattern.
The component’s controller has all of the interesting code, in three action handlers.
quickContactController.js
({
doInit : function(component, event, helper) {
116
Using Components Lightning Component Actions
// Update the UI: close panel, show toast, refresh account page
$A.get("e.force:closeQuickAction").fire();
resultsToast.fire();
$A.get("e.force:refreshView").fire();
}
else if (state === "ERROR") {
console.log('Problem saving contact, response state: ' + state);
}
else {
console.log('Unknown problem, response state: ' + state);
}
});
},
The first action handler, doInit, is an init handler. Its job is to use the record ID that’s provided via the force:hasRecordId
interface and load the full account record. Note that there’s nothing to stop this component from being used in an action on
another object, like a lead, opportunity, or custom object. In that case, doInit will fail to load a record, but the form will still
display.
The handleSaveContact action handler validates the form by calling a helper function. If the form isn’t valid, the field-level
errors are displayed. If the form is valid, then the action handler:
• Prepares the server action to save the new contact.
• Defines a callback function, called the response handler, for when the server completes the action. The response handler is
discussed in a moment.
117
Using Components Lightning Component Actions
({
validateContactForm: function(component) {
var validContact = true;
if (allValid) {
// Verify we have an account to attach it to
var account = component.get("v.account");
if($A.util.isEmpty(account)) {
validContact = false;
console.log("Quick action context doesn't have a valid account.");
}
return(validContact);
}
}
})
Finally, the Apex class used as the server-side controller for this component is deliberately simple to the point of being obvious.
QuickContactController.apxc
@AuraEnabled
public static Account getAccount(Id accountId) {
// Perform isAccessible() checks here
return [SELECT Name, BillingCity, BillingState FROM Account WHERE Id =
:accountId];
}
@AuraEnabled
public static Contact saveContactWithAccount(Contact contact, Id accountId) {
// Perform isAccessible() and isUpdateable() checks here
118
Using Components Override Standard Actions with Lightning Components
contact.AccountId = accountId;
upsert contact;
return contact;
}
One method retrieves an account based on the record ID. The other associates a new contact record with an account, and then
saves it to the database.
SEE ALSO:
Configure Components for Custom Actions
force:hasRecordId
force:hasSObjectName
119
Using Components Override Standard Actions with Lightning Components
However, there are important differences from Visualforce in how you create Lightning components that can be used as action overrides,
and significant differences in how Salesforce uses them. You’ll want to read the details thoroughly before you get started, and test
carefully in your sandbox or Developer Edition org before deploying to production.
IN THIS SECTION:
Standard Actions and Overrides Basics
There are six standard actions available on most standard and all custom objects: Tab, List, View, Edit, New, and Delete. In Salesforce
Classic, these are all distinct actions.
Override a Standard Action with a Lightning Component
You can override a standard action with a Lightning component in both Lightning Experience and mobile.
Creating a Lightning Component for Use as an Action Override
Add the lightning:actionOverride interface to a Lightning component to allow it to be used as an action override in
Lightning Experience or the Salesforce mobile app. Only components that implement this interface appear in the Lightning
component menu of an object action Override Properties panel.
Packaging Action Overrides
Action overrides for custom objects are automatically packaged with the custom object. Action overrides for standard objects can’t
be packaged.
SEE ALSO:
lightning:actionOverride
120
Using Components Override Standard Actions with Lightning Components
Note:
• “n/a” doesn’t mean you can’t access the standard behavior, and it doesn’t mean you can’t override the standard behavior. It
means you can’t access the override. It’s the override’s functionality that’s not available.
• There are two additional standard actions, Accept and Clone. These actions are more complex, and overriding them is an
advanced project. Overriding them with Lightning components isn’t supported.
How and Where You Can Use Lightning Component Action Overrides
Lightning components can be used to override the View, New, New Event, Edit, and Tab standard actions in Lightning Experience and
the Salesforce mobile app. You can use a Lightning component as an override in Lightning Experience and mobile, but not Salesforce
Classic.
121
Using Components Override Standard Actions with Lightning Components
Note: Users won’t see changes to action overrides until they reload Lightning Experience or the Salesforce mobile app.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Salesforce Help: Override Standard Buttons and Tab Home Pages
<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2><span class="slds-text-heading_small">Expense Details</span></h2>
</div>
</header>
<div class="slds-no-flex">
<lightning:button label="Edit" onclick="{!c.handleEdit}"/>
</div>
</div>
<div class="slds-card__body">(expense details go here)</div>
</article>
</aura:component>
In Lightning Experience, the standard Tab and View actions display as a page, while the standard New and Edit actions display in an
overlaid panel. When used as action overrides, Lightning components that implement the lightning:actionOverride interface
replace the standard behavior completely. However, overridden actions always display as a page, not as a panel. Your component displays
without controls, except for the main Lightning Experience navigation bar. Your component is expected to provide a complete user
interface for the action, including navigation or actions beyond the navigation bar.
One important difference from Visualforce that’s worth noting is how components are added to the Lightning component menu. The
Visualforce page menu lists pages that either use the standard controller for the specific object, or that don’t use a standard controller
at all. This filtering means that the menu options vary from object to object, and offer only pages that are specific to the object, or
completely generic.
The Lightning component menu includes every component that implements the lightning:actionOverride interface. A
component that implements lightning:actionOverride can’t restrict an admin to overriding only certain actions, or only
for certain objects. We recommend that your organization adopt processes and component naming conventions to ensure that
components are used to override only the intended actions on intended objects. Even so, it’s your responsibility as the component
122
Using Components Get Your Lightning Components Ready to Use on Lightning
Pages
developer to ensure that components that implement the lightning:actionOverride interface gracefully respond to being
used with any action on any object.
SEE ALSO:
force:hasRecordId
force:hasSObjectName
SEE ALSO:
Override a Standard Action with a Lightning Component
Metadata API Developer Guide : ActionOverride
123
Using Components Configure Components for Lightning Pages and the Lightning
App Builder
IN THIS SECTION:
Configure Components for Lightning Pages and the Lightning App Builder
There are a few steps to take before you can use your custom Lightning components in either Lightning pages or the Lightning App
Builder.
Configure Components for Lightning Experience Record Pages
After your component is set up to work on Lightning pages and in the Lightning App Builder, use these guidelines to configure the
component so it works on record pages in Lightning Experience.
Create Components for Lightning for Outlook and Lightning for Gmail
Create custom Lightning components that are available for drag-and-drop in the Email Application Pane for Lightning for Outlook
and Lightning for Gmail.
Create Dynamic Picklists for Your Custom Components
You can expose a component property as a picklist when the component is configured in the Lightning App Builder. The picklist’s
values are provided by an Apex class that you create.
Create a Custom Lightning Page Template Component
Every standard Lightning page is associated with a default template component, which defines the page’s regions and what
components the page includes. Custom Lightning page template components let you create page templates to fit your business
needs with the structure and components that you define. Once implemented, your custom template is available in the Lightning
App Builder’s new page wizard for your page creators to use.
Lightning Page Template Component Best Practices
Keep these best practices and limitations in mind when creating Lightning page template components.
Make Your Lightning Page Components Width-Aware with lightning:flexipageRegionInfo
When you add a component to a region on a page in the Lightning App Builder, the lightning:flexipageRegionInfo
sub-component passes the width of that region to its parent component. With lightning:flexipageRegionInfo and
some strategic CSS, you can tell the parent component to render in different ways in different regions at runtime.
Tips and Considerations for Configuring Components for Lightning Pages and the Lightning App Builder
Keep these guidelines in mind when creating components and component bundles for Lightning pages and the Lightning App
Builder.
Configure Components for Lightning Pages and the Lightning App Builder
There are a few steps to take before you can use your custom Lightning components in either Lightning pages or the Lightning App
Builder.
124
Using Components Configure Components for Lightning Pages and the Lightning
App Builder
Interface Description
flexipage:availableForAllPageTypes Makes your component available for record pages and any other
type of page, including a Lightning app’s utility bar.
<div style="box">
<span class="greeting">{!v.greeting}</span>, {!v.subject}!
</div>
</aura:component>
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your own
org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a Community
Builder user in another org.
125
Using Components Configure Components for Lightning Experience Record Pages
Here’s a simple red circle SVG resource to go with the “Hello World” component.
<?xml version="1.0"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg xmlns="http://www.w3.org/2000/svg"
width="400" height="400">
<circle cx="100" cy="100" r="50" stroke="black"
stroke-width="5" fill="red" />
</svg>
SEE ALSO:
Lightning Component Bundle Design Resources
Tips and Considerations for Configuring Components for Lightning Pages and the Lightning App Builder
Component Bundles
Interface Reference
Note: If your managed component implements the flexipage or forceCommunity interfaces, its upload is blocked if
the component and its attributes aren’t set to access="global". For more information on access checks, see Controlling
Access.
force:hasRecordId
Useful for components invoked in a context associated with a specific record, such as record page components or custom object actions.
Add this interface if you want your component to receive the ID of the currently displaying record.
The force:hasRecordId interface does two things to a component that implements it.
• It adds an attribute named recordId to your component. This attribute is of type String, and its value is an 18-character Salesforce
record ID, for example: 001xx000003DGSWAA4. If you added it yourself, the attribute definition would look like the following markup:
<aura:attribute name="recordId" type="String" />
126
Using Components Create Components for Lightning for Outlook and Lightning
for Gmail
Note: If your component implements force:hasRecordId, you don’t need to add a recordId attribute to the
component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a
runtime error.
• When your component is invoked in a record context in Lightning Experience or the Salesforce app, the recordId is set to the
ID of the record being viewed.
Don’t expose the recordId attribute to the Lightning App Builder—don’t put it in the component’s design resource. You don’t want
admins supplying a record ID.
The recordId attribute is set only when you place or invoke the component in an explicit record context. For example, when you
place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home. In all
other cases, such as when you invoke the component as a global action, or create the component programmatically inside another
component, recordId isn’t set, and your component shouldn’t depend on it.
force:hasSObjectName
Useful for record page components. Implement this interface if your component needs to know the API name of the object of the
currently displaying record.
This interface adds an attribute named sObjectName to your component. This attribute is of type String, and its value is the API
name of an object, such as Account or myNamespace__myObject__c. For example:
<aura:attribute name="sObjectName" type="String" />
Note: If your component implements force:hasSObjectName, you don’t need to add an sObjectName attribute to
the component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a
runtime error.
The sObjectName attribute is set only when you place or invoke the component in an explicit record context. For example, when
you place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home.
In all other cases, such as when you invoke the component as a global action, or create the component programmatically inside another
component, sObjectName isn’t set, and your component shouldn’t depend on it.
SEE ALSO:
Configure Components for Lightning Pages and the Lightning App Builder
Tips and Considerations for Configuring Components for Lightning Pages and the Lightning App Builder
Working with Salesforce Records
force:hasRecordId
force:hasSObjectName
Create Components for Lightning for Outlook and Lightning for Gmail
Create custom Lightning components that are available for drag-and-drop in the Email Application Pane for Lightning for Outlook and
Lightning for Gmail.
To add a component to email application panes in Lightning for Outlook or Lightning for Gmail, implement the
clients:availableForMailAppAppPage interface.
To allow the component access to email or calendar events, implement the clients:hasItemContext interface.
The clients:hasItemContext interface adds attributes to your component that it can use to implement record- or context-specific
logic. The attributes included are:
127
Using Components Create Components for Lightning for Outlook and Lightning
for Gmail
• The source attribute, which indicates the email or appointment source. Possible values include email and event.
<aura:attribute name="source" type="String" />
• The mode attribute, which indicates viewing or composing an email or event. Possible values include view and edit.
<aura:attribute name="mode" type="String" />
• The people attribute indicates recipients’ email addresses on the current email or appointment.
<aura:attribute name="people" type="Object" />
The shape of the people attribute changes according to the value of the source attribute.
When the source attribute is set to email, the people object contains the following elements.
{
to: [ { name: nameString, email: emailString }, ... ],
cc: [ ... ],
from: [ { name: senderName, email: senderEmail } ],
}
When the source attribute is set to event, the people object contains the following elements.
{
requiredAttendees: [ { name: attendeenameString, email: emailString }, ... ],
optionalAttendees: [ { name: optattendeenameString, email: emailString }, ... ],
organizer: [ { name: organizerName, email: senderEmail } ],
}
To provide the component with an event’s date or location, implement the clients:hasEventContext interface.
dates: {
"start": value (String),
"end": value (String),
}
Lightning for Outlook and Lightning for Gmail don’t support the following events:
• force:navigateToList
• force:navigateToRelatedList
• force:navigateToObjectHome
• force:refreshView
Note: To ensure that custom components appear correctly in Lightning for Outlook or Lightning for Gmail, enable them to adjust
to variable widths.
128
Using Components Create Components for Lightning for Outlook and Lightning
for Gmail
IN THIS SECTION:
Sample Custom Components for Lightning for Outlook and Lightning for Gmail
Review samples of custom Lightning components that you can implement in the Email Application Pane for Lightning for Outlook
and Lightning for Gmail.
Sample Custom Components for Lightning for Outlook and Lightning for Gmail
Review samples of custom Lightning components that you can implement in the Email Application Pane for Lightning for Outlook and
Lightning for Gmail.
Here’s an example of a custom Lightning Component you can include in your email application pane for Lightning for Outlook or
Lightning for Gmail. This component leverages the context of the selected email or appointment.
<aura:component implements="clients:availableForMailAppAppPage,clients:hasItemContext">
<!--
Add these handlers to customize what happens when the attributes change
<aura:handler name="change" value="{!v.subject}" action="{!c.handleSubjectChange}" />
<div id="content">
<aura:if isTrue="{!v.mode == 'edit'}">
You are composing the following Item: <br/>
<aura:set attribute="else">
You are reading the following Item: <br/>
</aura:set>
</aura:if>
<h1><b>Email subject</b></h1>
<span id="subject">{!v.subject}</span>
<h1>To:</h1>
<aura:iteration items="{!v.people.to}" var="to">
{!to.name} - {!to.email} <br/>
</aura:iteration>
<h1>From:</h1>
{!v.people.from.name} - {!v.people.from.email}
<h1>CC:</h1>
<aura:iteration items="{!v.people.cc}" var="cc">
{!cc.name} - {!cc.email} <br/>
</aura:iteration>
In this example, the custom component displays account and opportunity information based on the email recipients’ email addresses.
The component calls a JavaScript controller function, handlePeopleChange(), on initialization. The JavaScript controller calls
129
Using Components Create Components for Lightning for Outlook and Lightning
for Gmail
methods on an Apex server-side controller to query the information and compute the accounts ages and opportunities days until closing.
The Apex controller, JavaScript controller, and helper are listed next.
<!--
This component handles the email context on initialization.
It retrieves accounts and opportunities based on the email addresses included
in the email recipients list.
It then calculates the account and opportunity ages based on when the accounts
were created and when the opportunities will close.
-->
<aura:component
implements="clients:availableForMailAppAppPage,clients:hasItemContext"
controller="ComponentController">
</aura:component>
/*
On the server side, the Apex controller includes
Aura-enabled methods that accept a list of emails as parameters.
*/
130
Using Components Create Components for Lightning for Outlook and Lightning
for Gmail
/*
This method searches for OpportunityContactRoles with matching emails
in the email list.
Then, it calculates the number of days until closing to return a list
of objects to use on the client side.
*/
@AuraEnabled
public static List<Map<String, Object>> findOpportunityCloseDateTime(List<String>
emails) {
List<Map<String, Object>> ret = new List<Map<String, Object>>();
List<OpportunityContactRole> contacts =
[SELECT Opportunity.Name, Opportunity.CloseDate
FROM OpportunityContactRole
WHERE isPrimary=true AND Contact.Email IN :emails];
for (OpportunityContactRole c: contacts) {
Map<String, Object> item = new Map<String, Object>();
item.put('name', c.Opportunity.Name);
item.put('closesIn',
System.Date.today().daysBetween(
Date.valueOf(c.Opportunity.CloseDate)));
ret.add(item);
}
return ret;
}
}
({
/*
This JavaScript controller is called on component initialization and relies
on the helper functionality to build a list of email addresses from the
available people. It then makes a caller to the server to run the actions to
display information.
Once the server returns the values, it sets the appropriate values to display
on the client side.
*/
handlePeopleChange: function(component, event, helper){
var people = component.get("v.people");
var peopleEmails = helper.filterEmails(people);
var action = component.get("c.findOpportunityCloseDateTime");
action.setParam("emails", peopleEmails);
action.setCallback(this, function(response){
var state = response.getState();
if(state === "SUCCESS"){
component.set("v.opportunities", response.getReturnValue());
} else{
component.set("v.opportunities",[]);
}
});
$A.enqueueAction(action);
131
Using Components Create Dynamic Picklists for Your Custom Components
action.setCallback(this, function(response){
var state = response.getState();
if(state === "SUCCESS"){
component.set("v.accounts", response.getReturnValue());
} else{
component.set("v.accounts",[]);
}
});
$A.enqueueAction(action);
}
})
({
/*
This helper function filters emails from objects.
*/
filterEmails : function(people){
return this.getEmailsFromList(people.to).concat(
this.getEmailsFromList(people.cc));
},
getEmailsFromList : function(list){
var ret = [];
for (var i in list) {
ret.push(list[i].email);
}
return ret;
}
})
132
Using Components Create a Custom Lightning Page Template Component
myValues.addRow(value1);
myValues.addRow(value2);
return myValues;
}
}
Note: Although VisualEditor.DataRow allows you to specify any Object as its value, you can specify a datasource only
for String attributes. The default implementation for isValid() and getLabel() assumes that the object passed in the
parameter is a String for comparison.
For more information on the VisualEditor.DynamicPickList abstract class, see the Apex Developer Guide.
Note: My Domain must be enabled in your org before you can use custom template components in the Lightning App Builder.
133
Using Components Create a Custom Lightning Page Template Component
Custom Lightning page template components are supported for record pages, app pages, and Home pages. Each page type has a
different interface that the template component must implement.
• lightning:appHomeTemplate
• lightning:homeTemplate
• lightning:recordHomeTemplate
Important: Each template component should implement only one template interface. Template components shouldn’t implement
any other type of interface, such as flexipage:availableForAllPageTypes or force:hasRecordId. A template
component can’t multi-task as a regular Lightning component. It’s either a template, or it’s not.
Note: The Aura.Component[] attribute is interpreted as a region only if it’s also specified as a region in the design resource.
Here’s an example of a two-column app page template .cmp resource that uses the lightning:layout component and the
Salesforce Lightning Design System (SLDS) for styling.
When the template is viewed on a desktop, its right column takes up 30% (4 SLDS columns), and the left column takes up the remaining
70% of the page width. On non-desktop form factors, the columns display as 50/50.
<aura:component implements="lightning:appHomeTemplate" description="Main column
and right sidebar. On a phone, the regions are of equal width">
<aura:attribute name="left" type="Aura.Component[]" />
<aura:attribute name="right" type="Aura.Component[]" />
<div>
<lightning:layout horizontalAlign="spread">
<lightning:layoutItem flexibility="grow"
class="slds-m-right_small">
{!v.left}
</lightning:layoutItem>
<lightning:layoutItem size="{! $Browser.isDesktop ? '4' : '6' }"
class="slds-m-left_small">
{!v.right}
</lightning:layoutItem>
</lightning:layout>
</div>
</aura:component>
The description attribute on the aura:component tag is optional, but recommended. If you define a description, it displays
as the template description beneath the template image in the Lightning App Builder new page wizard.
134
Using Components Create a Custom Lightning Page Template Component
Attribute Description
name The name of an attribute in the .cmp resource marked type Aura.Component[]. Flags the
attribute as a region.
defaultWidth Specifies the default width of the region. This attribute is required for all regions. Valid values are:
Small, Medium, Large, and Xlarge.
flexipage:formFactor
Use this tag to specify how much space the component takes on the page based on the type of device that it renders on. This tag
should be specified as a child of the flexipage:region tag. Use multiple flexipage:formFactor tags per
flexipage:region to define flexible behavior across form factors.
Attribute Description
type The type of form factor or device the template renders on, such as a desktop or tablet. Valid values
are: Medium (tablet), and Large (desktop). Because the only reasonable width value for a
Small form factor (phone) is Small, you don’t have to specify a Small type. Salesforce
takes care of that association automatically.
width The available size of the area that the component in this region has to render in. Valid values are:
Small, Medium, Large, and Xlarge.
For example, in this code snippet, the region has a large width to render in when the template is rendered on a large form factor,
and a small width to render in when the template is rendered on a medium form factor.
<flexipage:region name="right" defaultWidth="Large">
<flexipage:formFactor type="Large" width="Large" />
<flexipage:formFactor type="Medium" width="Small" />
</flexipage:region>
Tip: You can use the lightning:flexipageRegionInfo sub-component to pass region width information to a
component, which lets you configure your page components to render differently based on what size region they display in.
Here’s the design file that goes with the sample .cmp resource. The label text in the design file displays as the name of the template in
the new page wizard.
<design:component label="Two Column Custom App Page Template">
<flexipage:template >
<!-- The default width for the "left" region is "MEDIUM". In tablets,
the width is "SMALL" -->
<flexipage:region name="left" defaultWidth="MEDIUM">
<flexipage:formfactor type="MEDIUM" width="SMALL" />
</flexipage:region>
<flexipage:region name="right" defaultWidth="SMALL" />
135
Using Components Lightning Page Template Component Best Practices
</flexipage:template>
</design:component>
We recommend that your SVG resource be no larger than 150KB, and no more than 160px high and 560px wide.
SEE ALSO:
Lightning Page Template Component Best Practices
Make Your Lightning Page Components Width-Aware with lightning:flexipageRegionInfo
Lightning Components Developer Guide: lightning:layout
136
Using Components Make Your Lightning Page Components Width-Aware with
lightning:flexipageRegionInfo
• Using getters to get the regions as variables works at design time but not at run time. Here’s an example of what we mean.
<aura:component implements="lightning:appHomeTemplate">
<aura:attribute name="region" type="Aura.Component[]" />
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<div>
{!v.region}
</div>
</aura:component>
{
init : function(component, event, helper) {
var region = cmp.get('v.region'); // This will fail at run time.
...
}
}
• You can remove regions from a template as long as it’s not being used by a Lightning page, and as long as it’s not set to access=global.
You can add regions at any time.
• A region can be used more than once in the code, but only one instance of the region should render at run time.
• A template component can contain up to 25 regions.
137
Using Components Make Your Lightning Page Components Width-Aware with
lightning:flexipageRegionInfo
Valid region width values are: Small, Medium, Large, and Xlarge.
You can use CSS to style your component and to help determine how your component renders. Here’s an example.
This simple component has two fields, field1 and field2. The component renders with the fields side by side, filling 50% of the region’s
available width when not in a small region. When the component is in a small region, the fields render as a list, using 100% of the region’s
width.
<aura:component implements="flexipage:availableForAllPageTypes">
<aura:attribute name="width" type="String"/>
<lightning:flexipageRegionInfo width="{!v.width}"/>
<div class="{! 'container' + (v.width=='SMALL'?' narrowRegion':'')}">
<div class="{! 'eachField f1' + (v.width=='SMALL'?' narrowRegion':'')}">
<lightning:input name="field1" label="First Name"/>
</div>
<div class="{! 'eachField f2' + (v.width=='SMALL'?' narrowRegion':'')}">
<lightning:input name="field2" label="Last Name"/>
</div>
</div>
</aura:component>
138
Using Components Tips and Considerations for Configuring Components for
Lightning Pages and the Lightning App Builder
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your own
org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a Community
Builder user in another org.
Components
• Set a friendly name for the component using the label attribute in the element in the design file, such as <design:component
label="foo">.
• Design your components to fill 100% of the width (including margins) of the region that they display in.
• Components must provide an appropriate placeholder behavior in declarative tools if they require interaction.
• A component must never display a blank box. Think of how other sites work. For example, Facebook displays an outline of the feed
before the actual feed items come back from the server. This improves the user’s perception of UI responsiveness.
• If the component depends on a fired event, then give it a default state that displays before the event fires.
• Style components in a manner consistent with the styling of Lightning Experience and consistent with the Salesforce Design System.
• If you don’t have My Domain enabled in your org and you activate a Lightning page that contains a custom component, the
component is dropped from the page at runtime.
Attributes
• Use the design file to control which attributes are exposed to the Lightning App Builder.
• Make your attributes easy to use and understandable to an administrator. Don’t expose SOQL queries, JSON objects, or Apex class
names.
• Give your required attributes default values. When a component that has required attributes with no default values is added to the
App Builder, it appears invalid, which is a poor user experience.
• Use basic supported types (string, integer, boolean) for any exposed attributes.
• Specify a min and max attribute for integer attributes in the <design:attribute> element to control the range of accepted
values.
• String attributes can provide a datasource with a set of predefined values allowing the attribute to expose its configuration as a
picklist.
• Give all attributes a label with a friendly display name.
• Provide descriptions to explain the expected data and any guidelines, such as data format or expected range of values. Description
text appears as a tooltip in the Property Editor.
• To delete a design attribute for a component that implements the flexipage:availableForAllPageTypes or
forceCommunity:availableForAllPageTypes interface, first remove the interface from the component before
deleting the design attribute. Then re-implement the interface. If the component is referenced in a Lightning page, you must remove
the component from the page before you can change it.
139
Using Components Use Lightning Components in Community Builder
Limitations
The Lightning App Builder doesn’t support the Map, Object, or java:// complex types.
SEE ALSO:
Configure Components for Lightning Pages and the Lightning App Builder
Configure Components for Lightning Experience Record Pages
IN THIS SECTION:
Configure Components for Communities
Make your custom Lightning components available for drag and drop in the Lightning Components pane in Community Builder.
Create Custom Theme Layout Components for Communities
Create a custom theme layout to transform the appearance and overall structure of the pages in the Customer Service (Napili)
template.
Create Custom Search and Profile Menu Components for Communities
Create custom components to replace the Customer Service (Napili) template’s standard Profile Header and Search & Post Publisher
components in Community Builder.
Create Custom Content Layout Components for Communities
Community Builder includes several ready-to-use layouts that define the content regions of your page, such as a two-column layout
with a 2:1 ratio. However, if you need a layout that’s customized for your community, create a custom content layout component
to use when building new pages in Community Builder. You can also update the content layout of the default pages that come with
your community template.
<div style="box">
<span class="greeting">{!v.greeting}</span>, {!v.subject}!
</div>
</aura:component>
140
Using Components Create Custom Theme Layout Components for Communities
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your own
org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a Community
Builder user in another org.
Next, add a design resource to your component bundle. A design resource describes the design-time behavior of a Lightning
component—information that visual tools need to allow adding the component to a page or app. It contains attributes that are available
for administrators to edit in Community Builder.
Adding this resource is similar to adding it for the Lightning App Builder. For more information, see Configure Components for Lightning
Pages and the Lightning App Builder.
Important: When you add custom components to your community, they can bypass the object- and field-level security (FLS)
you set for the guest user profile. Lightning components don’t automatically enforce CRUD and FLS when referencing objects or
retrieving the objects from an Apex controller. This means that the framework continues to display records and fields for which
users don’t have CRUD permissions and FLS visibility. You must manually enforce CRUD and FLS in your Apex controllers.
SEE ALSO:
Component Bundles
Standard Design Tokens for Communities
A theme layout type categorizes the pages in your community that share the same theme layout.
When you create a custom theme layout component in the Developer Console, it appears in Community Builder in the Settings >
Theme area. Here you can assign it to new or existing theme layout types. Then you apply the theme layout type—and thereby the
theme layout—in the page’s properties.
141
Using Components Create Custom Theme Layout Components for Communities
Tip: If you create a custom profile menu or a search component, declaring the attribute name value also lets users select the
custom component when using your theme layout.
Here’s the sample code for a simple theme layout.
<aura:component implements="forceCommunity:themeLayout" access="global" description="Sample
Custom Theme Layout">
<aura:attribute name="search" type="Aura.Component[]" required="false"/>
<aura:attribute name="profileMenu" type="Aura.Component[]" required="false"/>
<aura:attribute name="navBar" type="Aura.Component[]" required="false"/>
<aura:attribute name="newHeader" type="Aura.Component[]" required="false"/>
<div>
<div class="searchRegion">
{!v.search}
</div>
<div class="profileMenuRegion">
{!v.profileMenu}
</div>
<div class="navigation">
{!v.navBar}
</div>
<div class="newHeader">
{!v.newHeader}
</div>
<div class="mainContentArea">
{!v.body}
</div>
</div>
</aura:component>
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your own
org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a Community
Builder user in another org.
142
Using Components Create Custom Search and Profile Menu Components for
Communities
The design resource only exposes the properties. You must implement the properties in the component.
<aura:component implements="forceCommunity:themeLayout" access="global" description="Small
Header">
<aura:attribute name="blueBackground" type="Boolean" default="false"/>
<aura:attribute name="smallLogo" type="Boolean" default="false" />
...
SEE ALSO:
Create Custom Search and Profile Menu Components for Communities
forceCommunity:navigationMenuBase
Salesforce Help: Custom Theme Layouts and Theme Layout Types
143
Using Components Create Custom Content Layout Components for Communities
forceCommunity:profileMenuInterface
Add the forceCommunity:profileMenuInterface interface to a Lightning component to allow it to be used as a custom
profile menu component for the Customer Service (Napili) community template. After you create a custom profile menu component,
admins can select it in Community Builder in Settings > Theme to replace the template’s standard Profile Header component.
Here’s the sample code for a simple profile menu component.
<aura:component implements="forceCommunity:profileMenuInterface" access="global">
<aura:attribute name="options" type="String[]" default="Option 1, Option 2"/>
<ui:menu >
<ui:menuTriggerLink aura:id="trigger" label="Profile Menu"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<aura:iteration items="{!v.options}" var="itemLabel">
<ui:actionMenuItem label="{!itemLabel}" click="{!c.handleClick}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
</aura:component>
forceCommunity:searchInterface
Add the forceCommunity:searchInterface interface to a Lightning component to allow it to be used as a custom search
component for the Customer Service (Napili) community template. After you create a custom search component, admins can select it
in Community Builder in Settings > Theme to replace the template’s standard Search & Post Publisher component.
Here’s the sample code for a simple search component.
<aura:component implements="forceCommunity:searchInterface" access="global">
<div class="search">
<div class="search-wrapper">
<form class="search-form">
<div class="search-input-wrapper">
<input class="search-input" type="text" placeholder="My Search"/>
</div>
<input type="hidden" name="language" value="en" />
</form>
</div>
</div>
</aura:component>
SEE ALSO:
Create Custom Theme Layout Components for Communities
forceCommunity:navigationMenuBase
Salesforce Help: Custom Theme Layouts and Theme Layout Types
144
Using Components Create Custom Content Layout Components for Communities
When you create a custom content layout component in the Developer Console, it appears in Community Builder in the New Page and
the Change Layout dialog boxes.
<div class="container">
<div class="contentPanel">
<div class="left">
{!v.column1}
</div>
<div class="right">
{!v.column2}
</div>
</div>
</div>
</aura:component>
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your own
org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a Community
Builder user in another org.
.THIS .contentPanel:before,
.THIS .contentPanel:after {
content: " ";
display: table;
}
.THIS .contentPanel:after {
clear: both;
}
.THIS .left {
float: left;
width: 50%;
}
.THIS .right {
float: right;
145
Using Components Use Lightning Components with Flows
width: 50%;
}
SEE ALSO:
Component Bundles
Standard Design Tokens for Communities
IN THIS SECTION:
Customize Flow Screens By Using Lightning Components
To use a custom Lightning component in flow screens, configure the component and its design resource so that they’re compatible
with the Cloud Flow Designer.
Working with the Flow Lightning Component
Once you embed a flow in a Lightning component, use JavaScript and Apex code to configure the flow at run time. For example,
pass values into the flow or to control what happens when the flow finishes. lightning:flow supports only screen flows and
autolaunched flows.
Display Flow Stages with a Lightning Component
If you've added stages to your flow, display them to flow users with a Lightning component, such as
lightning:progressindicator.
IN THIS SECTION:
Considerations for Configuring Components for Flow Screens
When you create Lightning components for flow screens, understand which data types are supported and how to work with attributes.
146
Using Components Customize Flow Screens By Using Lightning Components
SEE ALSO:
lightning:availableForFlowScreens
lightning:availableForFlowScreens
Attributes
• In a design:attribute node, the Cloud Flow Designer supports only the name, label, and description attributes. The other
attributes are ignored.
147
Using Components Customize Flow Screens By Using Lightning Components
• To validate min and max lengths for a component attribute, create logic in your flow or component. For example, validate the length
of the values by using a flow formula or the component's controller.
• To edit or delete a design attribute for a component that implements the lightning:availableForFlowScreens
interface, remove the use of the attribute in all flow versions and then make your changes.
SEE ALSO:
lightning:availableForFlowScreens
<div style="box">
<span class="greeting">{!v.greeting}</span>, {!v.subject}!
</div>
</aura:component>
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your own
org. For example, if you want a component to be usable by a flow admin in another org.
Next, add a design resource to your component bundle. A design resource describes the design-time behavior of a Lightning
component—information that visual tools need to allow adding the component to a page or app. It contains attributes that are available
for admins to edit in the Cloud Flow Designer.
Adding this resource is similar to adding it for the Lightning App Builder.
SEE ALSO:
lightning:availableForFlowScreens
Control Flow Navigation from a Lightning Component
IN THIS SECTION:
Flow Navigation Actions
The availableActions attribute lists the valid navigation actions for that screen.
148
Using Components Customize Flow Screens By Using Lightning Components
SEE ALSO:
lightning:availableForFlowScreens
lightning:availableForFlowScreens
PAUSE Pause Saves the interview in its current state to the database, so that the user can resume it later
FINISH Finish Finishes the interview. This action is available only before the final screen in the flow.
SEE ALSO:
lightning:availableForFlowScreens
Example: This component (c:flowFooter) customizes the default flow footer in two ways.
• It swaps the Pause and Previous buttons, so that Previous floats to the left and Pause floats to the right with Next or Finish.
149
Using Components Customize Flow Screens By Using Lightning Components
c:flowFooter Component
Since the component implements lightning:availableForFlowScreens, it has access to the availableActions
attribute, which contains the valid actions for the screen. The declared attributes, like canPause and canBack, determine
which buttons to display. Those attributes are set by the JavaScript controller when the component initializes.
<aura:component access="global" implements="lightning:availableForFlowScreens">
c:flowFooter Controller
The init function loops through the screen's available actions and determines which buttons the component should show.
When the user clicks one of the buttons in the footer, the onButtonPressed function calls the navigateFlow action to
perform that action.
({
init : function(cmp, event, helper) {
150
Using Components Customize Flow Screens By Using Lightning Components
c:flowFooter Component
In your component, before the handler:
• Define an attribute to pass the screen's available actions from the parent component
• Register an event to pass the navigateFlow action to the parent component
<aura:attribute name="availableActions" type="String[]" />
<aura:registerEvent name="navigateFlowEvent" type="c:navigateFlow"/>
c:flowFooter Controller
Since navigateFlow is only available in the parent component, the onButtonPressed function fails. Update the
onButtonPressed function so that it fires navigateFlowEvent instead.
151
Using Components Customize Flow Screens By Using Lightning Components
c:flowParent Component
In the parent component's markup, pass availableActions into the child component's availableActions attribute
and the handleNavigate function into the child component's navigateFlowEvent event.
<c:flowFooter availableActions="{!v.availableActions}"
navigateFlowEvent="{!c.handleNavigate}"/>
c:flowParent Controller
When navigateFlowEvent fires in the child component, the handleNavigate function calls the parent component’s
navigateFlow action, using the action selected in the child component.
SEE ALSO:
lightning:availableForFlowScreens
Customize the Flow Header with a Lightning Component
Dynamically Update a Flow Screen with a Lightning Component
lightning:availableForFlowScreens
Example: This component (c:choiceNavigation) displays a script and a choice in the form of buttons.
152
Using Components Customize Flow Screens By Using Lightning Components
c:choiceNavigation Component
c:choiceNavigation Design
The design resource includes the scriptText attribute, so you can set the script from the flow.
<design:component>
<design:attribute name="scriptText" label="Script Text"
description="What the agent should say to the customer" />
</design:component>
c:choiceNavigation Style
.THIS.script-container {
border: t(borderWidthThick) solid t(colorBorderBrand);
border-radius: t(borderRadiusMedium);
}
.THIS .script {
font-size: 1.125rem; /*t(fontSizeTextLarge)*/
font-weight: t(fontWeightRegular);
153
Using Components Customize Flow Screens By Using Lightning Components
line-height: t(lineHeightHeading);
}
c:choiceNavigation Controller
When the user clicks either of the buttons, the JavaScript controller calls navigateFlow(“NEXT”), which is the equivalent
of the user clicking Next.
({
handleChange : function(component, event, helper) {
// When an option is selected, navigate to the next screen
var response = event.getSource().getLocalId();
component.set("v.value", response);
var navigate = component.get("v.navigateFlow");
navigate("NEXT");
}
})
defaultTokens.tokens
The script in c:choiceNavigation uses tokens to stay in sync with the Salesforce Lightning Design System styles.
<aura:tokens extends="force:base" >
</aura:tokens>
SEE ALSO:
lightning:availableForFlowScreens
Example: Instead of displaying the flow title and the help button, this component (c:flowHeader) displays the company
logo and the help button. The help text appears in a tooltip when the user hovers, instead of in a modal when the user clicks.
c:flowHeader Component
Since the component implements lightning:availableForFlowScreens, it has access to the screenHelpText
attribute, which contains the screen's help text if it has any.
<aura:component access="global" implements="lightning:availableForFlowScreens">
154
Using Components Customize Flow Screens By Using Lightning Components
SEE ALSO:
lightning:availableForFlowScreens
Customize the Flow Footer with a Lightning Component
Dynamically Update a Flow Screen with a Lightning Component
lightning:availableForFlowScreens
Example: This component (c:flowDynamicScreen) displays a custom script component and a group of radio buttons.
The component gets the contact's existing phone number from the flow, and uses that value to fill in the script.
If the user selects the No radio button, the component displays an input field, where the user can enter the new phone number.
155
Using Components Customize Flow Screens By Using Lightning Components
c:flowDynamicScreen Component
c:flowDynamicScreen Style
.THIS.script-container {
border: t(borderWidthThick) solid t(colorBorderBrand);
border-radius: t(borderRadiusMedium);
}
.THIS .script {
font-size: 1.125rem; /*t(fontSizeTextLarge)*/
font-weight: t(fontWeightRegular);
156
Using Components Working with the Flow Lightning Component
line-height: t(lineHeightHeading);
}
c:flowDynamicScreen Controller
When the user tabs out, or otherwise removes focus from the Phone field, the controller sets the newPhone attribute to the
input value, so that you can reference the new number in the flow.
({
handleNewPhone: function(cmp, event, helper) {
cmp.set("v.newPhone", cmp.find('phone_updated').get('v.value'));
}
})
defaultTokens.tokens
The script in c:flowDynamicScreen uses tokens to stay in sync with the Salesforce Lightning Design System styles.
<aura:tokens extends="force:base" >
</aura:tokens>
SEE ALSO:
lightning:availableForFlowScreens
Customize the Flow Header with a Lightning Component
Customize the Flow Footer with a Lightning Component
lightning:availableForFlowScreens
({
init : function (component) {
// Find the component whose aura:id is "flowData"
var flow = component.find("flowData");
// In that component, start your flow. Reference the flow's Unique Name.
flow.startFlow("myFlow");
},
})
157
Using Components Working with the Flow Lightning Component
Note: When a user opens a page that has a flow component, such as Lightning App Builder or an active Lightning page, the flow
runs when the page loads. Make sure that the flow doesn’t perform any actions – such as create or delete records – before the
first screen.
IN THIS SECTION:
Get Flow Variable Values to a Lightning Component
Flow variable values can be displayed or referenced in a Lightning component. Once you’ve embedded your flow in a custom
Lightning component, use the onstatuschange action to get values from the flow's output variables. Output variables are
returned as an array.
Set Flow Variable Values from a Lightning Component
When you embed a flow in a Lightning component, give the flow more context by initializing its variables, sObject variables, collection
variables, or sObject collection variables. In the component's controller, create a list of maps, then pass that list to the startFlow
method.
Control a Flow’s Finish Behavior in a Lightning Component
By default, when a flow user clicks Finish, the component starts a new interview and the user sees the first screen of the flow again.
However, you can shape what happens when the flow finishes by using the onstatuschange action. To redirect to another
page, use one of the force:navigateTo* events such as force:navigateToObjectHome or
force:navigateToUrl.
Resume a Flow Interview from a Lightning Component
By default, users can resume their paused interviews from the Paused Interviews component on their home page. If you want to
customize how and where users can resume their interviews, pass the interview ID into the resumeFlow method in your JavaScript
controller.
SEE ALSO:
lightning:flow
Note: The variable must allow output access. For each flow variable, output access is controlled by:
• The Input/Output Type variable field in the Cloud Flow Designer
• The isInput field on FlowVariable in the Metadata API
If you reference a variable that doesn’t allow output access, attempts to get the variable are ignored.
Example: This example uses the JavaScript controller to pass the flow's accountName and numberOfEmployees variables into
attributes on the component. Then, the component displays those values in output components.
<aura:component>
<aura:attribute name="accountName" type="String" />
<aura:attribute name="numberOfEmployees" type="Decimal" />
158
Using Components Working with the Flow Lightning Component
({
init : function (component) {
// Find the component whose aura:id is "flowData"
var flow = component.find("flowData");
// In that component, start your flow. Reference the flow's Unique Name.
flow.startFlow("myFlow");
},
SEE ALSO:
lightning:flow
Note: You can set variables only at the beginning of an interview, and the variables you set must allow input access. For each
flow variable, input access is controlled by:
• The Input/Output Type variable field in the Cloud Flow Designer
• The isInput field on FlowVariable in the Metadata API
If you reference a variable that doesn’t allow input access, attempts to set the variable are ignored.
For each variable you set, provide the variable's name, type, and value. For type, use the flow data type.
159
Using Components Working with the Flow Lightning Component
{
name : "varName",
type : "flowDataType",
value : valueToSet
},
{
name : "varName",
type : "flowDataType",
value : [ value1, value2]
}, ...
Example: This JavaScript controller sets values for a number variable, a date collection variable, and a couple of sObject variables.
({
init : function (component) {
// Find the component whose aura:id is "flowData"
var flow = component.find("flowData");
var inputVariables = [
{ name : "numVar", type : "Number", value: 30 },
{ name : "dateColl", type : "String", value: [ "2016-10-27", "2017-08-01" ]
},
// Sets values for fields in the account sObject variable. Id uses the
// value of the component's accountId attribute. Rating uses a string.
{ name : "account", type : "SObject", value: {
"Id" : component.get("v.accountId"),
"Rating" : "Warm"
}
},
// Set the contact sObject variable to the value of the component's contact
// attribute. We're assuming the attribute contains the entire sObject for
// a contact record.
160
Using Components Working with the Flow Lightning Component
Example: Here's an example of a component that gets an account via an Apex controller. The Apex controller passes the data
to the flow's sObject variable through the JavaScript controller.
<aura:component controller="AccountController" >
<aura:attribute name="account" type="Account" />
<aura:handler name="init" value="{!this}" action="{!c.init}"/>
<lightning:flow aura:id="flowData"/>
</aura:component>
({
init : function (component) {
// Create action to find an account
var action = component.get("c.getAccount");
161
Using Components Working with the Flow Lightning Component
SEE ALSO:
lightning:flow
Note: To control what happens when an autolaunched flow finishes, check for the FINISHED_SCREEN status.
<aura:component access="global">
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<lightning:flow aura:id="flowData" onstatuschange="{!c.handleStatusChange}" />
</aura:component>
Example: This function redirects the user to a case created in the flow by using the force:navigateToSObject event.
handleStatusChange : function (component, event) {
if(event.getParam("status") === "FINISHED") {
var outputVariables = event.getParam("outputVariables");
var outputVar;
for(var i = 0; i < outputVariables.length; i++) {
outputVar = outputVariables[i];
if(outputVar.name === "redirect") {
var urlEvent = $A.get("e.force:navigateToSObject");
urlEvent.setParams({
"recordId": outputVar.value,
"isredirect": "true"
});
urlEvent.fire();
}
}
162
Using Components Working with the Flow Lightning Component
}
}
SEE ALSO:
lightning:flow
Example: This example show how you can resume an interview—or start a new one. When users click Survey Customer from
a contact record, the Lightning component does one of two things.
• If the user has any paused interviews for the Survey Customers flow, it resumes the first one.
• If the user doesn’t have any paused interviews for the Survey Customers flow, it starts a new one.
<aura:component controller="InterviewsController">
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<lightning:flow aura:id="flowData" />
</aura:component>
This Apex controller performs a SOQL query to get a list of paused interviews. If nothing is returned from the query,
getPausedId() returns a null value, and the component starts a new interview. If at least one interview is returned from the
query, the component resumes the first interview in that list.
public class InterviewsController {
@AuraEnabled
public static String getPausedId() {
// Get the ID of the running user
String currentUser = UserInfo.getUserId();
// Find all of that user's paused interviews for the Survey customers flow
List<FlowInterview> interviews =
[ SELECT Id FROM FlowInterview
WHERE CreatedById = :currentUser AND InterviewLabel LIKE '%Survey
customers%'];
163
Using Components Display Flow Stages with a Lightning Component
return interviews.get(0).Id;
}
}
If the JavaScript controller got an interview ID back from the Apex controller, the component resumes that interview. If the Apex
controller returned a null interview ID, the component starts a new interview.
({
init : function (component) {
//Create request for interview ID
var action = component.get("c.getPausedId");
action.setCallback(this, function(response) {
var interviewId = response.getReturnValue();
// Find the component whose aura:id is "flowData"
var flow = component.find("flowData");
// If an interview ID was returned, resume it in the component
// whose aura:id is "flowData".
if ( interviewId !== null ) {
flow.resumeFlow(interviewID);
}
// Otherwise, start a new interview in that component. Reference
// the flow's Unique Name.
else {
flow.startFlow("Survey_customers");
}
});
//Send request to be enqueued
$A.enqueueAction(action);
},
})
SEE ALSO:
lightning:flow
Note: This release contains a beta version of flow stages that is production quality but has known limitations. To provide feedback
and suggestions, go to IdeaExchange.
To add a progress indicator component to your flow, you have two options:
• Wrap the progress indicator with a lightning:flow component in a parent component.
<aura:component>
<lightning:progressindicator/>
<lightning:flow/>
</aura:component>
• Add the progress indicator to your flow screen directly, by using a Lightning component screen field.
It's easier to get labels for the active and current stages in a flow from the lightning:flow component.
164
Using Components Display Flow Stages with a Lightning Component
• Wrapper component: The onstatuschange action in the standard lightning:flow component returns the names
and labels for the flow's active stages and current stage.
• Lightning component screen field: You can only pass the fully resolved stage name into a Lightning component. If your flow is
namespaced, the fully resolved name is namespace.flowName:stageName. Otherwise, it'sflowName:stageName.
Depending on your naming convention, you can convert the stage names into labels by dropping the namespace and flow name,
then replacing underscores with spaces.
IN THIS SECTION:
Display Flow Stages by Wrapping a Progress Indicator
If you're tracking stages in your flow, display them at runtime by creating a custom component that wraps a progress indicator with
the lightning:flow component. Use the progress indicator to display the flow's active stages and current stage, and use the
lightning:flow component to display the flow's screens. To pass the flow's active stages and current stage to the progress
indicator, use the lightning:flow component's onstatuschange action.
Display Flow Stages By Adding a Progress Indicator to a Flow Screen
If you're tracking stages in your flow, display them at runtime by adding a custom component to the flow's screens. Create a progress
indicator component that displays the flow's active stages and current stage, and make sure that it's available as a Lightning
component screen field. When you add the component to each flow screen, pass the $Flow.ActiveStages and
$Flow.CurrentStage system variables into the component's attributes.
SEE ALSO:
Cloud Flow Designer Guide: Show Users Progress Through a Flow with Stages
Display Flow Stages By Adding a Progress Indicator to a Flow Screen
Note: This release contains a beta version of flow stages that is production quality but has known limitations. To provide feedback
and suggestions, go to IdeaExchange.
c:flowStages_global Component
165
Using Components Display Flow Stages with a Lightning Component
<!-- Get flow name from the Lightning App Builder -->
<aura:attribute name="flowName" type="String"/>
c:flowStages_global Design
The design resource includes the flowName attribute, so you can specify which flow to start from Lightning App Builder.
<design:component>
<design:attribute name="flowName" label="Flow Name"/>
</design:component>
c:flowStages_global Style
c:flowStages_global Controller
The controller uses the flowName attribute to determine which flow to start.
Each time a new screen loads, the onstatuschange action fires, which gives the controller access to a handful of parameters
about the flow. The currentStage and activeStages parameters return the labels and names of the relevant stages.
When onstatuschange fires in this component, it calls the controller's statusChange method. That method passes the
flow's currentStage and activeStages parameters into the component's attributes. For each item in the
activeStages attribute, the method adds a lightning:progressStep component to the component markup.
({
init : function(component, event, helper) {
var flow = component.find("flow");
flow.startFlow(component.get("v.flowName"));
},
166
Using Components Display Flow Stages with a Lightning Component
SEE ALSO:
Cloud Flow Designer Guide: Show Users Progress Through a Flow with Stages
Display Flow Stages with a Lightning Component
lightning:flow
Note: This release contains a beta version of flow stages that is production quality but has known limitations. To provide feedback
and suggestions, go to IdeaExchange.
Pass the $Flow.ActiveStages and $Flow.CurrentStage system variables to the component’s attributes. Then use those
attributes to display the flow’s active stages and select the current one.
It’s easier to get labels for the active and current stages in a flow from the lightning:flow component. In a Lightning component
screen field, you can pass only the fully resolved stage name into the component. If your flow is namespaced, the fully resolved name
is namespace.flowName:stageName. Otherwise, it’s flowName:stageName.
Depending on your naming convention, you can convert the stage names into labels by dropping the namespace and flow name and
replacing underscores with spaces.
167
Using Components Display Flow Stages with a Lightning Component
c:flowStages_field Component
<aura:component implements="lightning:availableForFlowScreens">
<!-- Attributes that store $Flow.ActiveStages and $Flow.CurrentStage -->
<aura:attribute name="stages" type="String[]"/>
<aura:attribute name="currentStage" type="String"/>
c:flowStages_field Design
The design resource includes the stages and currentStage attributes so that they’re available in the Cloud Flow Designer.
In the flow screen, pass $Flow.ActiveStages into the stages attribute, and pass $Flow.CurrentStage into the
currentStage attribute.
<design:component>
<design:attribute name="stages" label="Stages" description="What stages are active"/>
c:flowStages_field Style
c:flowStages_field Controller
When you add this component to a flow screen, you pass $Flow.ActiveStages into the stages attribute and
$Flow.CurrentStage into the currentStage attribute. As a result, the component's attributes contain the relevant
stages' fully qualified names (namespace.flowName:stageName) but not the associated labels.
To work around this limitation, this example converts the stage's fully qualified name to a label by removing the prefix and changing
the underscores to spaces. For example, for stage name Online_Purchase:Billing_Details, the converted label is
Billing Details.
For each item in the stages attribute, the init method converts the stage name to a label. Then for each item in the array, it
adds a lightning:progressStep component to the c:flowStages_field component markup.
({
init : function(component, event, helper) {
var progressIndicator = component.find('progressIndicator');
for (let step of component.get('v.stages')) {
168
Using Components Add Components to Apps
SEE ALSO:
Cloud Flow Designer Guide: Show Users Progress Through a Flow with Stages
Display Flow Stages with a Lightning Component
Display Flow Stages with a Lightning Component
lightning:availableForFlowScreens
Note: For all the out-of-the-box components, see the Components folder at
https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the
name of your custom Salesforce domain. The ui namespace includes many components that are common on Web pages.
Components are encapsulated and their internals stay private, while their public shape is visible to consumers of the component. This
strong separation gives component authors freedom to change the internal implementation details and insulates component consumers
from those changes.
169
Using Components Integrate Your Custom Apps into the Chatter Publisher
The public shape of a component is defined by the attributes that can be set and the events that interact with the component. The
shape is essentially the API for developers to interact with the component. To design a new component, think about the attributes that
you want to expose and the events that the component should initiate or respond to.
Once you have defined the shape of any new components, developers can work on the components in parallel. This is a useful approach
if you have a team working on an app.
To add a new custom component to your app, see Using the Developer Console on page 6.
SEE ALSO:
Component Composition
Using Object-Oriented Development
Component Attributes
Communicating with Events
Note: Rich Publisher Apps are available to Lightning communities in topics, group, and profile feeds and in direct messages.
170
Using Components Integrate Your Custom Apps into the Chatter Publisher
The next sections describe how we integrated the custom quotation app with the Chatter publisher.
171
Using Components Integrate Your Custom Apps into the Chatter Publisher
<aura:component implements="lightning:availableForChatterExtensionComposer">
<aura:handler name="init" value="{!this}" action="{!c.init}"/>
<div class="container">
<span class="quote" aura:id="quote"></span>
<span class="author" aura:id="author"></span>
<ui:button label="Get next Quote" press="{!c.getQuote}"/>
</div>
</aura:component>
Use your controller and helper to initialize the composer component and to get the quote from a source. Once you get the quote, fire
the event sendChatterExtensionPayload. Firing the event enables the Add button so the platform can associate the app’s
payload with the feed item. You can also add a title and description as metadata for the payload. The title and description are shown in
a non-Lightning context, like Salesforce Classic.
getQuote: function(cmp, event, helper) {
// get quote from the source
var compEvent = cmp.getEvent("sendChatterExtensionPayload");
compEvent.setParams({
"payload" : "<payload object>",
"extensionTitle" : "<title to use when extension is rendered>",
"extensionDescription" : "<description to use when extension is rendered>"
});
compEvent.fire();
}
Add a CSS resource to your component bundle to style your composition component.
<div class="container">
<span class="quote" aura:id="quote">{!v._quote}</span>
<span class="author" aura:id="author">--- {!v._author} ---</span>
</div>
</aura:component>
172
Using Components Integrate Your Custom Apps into the Chatter Publisher
You have a couple of ways of dealing with the payload. You can use the payload directly in the component {!v.payload}. You can
use your controller to parse the payload provided by the lightning:availableForChatterExtensionRenderer
interface and set its attributes yourself. Add a CSS resource to your renderer bundle to style your renderer component.
In the Value column, provide values for ChatterExtension fields (see ChatterExtension for values and descriptions).
173
Using Components Integrate Your Custom Apps into the Chatter Publisher
Get the IconId for the file asset. Go to Workbench > utilities > REST Explorer and make a new POST request for
creating a file asset with a fileId from your org.
Note: Rich Publisher Apps information is cached, so there can be a 5-minute wait before your app appears in the publisher.
174
Using Components Use Lightning Components in Visualforce Pages
After you move apps to the Selected Items column and click Save, the selected apps appear in the Chatter Publisher.
SEE ALSO:
lightning:availableForChatterExtensionComposer
lightning:availableForChatterExtensionRenderer
lightning:sendChatterExtensionPayload
Important: 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 other ways using Lightning Components for Visualforce is just like using Lightning Out. Refer to the Lightning Out section of
this guide for additional details.
175
Using Components Use Lightning Components in Visualforce Pages
Note: Extending from ltng:outApp adds SLDS resources to the page to allow your Lightning components to be styled with
the Salesforce Lightning Design System (SLDS). If you don’t want SLDS resources added to the page, extend from
ltng:outAppUnstyled instead.
To reference this app on your page, use the following JavaScript code, where theNamespace is the namespace prefix for the app.
That is, either your org’s namespace, or the namespace of the managed package that provides the app.
If the app is defined in your org (that is, not in a managed package), you can use the default “c” namespace instead, as shown in the
next example. If your org doesn’t have a namespace defined, you must use the default namespace.
For further details about creating a Lightning dependency app, see Lightning Out Dependencies.
<script>
$Lightning.use("c:lcvfTest", function() {
$Lightning.createComponent("ui:button",
{ label : "Press Me!" },
"lightning",
function(cmp) {
// do some stuff
});
});
176
Using Components Add Lightning Components to Any App with Lightning Out
(Beta)
</script>
</apex:page>
This code creates a DOM element with the ID “lightning”, which is then referenced in the $Lightning.createComponent()
method. This method creates a ui:button that says “Press Me!”, and then executes the callback function.
Important: You can call $Lightning.use() multiple times on a page, but all calls must reference the same Lightning
dependency app.
For further details about using $Lightning.use() and $Lightning.createComponent(), see Lightning Out Markup.
SEE ALSO:
Lightning Out Dependencies
Add Lightning Components to Any App with Lightning Out (Beta)
Lightning Out Markup
Share Lightning Out Apps with Non-Authenticated Users
Lightning Out Considerations and Limitations
Note: This release contains a beta version of Lightning Out, which means it’s a high quality feature with known limitations. You
can provide feedback and suggestions for Lightning Out on the IdeaExchange.
Developing Lightning components that you can deploy anywhere is for the most part the same as developing them to run within
Salesforce. Everything you already know about Lightning components development still applies. The only real difference is in how you
embed your Lightning components app in the remote web container, or origin server.
Lightning Out is added to external apps in the form of a JavaScript library you include in the page on the origin server, and markup you
add to configure and activate your Lightning components app. Once initialized, Lightning Out pulls in your Lightning components app
over a secure connection, spins it up, and inserts it into the DOM of the page it’s running on. Once it reaches this point, your “normal”
Lightning components code takes over and runs the show.
Note: This approach is quite different from embedding an app using an iframe. Lightning components running via Lightning
Out are full citizens on the page. If you choose to, you can enable interaction between your Lightning components app and the
page or app you’ve embedded it in. This interaction is handled using Lightning events.
In addition to some straightforward markup, there’s a modest amount of setup and preparation within Salesforce to enable the secure
connection between Salesforce and the origin server. And, because the origin server is hosting the app, you need to manage authentication
with your own code.
This setup process is similar to what you’d do for an application that connects to Salesforce using the Lightning Platform REST API, and
you should expect it to require an equivalent amount of work.
IN THIS SECTION:
Lightning Out Requirements
Deploying a Lightning components app using Lightning Out has a few modest requirements to ensure connectivity and security.
177
Using Components Lightning Out Requirements
SEE ALSO:
Idea Exchange: Lightning Components Anywhere / Everywhere
178
Using Components Lightning Out Markup
The mechanism for specifying dependencies is a Lightning dependency app. A dependency app is simply an <aura:application>
with a few attributes, and the dependent components described using the <aura:dependency> tag. A Lightning dependency
app isn’t one you’d ever actually deploy as an app for people to use directly. A Lightning dependency app is used only to specify
the dependencies for Lightning Out. (Or for Lightning Components for Visualforce, which uses Lightning Out under the covers.)
A basic Lightning dependency app looks like the following.
<aura:application access="GLOBAL" extends="ltng:outApp">
<aura:dependency resource="c:myAppComponent"/>
</aura:application>
Note: Don’t worry about components used within the top-level component. The Lightning Component framework handles
dependency resolution for child components.
Usage Notes
A Lightning dependency app isn’t a normal Lightning app, and you shouldn’t treat it like one. Use it only to specify the dependencies
for your Lightning Out app.
In particular, note the following.
• You can’t add a template to a Lightning dependency app.
• Content you add to the body of the Lightning dependency app won’t be rendered.
SEE ALSO:
Create a Connected App
Use CORS to Access Salesforce Resources from Web Browsers
aura:dependency
Using the Salesforce Lightning Design System in Apps
179
Using Components Lightning Out Markup
The markup and JavaScript functions in the Lightning Out library are the only things specific to Lightning Out. Everything else is the
Lightning components code you already know and love.
<script src="https://myDomain.my.salesforce.com/lightning/lightning.out.js"></script>
Important: Use your custom domain for the host. Don’t copy-and-paste someone else’s instance from example source code. If
you do this, your app will break whenever there’s a version mismatch between your Salesforce instance and the instance from
which you’re loading the Lightning Out library. This happens at least three times a year, during regular upgrades of Salesforce.
Don’t do it!
callback function A function to call once the Lightning Component framework and your app
have fully loaded. The callback receives no arguments.
This callback is usually where you call
$Lightning.createComponent() to add your app to the page
(see the next section). You might also update your display in other ways, or
otherwise respond to your Lightning components app being ready.
lightningEndPointURI string The URL for the Lightning domain on your Salesforce instance. For example,
“https://myDomain.lightning.force.com”.
authToken string The session ID or OAuth access token for a valid, active Salesforce session.
Note: You must obtain this token in your own code. Lightning Out
doesn’t handle authentication for you. See Authentication from
Lightning Out.
appName is required. The other three parameters are optional. In normal use you provide all four parameters.
Note: You can’t use more than one Lightning dependency app on a page. You can call $Lightning.use() more than
once, but you must reference the same dependency app in every call.
180
Using Components Authentication from Lightning Out
attributes Object Required. The attributes to set on the component when it’s created. For
example, { name: theName, amount: theAmount }. If the
component doesn’t require any attributes, pass in an empty object, { }.
domLocator Element or string Required. The DOM element or element ID that indicates where on the page
to insert the created component.
callback function A function to call once the component is added to and active on the page.
The callback receives the component created as its only argument.
Note: You can add more than one Lightning component to a page. That is, you can call $Lightning.createComponent()
multiple times, with multiple DOM locators, to add components to different parts of the page. Each component created this way
must be specified in the page’s Lightning dependency app.
Behind the scenes $Lightning.createComponent() calls the standard $A.createComponent() function. Except for
the DOM locator, the arguments are the same. And except for wrapping the call in some Lightning Out semantics, the behavior is the
same, too.
SEE ALSO:
Dynamically Creating Components
Important: Lightning Out isn’t in the business of authentication. The $Lightning.use() function simply passes along to
the security subsystem whatever authentication token you provide it. For most organizations, this will be a session ID or an OAuth
token.
Lightning Out has the same privileges as the session from which you obtain the authentication token. For Visualforce using {!
$Api.Session_ID }, the session has the privileges of the current user. For OAuth it’s whatever OAuth scope setting that
the OAuth Connected App is defined with. In most cases, using Lightning Out with OAuth requires you to grant “Full Access” scope
to the Connected App returning the OAuth token.
181
Using Components Share Lightning Out Apps with Non-Authenticated Users
Important: When you make a Lightning app accessible to guest users by adding the ltng:allowGuestAccess interface,
it’s available through every community in your org, whether that community is enabled for public access or not. You can’t prevent
it from being accessible via community URLs, and you can’t make it available for some communities but not others.
Warning: Be extremely careful about apps you open for guest access. Apps enabled for guest access bypass the object- and
field-level security (FLS) you set for your community’s guest user profile. Lightning components don’t automatically enforce CRUD
and FLS when you reference objects or retrieve the objects from an Apex controller. This means that the framework continues to
display records and fields for which users don’t have CRUD access and FLS visibility. You must manually enforce CRUD and FLS in
your Apex controllers. A mistake in code used in an app enabled for guest access can open your org’s data to the world.
Lightning Out Lightning Components for Visualforce
Usage
To begin with, add the ltng:allowGuestAccess interface to your Lightning Out dependency app. For example:
<aura:application access="GLOBAL" extends="ltng:outApp"
implements="ltng:allowGuestAccess">
<aura:dependency resource="c:storeLocatorMain"/>
</aura:application>
Note: You can only add the ltng:allowGuestAccess interface to Lightning apps, not to individual components.
182
Using Components Lightning Out Considerations and Limitations
Finally, add the JavaScript code to load and activate your Lightning app. This code is standard Lightning Out, with the important addition
that you must use one of your org’s community URLs for the endpoint. The endpoint URL takes the form
https://yourCommunityDomain/communityURL/. The relevant line is emphasized in the following sample.
<script>
$Lightning.use("c:locatorApp", // name of the Lightning app
function() { // Callback once framework and app loaded
$Lightning.createComponent(
"c:storeLocatorMain", // top-level component of your app
{ }, // attributes to set on the component when created
"lightningLocator", // the DOM location to insert the component
function(cmp) {
// callback when component is created and active on the page
}
);
},
'https://universalcontainers.force.com/ourstores/' // Community endpoint
);
</script>
SEE ALSO:
Salesforce Help: Create Communities
Use Lightning Components in Visualforce Pages
Note: This event is handled by the one.app container. It’s supported in Lightning Experience and Salesforce app only.
183
Using Components Lightning Out Considerations and Limitations
SEE ALSO:
Browser Support Considerations for Lightning Components
Authentication from Lightning Out
System Event Reference
Use Lightning Components in Visualforce Pages
184
CHAPTER 5 Communicating with Events
In this chapter ... The framework uses event-driven programming. You write handlers that respond to interface events as
they occur. The events may or may not have been triggered by user interaction.
• Actions and Events
In the Lightning Component framework, events are fired from JavaScript controller actions. Events can
• Handling Events with
contain attributes that can be set before the event is fired and read when the event is handled.
Client-Side
Controllers Events are declared by the aura:event tag in a .evt resource, and they can have one of two types:
• Component Events component or application.
• Application Events Component Events
• Event Handling A component event is fired from an instance of a component. A component event can be handled
Lifecycle by the component that fired the event or by a component in the containment hierarchy that receives
the event.
• Advanced Events
Example Application Events
• Firing Lightning Application events follow a traditional publish-subscribe model. An application event is fired from
Events from an instance of a component. All components that provide a handler for the event are notified.
Non-Lightning Code
Note: Always try to use a component event instead of an application event, if possible. Component
• Events Best Practices events can only be handled by components above them in the containment hierarchy so their
• Events Fired During usage is more localized to the components that need to know about them. Application events
the Rendering are best used for something that should be handled at the application level, such as navigating
Lifecycle to a specific record. Application events allow communication between components that are in
• Events Handled in separate parts of the application and have no direct containment relationship.
the Salesforce mobile
app and Lightning
Experience
• System Events
185
Communicating with Events Actions and Events
Clicking the button invokes the handleClick method in the component’s client-side controller.
Events
A notification by the browser regarding an action. Browser events are handled by client-side JavaScript controllers, as shown in the
previous example. A browser event is not the same as a framework component event or application event, which you can create and
fire in a JavaScript controller to communicate data between components. For example, you can wire up the click event of a checkbox
to a client-side controller, which fires a component event to communicate relevant data to a parent component.
Another type of event, known as a system event, is fired automatically by the framework during its lifecycle, such as during component
initialization, change of an attribute value, and rendering. Components can handle a system event by registering the event in the
component markup.
The following diagram describes what happens when a user clicks a button that requires the component to retrieve data from the server.
1. User clicks a button or interacts with a component, triggering a browser event. For example, you want to save data from the server
when the button is clicked.
2. The button click invokes a client-side JavaScript controller, which provides some custom logic before invoking a helper function.
3. The JavaScript controller invokes a helper function. A helper function improves code reuse but it’s optional for this example.
4. The helper function calls an Apex controller method and queues the action.
5. The Apex method is invoked and data is returned.
6. A JavaScript callback function is invoked when the Apex method completes.
7. The JavaScript callback function evaluates logic and updates the component’s UI.
186
Communicating with Events Handling Events with Client-Side Controllers
SEE ALSO:
Handling Events with Client-Side Controllers
Detecting Data Changes with Change Handlers
Calling a Server-Side Action
Events Fired During the Rendering Lifecycle
187
Communicating with Events Handling Events with Client-Side Controllers
Component source
<aura:component>
<aura:attribute name="text" type="String" default="Just a string. Waiting for change."/>
If you know some JavaScript, you might be tempted to write something like the first "Flawed" button because you know that HTML tags
are first-class citizens in the framework. However, the "Flawed" button won't work because arbitrary JavaScript, such as the alert()
call, in the component is ignored.
The framework has its own event system. DOM events are mapped to Lightning events, since HTML tags are mapped to Lightning
components.
Any browser DOM element event starting with on, such as onclick or onkeypress, can be wired to a controller action. You can
only wire browser events to controller actions.
The "Framework" button wires the onclick attribute in the <lightning:button> component to the handleClick action
in the controller.
Client-side controller source
({
handleClick : function(cmp, event) {
var attributeValue = cmp.get("v.text");
console.log("current text: " + attributeValue);
The handleClick action uses event.getSource() to get the source component that fired this component event. In this
case, the source component is the <lightning:button> in the markup.
The code then sets the value of the text component attribute to the value of the button’s label attribute. The text component
attribute is defined in the <aura:attribute> tag in the markup.
Tip: Use unique names for client-side and server-side actions in a component. A JavaScript function (client-side action) with the
same name as an Apex method (server-side action ) can lead to hard-to-debug issues. In debug mode, the framework logs a
browser console warning about the clashing client-side and server-side action names.
188
Communicating with Events Component Events
SEE ALSO:
Sharing JavaScript Code in a Component Bundle
Event Handling Lifecycle
Creating Server-Side Logic with Controllers
Component Events
A component event is fired from an instance of a component. A component event can be handled by the component that fired the
event or by a component in the containment hierarchy that receives the event.
IN THIS SECTION:
Component Event Propagation
The framework supports capture and bubble phases for the propagation of component events. These phases are similar to DOM
handling patterns and provide an opportunity for interested components to interact with an event and potentially control the
behavior for subsequent handlers.
Create Custom Component Events
Create a custom component event using the <aura:event> tag in a .evt resource. Events can contain attributes that can
be set before the event is fired and read when the event is handled.
Fire Component Events
Fire a component event to communicate data to another component. A component event can be handled by the component that
fired the event or by a component in the containment hierarchy that receives the event.
189
Communicating with Events Component Event Propagation
SEE ALSO:
aura:method
Application Events
Handling Events with Client-Side Controllers
Advanced Events Example
What is Inherited?
Note: Application events have a separate default phase. There’s no separate default phase for component events. The default
phase is the bubble phase.
190
Communicating with Events Create Custom Component Events
The component that fires an event can set the event’s data. To set the attribute values, call event.setParam() or
event.setParams(). A parameter name set in the event must match the name attribute of an <aura:attribute> in the
event. For example, if you fire c:compEvent, you could use:
event.setParam("message", "event message here");
The component that handles an event can retrieve the event data. To retrieve the attribute value in this event, call
event.getParam("message") in the handler’s client-side controller.
Register an Event
A component registers that it may fire an event by using <aura:registerEvent> in its markup. For example:
<aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>
We’ll see how the value of the name attribute is used for firing and handling events.
Fire an Event
To get a reference to a component event in JavaScript, use cmp.getEvent("evtName") where evtName matches the name
attribute in <aura:registerEvent>.
Use fire() to fire the event from an instance of a component. For example, in an action function in a client-side controller:
var compEvent = cmp.getEvent("sampleComponentEvent");
// Optional: set some data for the event (also known as event shape)
// A parameter’s name must match the name attribute
// of one of the event’s <aura:attribute> tags
// compEvent.setParams({"myParam" : myValue });
compEvent.fire();
SEE ALSO:
Fire Application Events
191
Communicating with Events Handling Component Events
The name attribute in <aura:handler> must match the name attribute in the <aura:registerEvent> tag in the
component that fires the event.
The action attribute of <aura:handler> sets the client-side controller action to handle the event.
The event attribute specifies the event being handled. The format is namespace:eventName.
In this example, when the event is fired, the handleComponentEvent client-side controller action is called.
IN THIS SECTION:
Component Handling Its Own Event
A component can handle its own event by using the <aura:handler> tag in its markup.
Handle Component Event of Instantiated Component
A parent component can set a handler action when it instantiates a child component in its markup.
Handling Bubbled or Captured Component Events
Event propagation rules determine which components in the containment hierarchy can handle events by default in the bubble or
capture phases. Learn about the rules and how to handle events in the bubble or capture phases.
Handling Component Events Dynamically
A component can have its handler bound dynamically via JavaScript. This is useful if a component is created in JavaScript on the
client-side.
SEE ALSO:
Component Event Propagation
Handling Application Events
192
Communicating with Events Handling Component Events
Note: The name attributes in <aura:registerEvent> and <aura:handler> must match, since each event is
defined by its name.
SEE ALSO:
Handle Component Event of Instantiated Component
c:parent sets a handler for this event when it instantiates c:child in its markup.
Note how c:parent uses the following syntax to set a handler for the sampleComponentEvent event fired by c:child.
<c:child sampleComponentEvent="{!c.handleChildEvent}"/>
The syntax looks similar to how you set an attribute called sampleComponentEvent. However, in this case,
sampleComponentEvent isn’t an attribute. sampleComponentEvent matches the event name declared in c:child.
The preceding syntax is a convenient shortcut for the normal way that a component declares a handler for an event. The parent component
can only use this syntax to handle events from a direct descendent. If you want to be more explicit in c:parent that you’re handling
an event, or if the event might be fired by a component further down the component hierarchy, use an <aura:handler> tag
instead of declaring the handler within the <c:child> tag.
<!-- parent.cmp -->
<aura:component>
<aura:handler name="sampleComponentEvent" event="c:compEvent"
action="{!c.handleSampleEvent}"/>
<c:child />
</aura:component>
193
Communicating with Events Handling Component Events
The two versions of c:parent markup behave the same. However, using <aura:handler> makes it more obvious that you’re
handling a sampleComponentEvent event.
SEE ALSO:
Component Handling Its Own Event
Handling Bubbled or Captured Component Events
<!--c:owner-->
<aura:component>
<c:container>
<c:eventSource />
</c:container>
</aura:component>
If c:eventSource fires an event, it can handle the event itself. The event then bubbles up the containment hierarchy.
c:container contains c:eventSource but it’s not the owner because it’s not the outermost component in the markup, so it
can’t handle the bubbled event.
c:owner is the owner because c:container is in its markup. c:owner can handle the event.
194
Communicating with Events Handling Component Events
A container component has a facet attribute whose type is Aura.Component[], such as the default body attribute. The container
component includes those components in its definition using an expression, such as {!v.body}. The container component isn’t the
owner of the components rendered with that expression.
To allow a container component to handle the event, add includeFacets="true" to the <aura:handler> tag of the
container component. For example, adding includeFacets="true" to the handler in the container component, c:container,
enables it to handle the component event bubbled from c:eventSource.
<aura:handler name="bubblingEvent" event="c:compEvent" action="{!c.handleBubbling}"
includeFacets="true" />
A component handling the event in the bubble phase uses the <aura:handler> tag to assign a handling action in its client-side
controller.
<aura:component>
<aura:handler name="compEvent" event="c:compEvent" action="{!c.handleBubbling}"/>
</aura:component>
Note: The name attribute in <aura:handler> must match the name attribute in the <aura:registerEvent> tag
in the component that fires the event.
The default handling phase for component events is bubble if no phase attribute is set.
195
Communicating with Events Handling Component Events
Note: This sample code uses the default c namespace. If your org has a namespace, use that namespace instead.
<!--c:eventBubblingEmitter-->
<aura:component>
<aura:registerEvent name="bubblingEvent" type="c:compEvent" />
<lightning:button onclick="{!c.fireEvent}" label="Start Bubbling"/>
</aura:component>
Here’s the controller for c:eventBubblingEmitter. When you press the button, it fires the bubblingEvent event registered
in the markup.
/*eventBubblingEmitterController.js*/
{
fireEvent : function(cmp) {
var cmpEvent = cmp.getEvent("bubblingEvent");
cmpEvent.fire();
}
}
<div class="grandchild">
<c:eventBubblingEmitter />
</div>
</aura:component>
196
Communicating with Events Handling Component Events
The controller logs the event name when the handler is called.
Here’s the markup for c:eventBubblingChild. We will pass c:eventBubblingGrandchild in as the body of
c:eventBubblingChild when we create c:eventBubblingParent later in this example.
<!--c:eventBubblingChild-->
<aura:component>
<aura:handler name="bubblingEvent" event="c:compEvent" action="{!c.handleBubbling}"/>
<div class="child">
{!v.body}
</div>
</aura:component>
<!--c:eventBubblingParent-->
<aura:component>
<aura:handler name="bubblingEvent" event="c:compEvent" action="{!c.handleBubbling}"/>
<div class="parent">
<c:eventBubblingChild>
<c:eventBubblingGrandchild />
</c:eventBubblingChild>
</div>
</aura:component>
Now, let’s see what happens when you run the code.
1. In your browser, navigate to c:eventBubblingParent. Create a .app resource that contains
<c:eventBubblingParent />.
2. Click the Start Bubbling button that is part of the markup in c:eventBubblingEmitter.
197
Communicating with Events Component Event Example
SEE ALSO:
Component Event Propagation
Handle Component Event of Instantiated Component
Note: The event and components in this example use the default c namespace. If your org has a namespace, use that namespace
instead.
198
Communicating with Events Component Event Example
Component Event
The ceEvent.evt component event has one attribute. We’ll use this attribute to pass some data in the event when it’s fired.
<!--c:ceEvent-->
<aura:event type="COMPONENT">
<aura:attribute name="message" type="String"/>
</aura:event>
Notifier Component
The c:ceNotifier component uses aura:registerEvent to declare that it may fire the component event.
The button in the component contains an onclick browser event that is wired to the fireComponentEvent action in the
client-side controller. The action is invoked when you click the button.
<!--c:ceNotifier-->
<aura:component>
<aura:registerEvent name="cmpEvent" type="c:ceEvent"/>
The client-side controller gets an instance of the event by calling cmp.getEvent("cmpEvent"), where cmpEvent matches
the value of the name attribute in the <aura:registerEvent> tag in the component markup. The controller sets the message
attribute of the event and fires the event.
/* ceNotifierController.js */
{
fireComponentEvent : function(cmp, event) {
// Get the component event by using the
// name value from aura:registerEvent
var cmpEvent = cmp.getEvent("cmpEvent");
cmpEvent.setParams({
"message" : "A component event fired me. " +
"It all happened so fast. Now, I'm here!" });
cmpEvent.fire();
}
}
Handler Component
The c:ceHandler handler component contains the c:ceNotifier component. The <aura:handler> tag uses the same
value of the name attribute, cmpEvent, from the <aura:registerEvent> tag in c:ceNotifier. This wires up
c:ceHandler to handle the event bubbled up from c:ceNotifier.
When the event is fired, the handleComponentEvent action in the client-side controller of the handler component is invoked.
<!--c:ceHandler-->
<aura:component>
<aura:attribute name="messageFromEvent" type="String"/>
199
Communicating with Events Application Events
<p>{!v.messageFromEvent}</p>
<p>Number of events: {!v.numEvents}</p>
</aura:component>
The controller retrieves the data sent in the event and uses it to update the messageFromEvent attribute in the handler component.
/* ceHandlerController.js */
{
handleComponentEvent : function(cmp, event) {
var message = event.getParam("message");
SEE ALSO:
Component Events
Creating Server-Side Logic with Controllers
Application Event Example
Application Events
Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All
components that provide a handler for the event are notified.
200
Communicating with Events Application Event Propagation
IN THIS SECTION:
Application Event Propagation
The framework supports capture, bubble, and default phases for the propagation of application events. The capture and bubble
phases are similar to DOM handling patterns and provide an opportunity for interested components to interact with an event and
potentially control the behavior for subsequent handlers. The default phase preserves the framework’s original handling behavior.
Create Custom Application Events
Create a custom application event using the <aura:event> tag in a .evt resource. Events can contain attributes that can be
set before the event is fired and read when the event is handled.
Fire Application Events
Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All
components that provide a handler for the event are notified.
Handling Application Events
Use <aura:handler> in the markup of the handler component.
SEE ALSO:
Component Events
Handling Events with Client-Side Controllers
Application Event Propagation
Advanced Events Example
201
Communicating with Events Create Custom Application Events
Capture
The event is captured and trickles down from the application root to the source component. The event can be handled by a component
in the containment hierarchy that receives the captured event.
Event handlers are invoked in order from the application root down to the source component that fired the event.
Any registered handler in this phase can stop the event from propagating, at which point no more handlers are called in this phase
or the bubble phase. If a component stops the event propagation using event.stopPropagation(), the component
becomes the root node used in the default phase.
Any registered handler in this phase can cancel the default behavior of the event by calling event.preventDefault(). This
call prevents execution of any of the handlers in the default phase.
Bubble
The component that fired the event can handle it. The event then bubbles up from the source component to the application root.
The event can be handled by a component in the containment hierarchy that receives the bubbled event.
Event handlers are invoked in order from the source component that fired the event up to the application root.
Any registered handler in this phase can stop the event from propagating, at which point no more handlers will be called in this
phase. If a component stops the event propagation using event.stopPropagation(), the component becomes the root
node used in the default phase.
Any registered handler in this phase can cancel the default behavior of the event by calling event.preventDefault(). This
call prevents execution of any of the handlers in the default phase.
Default
Event handlers are invoked in a non-deterministic order from the root node through its subtree. The default phase doesn’t have the
same propagation rules related to component hierarchy as the capture and bubble phases. The default phase can be useful for
handling application events that affect components in different sub-trees of your app.
If the event’s propagation wasn’t stopped in a previous phase, the root node defaults to the application root. If the event’s propagation
was stopped in a previous phase, the root node is set to the component whose handler invoked event.stopPropagation().
Here is the sequence of application event propagation.
1. Event fired—An application event is fired. The component that fires the event is known as the source component.
2. Capture phase—The framework executes the capture phase from the application root to the source component until all components
are traversed. Any handling event can stop propagation by calling stopPropagation() on the event.
3. Bubble phase—The framework executes the bubble phase from the source component to the application root until all components
are traversed or stopPropagation() is called.
4. Default phase—The framework executes the default phase from the root node unless preventDefault() was called in the
capture or bubble phases. If the event’s propagation wasn’t stopped in a previous phase, the root node defaults to the application
root. If the event’s propagation was stopped in a previous phase, the root node is set to the component whose handler invoked
event.stopPropagation().
202
Communicating with Events Fire Application Events
The component that fires an event can set the event’s data. To set the attribute values, call event.setParam() or
event.setParams(). A parameter name set in the event must match the name attribute of an <aura:attribute> in the
event. For example, if you fire c:appEvent, you could use:
event.setParam("message", "event message here");
The component that handles an event can retrieve the event data. To retrieve the attribute in this event, call
event.getParam("message") in the handler’s client-side controller.
Register an Event
A component registers that it may fire an application event by using <aura:registerEvent> in its markup. The name attribute
is required but not used for application events. The name attribute is only relevant for component events. This example uses
name="appEvent" but the value isn’t used anywhere.
Fire an Event
Use $A.get("e.myNamespace:myAppEvent") in JavaScript to get an instance of the myAppEvent event in the
myNamespace namespace.
Note: The syntax to get an instance of an application event is different than the syntax to get a component event, which is
cmp.getEvent("evtName").
Use fire() to fire the event.
var appEvent = $A.get("e.c:appEvent");
// Optional: set some data for the event (also known as event shape)
// A parameter’s name must match the name attribute
// of one of the event’s <aura:attribute> tags
//appEvent.setParams({ "myParam" : myValue });
appEvent.fire();
203
Communicating with Events Handling Application Events
Note: We don't recommend using the legacy aura:waiting, aura:doneWaiting, and aura:doneRendering
application events except as a last resort. The aura:waiting and aura:doneWaiting application events are fired for
every batched server request, even for requests from other components in your app. Unless your component is running in complete
isolation in a standalone app and not included in Lightning Experience or the Salesforce app, you probably don’t want to handle
these application events. The container app may fire server-side actions and trigger your event handlers multiple times.
For more information, see Events Fired During the Rendering Lifecycle on page 216.
SEE ALSO:
Fire Component Events
The event attribute specifies the event being handled. The format is namespace:eventName.
The action attribute of <aura:handler> sets the client-side controller action to handle the event.
Note: The handler for an application event won’t work if you set the name attribute in <aura:handler>. Use the name
attribute only when you’re handling component events.
In this example, when the event is fired, the handleApplicationEvent client-side controller action is called.
IN THIS SECTION:
Handling Bubbled or Captured Application Events
Event propagation rules determine which components in the containment hierarchy can handle events by default in the bubble or
capture phases. Learn about the rules and how to handle events in the bubble or capture phases.
SEE ALSO:
Handling Component Events
204
Communicating with Events Handling Application Events
<!--c:owner-->
<aura:component>
<c:container>
<c:eventSource />
</c:container>
</aura:component>
If c:eventSource fires an event, it can handle the event itself. The event then bubbles up the containment hierarchy.
c:container contains c:eventSource but it’s not the owner because it’s not the outermost component in the markup, so it
can’t handle the bubbled event.
c:owner is the owner because c:container is in its markup. c:owner can handle the event.
205
Communicating with Events Application Event Example
The event attribute specifies the event being handled. The format is namespace:eventName.
The action attribute of <aura:handler> sets the client-side controller action to handle the event.
Note: The event and components in this example use the default c namespace. If your org has a namespace, use that namespace
instead.
Application Event
The aeEvent.evt application event has one attribute. We’ll use this attribute to pass some data in the event when it’s fired.
<!--c:aeEvent-->
<aura:event type="APPLICATION">
<aura:attribute name="message" type="String"/>
</aura:event>
206
Communicating with Events Application Event Example
Notifier Component
The aeNotifier.cmp notifier component uses aura:registerEvent to declare that it may fire the application event. The
name attribute is required but not used for application events. The name attribute is only relevant for component events.
The button in the component contains a onclick browser event that is wired to the fireApplicationEvent action in the
client-side controller. Clicking this button invokes the action.
<!--c:aeNotifier-->
<aura:component>
<aura:registerEvent name="appEvent" type="c:aeEvent"/>
The client-side controller gets an instance of the event by calling $A.get("e.c:aeEvent"). The controller sets the message
attribute of the event and fires the event.
/* aeNotifierController.js */
{
fireApplicationEvent : function(cmp, event) {
// Get the application event by using the
// e.<namespace>.<event> syntax
var appEvent = $A.get("e.c:aeEvent");
appEvent.setParams({
"message" : "An application event fired me. " +
"It all happened so fast. Now, I'm everywhere!" });
appEvent.fire();
}
}
Handler Component
The aeHandler.cmp handler component uses the <aura:handler> tag to register that it handles the application event.
Note: The handler for an application event won’t work if you set the name attribute in <aura:handler>. Use the name
attribute only when you’re handling component events.
When the event is fired, the handleApplicationEvent action in the client-side controller of the handler component is invoked.
<!--c:aeHandler-->
<aura:component>
<aura:attribute name="messageFromEvent" type="String"/>
<aura:attribute name="numEvents" type="Integer" default="0"/>
<p>{!v.messageFromEvent}</p>
<p>Number of events: {!v.numEvents}</p>
</aura:component>
207
Communicating with Events Event Handling Lifecycle
The controller retrieves the data sent in the event and uses it to update the messageFromEvent attribute in the handler component.
/* aeHandlerController.js */
{
handleApplicationEvent : function(cmp, event) {
var message = event.getParam("message");
Container Component
The aeContainer.cmp container component contains the notifier and handler components. This is different from the component
event example where the handler contains the notifier component.
<!--c:aeContainer-->
<aura:component>
<c:aeNotifier/>
<c:aeHandler/>
</aura:component>
SEE ALSO:
Application Events
Creating Server-Side Logic with Controllers
Component Event Example
208
Communicating with Events Event Handling Lifecycle
209
Communicating with Events Advanced Events Example
• Set attributes or modify data on the component (causing a re-rendering of the component).
• Fire another event or invoke a client-side or server-side action.
3.2 Executing an Application Event Handler
All event handlers are executed. When the event handler is executed, the event instance is passed into the event handler.
4 Re-render Component (optional)
After the event handlers and any callback actions are executed, a component might be automatically re-rendered if it was modified
during the event handling process.
SEE ALSO:
Create a Custom Renderer
Container Component eventsContainer.cmp Displays the event handlers on the UI for the complete
demo.
The definitions of component and application events are stored in separate .evt resources, but individual notifier and handler
component bundles can contain code to work with both types of events.
The component and application events both contain a context attribute that defines the shape of the event. This is the data that is
passed to handlers of the event.
210
Communicating with Events Advanced Events Example
Component Event
Here is the markup for compEvent.evt.
<!--c:compEvent-->
<aura:event type="COMPONENT">
<!-- pass context of where the event was fired to the handler. -->
<aura:attribute name="context" type="String"/>
</aura:event>
Application Event
Here is the markup for appEvent.evt.
<!--c:appEvent-->
<aura:event type="APPLICATION">
<!-- pass context of where the event was fired to the handler. -->
<aura:attribute name="context" type="String"/>
</aura:event>
Notifier Component
The eventsNotifier.cmp notifier component contains buttons to initiate a component or application event.
The notifier uses aura:registerEvent tags to declare that it may fire the component and application events. Note that the
name attribute is required but the value is only relevant for the component event; the value is not used anywhere else for the application
event.
The parentName attribute is not set yet. We will see how this attribute is set and surfaced in eventsContainer.cmp.
<!--c:eventsNotifier-->
<aura:component>
<aura:attribute name="parentName" type="String"/>
<aura:registerEvent name="componentEventFired" type="c:compEvent"/>
<aura:registerEvent name="appEvent" type="c:appEvent"/>
<div>
<h3>This is {!v.parentName}'s eventsNotifier.cmp instance</h3>
<p><ui:button
label="Click here to fire a component event"
press="{!c.fireComponentEvent}" />
</p>
<p><ui:button
label="Click here to fire an application event"
press="{!c.fireApplicationEvent}" />
</p>
</div>
</aura:component>
CSS source
The CSS is in eventsNotifier.css.
/* eventsNotifier.css */
.cEventsNotifier {
211
Communicating with Events Advanced Events Example
display: block;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
You can click the buttons to fire component and application events but there is no change to the output because we haven't wired up
the handler component to react to the events yet.
The controller sets the context attribute of the component or application event to the parentName of the notifier component
before firing the event. We will see how this affects the output when we look at the handler component.
Handler Component
The eventsHandler.cmp handler component contains the c:eventsNotifier notifier component and <aura:handler>
tags for the application and component events.
<!--c:eventsHandler-->
<aura:component>
<aura:attribute name="name" type="String"/>
<aura:attribute name="mostRecentEvent" type="String" default="Most recent event handled:"/>
212
Communicating with Events Advanced Events Example
<div>
<h3>This is {!v.name}</h3>
<p>{!v.mostRecentEvent}</p>
<p># component events handled: {!v.numComponentEventsHandled}</p>
<p># application events handled: {!v.numApplicationEventsHandled}</p>
<c:eventsNotifier parentName="{#v.name}" />
</div>
</aura:component>
Note: {#v.name} is an unbound expression. This means that any change to the value of the parentName attribute in
c:eventsNotifier doesn’t propagate back to affect the value of the name attribute in c:eventsHandler. For more
information, see Data Binding Between Components on page 44.
CSS source
The CSS is in eventsHandler.css.
/* eventsHandler.css */
.cEventsHandler {
display: block;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
var numComponentEventsHandled =
parseInt(cmp.get("v.numComponentEventsHandled")) + 1;
cmp.set("v.numComponentEventsHandled", numComponentEventsHandled);
},
var numApplicationEventsHandled =
parseInt(cmp.get("v.numApplicationEventsHandled")) + 1;
cmp.set("v.numApplicationEventsHandled", numApplicationEventsHandled);
}
}
The name attribute is not set yet. We will see how this attribute is set and surfaced in eventsContainer.cmp.
213
Communicating with Events Firing Lightning Events from Non-Lightning Code
You can click buttons and the UI now changes to indicate the type of event. The click count increments to indicate whether it's a
component or application event. We aren't finished yet though. Notice that the source of the event is undefined as the event context
attribute hasn't been set .
Container Component
Here is the markup for eventsContainer.cmp.
<!--c:eventsContainer-->
<aura:component>
<c:eventsHandler name="eventsHandler1"/>
<c:eventsHandler name="eventsHandler2"/>
</aura:component>
The container component contains two handler components. It sets the name attribute of both handler components, which is passed
through to set the parentName attribute of the notifier components. This fills in the gaps in the UI text that we saw when we looked
at the notifier or handler components directly.
Add the c:eventsContainer component to a c:eventsContainerApp application. Navigate to the application.
https://<myDomain>.lightning.force.com/c/eventsContainerApp.app, where <myDomain> is the name
of your custom Salesforce domain.
Click the Click here to fire a component event button for either of the event handlers. Notice that the # component events handled
counter only increments for that component because only the firing component's handler is notified.
Click the Click here to fire an application event button for either of the event handlers. Notice that the # application events handled
counter increments for both the components this time because all the handling components are notified.
SEE ALSO:
Component Event Example
Application Event Example
Event Handling Lifecycle
214
Communicating with Events Events Best Practices
window.opener.$A.get() references the master window where your Lightning app is loaded.
SEE ALSO:
Application Events
Modifying Components Outside the Framework Lifecycle
SEE ALSO:
Handling Events with Client-Side Controllers
Events Anti-Patterns
215
Communicating with Events Events Anti-Patterns
Events Anti-Patterns
These are some anti-patterns that you should avoid when using events.
Instead, use the init hook to run a controller action after component construction but before rendering. Add this code to your
component:
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
For more details, see .Invoking Actions on Component Initialization on page 269.
SEE ALSO:
Create a Custom Renderer
Events Best Practices
Component Creation
The component lifecycle starts when the client sends an HTTP request to the server and the component configuration data is returned
to the client. No server trip is made if the component definition is already on the client from a previous request and the component has
no server dependencies.
Let’s look at an app with several nested components. The framework instantiates the app and goes through the children of the v.body
facet to create each component, First, it creates the component definition, its entire parent hierarchy, and then creates the facets within
those components. The framework also creates any component dependencies on the server, including definitions for attributes, interfaces,
controllers, and actions.
The following image lists the order of component creation.
216
Communicating with Events Events Fired During the Rendering Lifecycle
After creating a component instance, the serialized component definitions and instances are sent down to the client. Definitions are
cached but not the instance data. The client deserializes the response to create the JavaScript objects or maps, resulting in an instance
tree that’s used to render the component instance. When the component tree is ready, the init event is fired for all the components,
starting from the children component and finishing in the parent component.
Component Rendering
The rendering lifecycle happens once in the lifetime of a component unless the component gets explicitly unrendered. When you create
a component:
The following image depicts a typical rendering lifecycle of a component on the client, after the component definitions and instances
are deserialized.
1. The init event is fired by the component service that constructs the components to signal that initialization has completed.
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
You can customize the init handler and add your own controller logic before the component starts rendering. For more information,
see Invoking Actions on Component Initialization on page 269.
2. For each component in the tree, the base implementation of render() or your custom renderer is called to start component
rendering. For more information, see Create a Custom Renderer on page 281. Similar to the component creation process, rendering
starts at the root component, its children components and their super components, if any, and finally the subchildren components.
3. Once your components are rendered to the DOM, afterRender() is called to signal that rendering is completed for each of
these component definitions. It enables you to interact with the DOM tree after the framework rendering service has created the
DOM elements.
4. To indicate that the client is done waiting for a response to the server request XHR, the aura:doneWaiting event is fired. You
can handle this event by adding a handler wired to a client-side controller action.
Note: We don't recommend using the legacy aura:doneWaiting event except as a last resort. The
aura:doneWaiting application event is fired for every server response, even for responses from other components in
your app. Unless your component is running in complete isolation in a standalone app and not included in Lightning Experience
or the Salesforce app, you probably don’t want to handle this application event. The container app may fire server-side actions
and trigger your event handler multiple times.
217
Communicating with Events Events Handled in the Salesforce mobile app and Lightning
Experience
5. The framework fires a render event, enabling you to interact with the DOM tree after the framework’s rendering service has
inserted DOM elements. Handling the render event is preferred to creating a custom renderer and overriding afterRender().
For more information, see Handle the render Event.
6. Finally, the aura:doneRendering event is fired at the end of the rendering lifecycle.
Note: We don't recommend using the legacy aura:doneRendering event except as a last resort. Unless your component
is running in complete isolation in a standalone app and not included in complex apps, such as Lightning Experience or the
Salesforce app, you probably don’t want to handle this application event. The container app may trigger your event handler
multiple times.
During initialization, the init() event is fired in this order: ui:button, ui:myCmp, and myApp.app.
SEE ALSO:
Create a Custom Renderer
System Event Reference
218
Communicating with Events Events Handled in the Salesforce mobile app and Lightning
Experience
force:showToast Displays a toast notification with a message. (Not available on login pages.)
lightning:openFiles Opens one or more file records from the ContentDocument and ContentHubItem
objects.
219
Communicating with Events System Events
}
}
SEE ALSO:
Event Reference
aura:dependency
Fire Component Events
Fire Application Events
System Events
The framework fires several system events during its lifecycle.
You can handle these events in your Lightning apps or components, and within the Salesforce mobile app.
aura:doneWaiting Indicates that the app is done waiting for a response to a server request. This
event is preceded by an aura:waiting event. We don't recommend using
the legacy aura:doneWaiting event except as a last resort. The
aura:doneWaiting application event is fired for every server response,
even for responses from other components in your app. Unless your component
is running in complete isolation in a standalone app and not included in Lightning
Experience or the Salesforce app, you probably don’t want to handle this
application event. The container app may fire server-side actions and trigger your
event handler multiple times.
aura:locationChange Indicates that the hash part of the URL has changed.
aura:noAccess Indicates that a requested resource is not accessible due to security constraints
on that resource.
aura:waiting Indicates that the app is waiting for a response to a server request. We don't
recommend using the legacy aura:waiting event except as a last resort.
220
Communicating with Events System Events
SEE ALSO:
System Event Reference
221
CHAPTER 6 Creating Apps
In this chapter ... Components are the building blocks of an app. This section shows you a typical workflow to put the
pieces together to create a new app.
• App Overview
First, you should decide whether you’re creating a component for a standalone app or for Salesforce
• Designing App UI
apps, such as Lightning Experience or Salesforce for Android, iOS, and mobile web. Both components
• Creating App can access your Salesforce data, but only a component created for Lightning Experience or Salesforce
Templates for Android, iOS, and mobile web can automatically handle Salesforce events that take advantage of
• Developing Secure record create and edit pages, among other benefits.
Code
The Quick Start on page 8 walks you through creating components for a standalone app and
• Validations for components for Salesforce for Android, iOS, and mobile web to help you determine which one you need.
Lightning Component
Code
• Styling Apps
• Using JavaScript
• JavaScript Cookbook
• Using Apex
• Lightning Data
Service
• Lightning Container
• Controlling Access
• Using
Object-Oriented
Development
• Using the AppCache
• Distributing
Applications and
Components
222
Creating Apps App Overview
App Overview
An app is a special top-level component whose markup is in a .app resource.
On a production server, the .app resource is the only addressable unit in a browser URL. Access an app using the URL:
https://<myDomain>.lightning.force.com/<namespace>/<appName>.app, where <myDomain> is the
name of your custom Salesforce domain
SEE ALSO:
aura:application
Supported HTML Tags
Designing App UI
Design your app's UI by including markup in the .app resource. Each part of your UI corresponds to a component, which can in turn
contain nested components. Compose components to create a sophisticated app.
An app’s markup starts with the <aura:application> tag.
Note: Creating a standalone app enables you to host your components outside of Salesforce for Android, iOS, and mobile web
or Lightning Experience, such as with Lightning Out or Lightning components in Visualforce pages. To learn more about the
<aura:application> tag, see aura:application.
Let's look at a sample.app file, which starts with the <aura:application> tag.
<aura:application extends="force:slds">
<lightning:layout>
<lightning:layoutItem padding="around-large">
<h1 class="slds-text-heading_large">Sample App</h1>
</lightning:layoutItem>
</lightning:layout>
<lightning:layout>
<lightning:layoutItem padding="around-small">
Sidebar
<!-- Other component markup here -->
</lightning:layoutItem>
<lightning:layoutItem padding="around-small">
Content
<!-- Other component markup here -->
</lightning:layoutItem>
</lightning:layout>
</aura:application>
The sample.app file contains HTML tags, such as <h1>, as well as components, such as <lightning:layout>. We won't go
into the details for all the components here but note how simple the markup is. The <lightning:layoutItem> component
can contain other components or HTML markup.
SEE ALSO:
aura:application
223
Creating Apps Creating App Templates
Note how the component extends aura:template and sets the title attribute using aura:set.
The app points at the custom template by setting the template system attribute in <aura:application>.
<aura:application template="np:template">
...
</aura:application>
A template can only extend a component or another template. A component or an application can't extend a template.
IN THIS SECTION:
What is LockerService?
LockerService is a powerful security architecture for Lightning components. LockerService enhances security by isolating Lightning
components in their own namespace. LockerService also promotes best practices that improve the supportability of your code by
only allowing access to supported APIs and eliminating access to non-published framework internals.
Content Security Policy Overview
The Lightning Component framework uses Content Security Policy (CSP), which is a W3C standard, to control the source of content
that can be loaded on a page.
What is LockerService?
LockerService is a powerful security architecture for Lightning components. LockerService enhances security by isolating Lightning
components in their own namespace. LockerService also promotes best practices that improve the supportability of your code by only
allowing access to supported APIs and eliminating access to non-published framework internals.
224
Creating Apps What is LockerService?
IN THIS SECTION:
JavaScript ES5 Strict Mode Enforcement
LockerService implicitly enables JavaScript ES5 strict mode. You don’t need to specify "use strict" in your code. JavaScript
strict mode makes code more robust and supportable. For example, it throws some errors that would otherwise be suppressed.
DOM Access Containment
A component can only traverse the DOM and access elements created by a component in the same namespace. This behavior
prevents the anti-pattern of reaching into DOM elements owned by components in another namespace.
Secure Wrappers for Global References
LockerService applies restrictions to global references. LockerService provides secure versions of non-intrinsic objects, such as
window. For example, the secure version of window is SecureWindow. You can interact with a secure wrapper in the same
way as you interact with the non-intrinsic object, but the secure wrappers filter access to the object and its properties. The secure
wrappers expose a subset of the API of the underlying objects.
Access to Supported JavaScript API Framework Methods Only
You can access published, supported JavaScript API framework methods only. These methods are published in the reference doc
app at https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is
the name of your custom Salesforce domain. Previously, unsupported methods were accessible, which exposed your code to the
risk of breaking when unsupported methods were changed or removed.
What Does LockerService Affect?
Find out what’s affected and what’s not affected by LockerService.
Disabling LockerService for a Component
You can disable LockerService for a component by setting API version 39.0 or lower for the component. If a component is set to at
least API version 40.0, LockerService is enabled. API version 40.0 corresponds to Summer ’17, when LockerService was enabled for
all orgs.
Don’t Mix Component API Versions
For consistency and ease of debugging, we recommend that you set the same API version for all custom components in your app,
containment hierarchy (component within component), or extension hierarchy (component extending component).
LockerService Disabled for Unsupported Browsers
LockerService relies on some JavaScript features in the browser: support for strict mode, the Map object, and the Proxy object.
If a browser doesn’t meet the requirements, LockerService can’t enforce all its security features and is disabled.
SEE ALSO:
Content Security Policy Overview
Modifying the DOM
Component Library (Beta)
Salesforce Lightning CLI (Deprecated)
Salesforce Help: Supported Browsers for Lightning Experience
225
Creating Apps What is LockerService?
• You must explicitly attach a variable to the window object to make the variable available outside a library. For more information,
see Sharing JavaScript Code Across Components.
• The libraries that your components use must also work in strict mode.
For more information about JavaScript strict mode, see the Mozilla Developer Network.
Note: It’s an anti-pattern for any component to “reach into” another component, regardless of namespace. LockerService only
prevents cross-namespace access. Your good judgment should prevent cross-component access within your own namespace as
it makes components tightly coupled and more likely to break.
Let’s look at a sample component that demonstrates DOM containment.
<!--c:domLocker-->
<aura:component>
<div id="myDiv" aura:id="div1">
<p>See how LockerService restricts DOM access</p>
</div>
<lightning:button name="myButton" label="Peek in DOM"
aura:id="button1" onclick="{!c.peekInDom}"/>
</aura:component>
// returns an error
//console.log("button1 element: ", cmp.find("button1").getElement());
}
})
226
Creating Apps What is LockerService?
event.getSource().get("v.name")
Returns the name of the button that dispatched the event; in this case, myButton.
IN THIS SECTION:
How LockerService Uses the Proxy Object
LockerService uses the standard JavaScript Proxy object to filter a component’s access to underlying JavaScript objects. The
Proxy object ensures that a component only sees DOM elements created by a component in the same namespace.
SEE ALSO:
What is LockerService?
Using JavaScript
227
Creating Apps What is LockerService?
For more information about standard JavaScript Proxy object, see the Mozilla Developer Network.
SEE ALSO:
DOM Access Containment
Secure Wrappers for Global References
Don’t Mix Component API Versions
Example
Let’s look at a sample component that demonstrates some of the secure wrappers.
<!--c:secureWrappers-->
<aura:component >
228
Creating Apps What is LockerService?
The c:secureWrappers component creates a <div> HTML element and a <lightning:button> component.
Here’s the client-side controller that peeks around in the DOM.
({ /* secureWrappersController.js */
peekInDom : function(cmp, event, helper) {
console.log("div1: ", cmp.find("div1").getElement());
We use console.log() to look at the <div> element and the button. The <div> SecureElement is wrapped in a Proxy
object as a performance optimization so that its data can be lazily filtered when it’s accessed.
We put a debugger statement in the code so that we could inspect the elements in the browser console.
Type these expressions into the browser console and look at the results.
cmp
cmp+""
cmp.find("button1")
cmp.find("button1")+""
window
window+""
$A
$A+""
We add an empty string to some expressions so that the object is converted to a String. You could also use the toString()
method.
Here’s the output.
229
Creating Apps What is LockerService?
IN THIS SECTION:
JavaScript API for Secure Wrappers
The secure wrappers, such as SecureWindow, expose a subset of the API of the objects that they wrap. The API for the secure
wrappers is documented in the LockerService API Viewer app or the reference doc app.
SEE ALSO:
How LockerService Uses the Proxy Object
230
Creating Apps What is LockerService?
SEE ALSO:
Secure Wrappers for Global References
231
Creating Apps What is LockerService?
Component versioning enables you to associate a component with an API version. When you create a component, the default version
is the latest API version. In Developer Console, click Bundle Version Settings in the right panel to set the component version.
For consistency and ease of debugging, we recommend that you set the same API version for all components in your app, when possible.
SEE ALSO:
Don’t Mix Component API Versions
Component Versioning
Create Lightning Components in the Developer Console
Extension Hierarchy
LockerService is enabled for a component or an application purely based on component version. The extension hierarchy for a component
doesn’t factor into LockerService enforcement.
Let’s look at an example where a Car component extends a Vehicle component. Car has API version 39.0 so LockerService is
disabled. Vehicle has API version 40.0 so LockerService is enabled.
Now, let’s say that Vehicle adds an expando property, _counter, to the window object by assigning a value to
window._counter. Since LockerService is enabled for Vehicle, the _counter property is added to SecureWindow, the
secure wrapper for window for the component’s namespace. The property isn’t added to the native window object.
LockerService is disabled for Car so the component has access to the native window object. Car can’t see the _counter property
as it’s only available in the SecureWindow object.
This subtle behavior can cause much gnashing of teeth when your code doesn’t work as you expect. You’ll never get that debugging
time back! Save yourself some grief and use the same API version for all components in an extension hierarchy.
Containment Hierarchy
The containment hierarchy within an application or a component doesn’t factor into LockerService enforcement.
Let’s look at an example where a Bicycle component contains a Wheel component. If Bicycle has API version 40.0, LockerService
is enabled. If Wheel has API version 39.0, LockerService is disabled for Wheel even though it’s contained in a component, Bicycle,
that has LockerService enabled.
Due to the mix of component API versions, you’re likely to run into issues similar to those for the extension hierarchy. We recommend
that you set the same API version for all components in your app or component hierarchy, when possible.
SEE ALSO:
Component Versioning
Disabling LockerService for a Component
Secure Wrappers for Global References
Sharing JavaScript Code Across Components
232
Creating Apps Content Security Policy Overview
Note: The LockerService requirements align with the supported browsers for Lightning Experience, except for IE11. LockerService
is disabled for IE11. We recommend using supported browsers other than IE11 for enhanced security.
SEE ALSO:
Browser Support Considerations for Lightning Components
Salesforce Help: Supported Browsers for Lightning Experience
Browser Support
CSP isn’t enforced by all browsers. For a list of browsers that enforce CSP, see caniuse.com.
Note: IE11 doesn’t support CSP, so we recommend using other supported browsers for enhanced security.
If your app’s functionality isn’t affected, you can ignore the CSP violation.
233
Creating Apps Content Security Policy Overview
IN THIS SECTION:
Critical Update for Stricter CSP Restrictions
The Lightning Component framework already uses Content Security Policy (CSP), which is a W3C standard, to control the source of
content that can be loaded on a page. The “Enable Stricter Content Security Policy for Lightning Components” critical update tightens
CSP to mitigate the risk of cross-site scripting attacks. Stricter CSP is only enforced in sandboxes and Developer Edition orgs.
SEE ALSO:
Browser Support Considerations for Lightning Components
Making API Calls from Components
Create CSP Trusted Sites to Access Third-Party APIs
Salesforce Help: Supported Browsers for Lightning Experience
Note: Stricter CSP was originally part of the LockerService critical update, which was automatically activated for all orgs in Summer
’17. Stricter CSP was decoupled from LockerService in Summer ’17 to give you more time to update your code.
234
Creating Apps Validations for Lightning Component Code
Note: There is a separate “Enable Stricter Content Security Policy for Lightning Components in Communities” critical update to
enable stricter CSP for Communities.
The critical update doesn’t affect:
• Salesforce Classic
• Any apps for Salesforce Classic, such as Salesforce Console in Salesforce Classic
• Lightning Out, which allows you to run Lightning components in a container outside of Lightning apps, such as Lightning components
in Visualforce and Visualforce-based Communities. The container defines the CSP rules.
IN THIS SECTION:
Validation When You Save Code Changes
Lightning component JavaScript code is validated when you save it. Validation ensures that your components are written using best
practices and avoid common pitfalls that can make them incompatible with LockerService. Validation happens automatically when
you save Lightning component resources in the Developer Console, in your favorite IDE, and via API.
Validation During Development Using the Salesforce CLI
Salesforce DX includes a code analysis and validation tool usable via the Salesforce CLI. Use force:lightning:lint to scan
and improve your code during development. Validation using the Salesforce CLI doesn’t just help you avoid LockerService conflicts
and anti-patterns. It’s a terrific practice for improving your code quality and consistency, and to uncover subtle bugs before you
commit them to your codebase.
Review and Resolve Validation Errors and Warnings
When you run validations on your Lightning component code, the results include details for each issue found in the files scanned.
Review the results and resolve problems in your code.
Lightning Component Validation Rules
Rules built into Lightning component code validations cover restrictions under LockerService, correct use of Lightning APIs, and a
number of best practices for writing Lightning component code. Each rule, when triggered by your code, points to an area where
your code might have an issue.
Salesforce Lightning CLI (Deprecated)
Lightning CLI was a Heroku Toolbelt plugin to scan your code for general JavaScript coding issues and Lightning-specific issues.
Lightning CLI is deprecated in favor of the force:lightning:lint tool available in the Salesforce DX CLI.
235
Creating Apps Validation When You Save Code Changes
Validations are applied only to components set to API version 41.0 and later. If the validation service prevents you from saving important
changes, set the component version to API 40.0 or earlier to disable validations temporarily. When you’ve corrected the coding errors,
return your component to API 41.0 or later to save it with passing validations.
236
Creating Apps Validation During Development Using the Salesforce CLI
Validations performed using the Salesforce CLI are different from validations performed at save time in the following important ways.
• The Salesforce CLI uses many more rules to analyze your component code. Save time validations prevent you from making the most
fundamental mistakes only. Validation with the Salesforce CLI errs on the side of giving you more information.
• Validation via the Salesforce CLI ignores the API version of your components. Save time validations are performed only for components
set to API 41.0 and later.
IN THIS SECTION:
Use force:lightning:lint
Run force:lightning:lint just like any other lint command-line tool. The only trick is invoking it through the sfdx
command. Your shell window shows the results.
force:lightning:lint Options
Use options to modify the behavior of force:lightning:lint.
Custom “House Style” Rules
Customize the JavaScript style rules that force:lightning:lint applies to your code.
Use force:lightning:lint
Run force:lightning:lint just like any other lint command-line tool. The only trick is invoking it through the sfdx command.
Your shell window shows the results.
237
Creating Apps Validation During Development Using the Salesforce CLI
Normal Use
You can run the force:lightning:lint lint tool on any folder that contains Lightning components:
sfdx force:lightning:lint ./path/to/lightning/components/
Note: force:lightning:lint runs only on local files. Use Salesforce DX or third-party tools to download your component
code to your machine. Options include Salesforce CLI commands like force:mdapi:retrieve and force:source:pull,
or other tools such as the Force.com IDE, the Ant Migration Tool, or various third-party options.
The default output only shows errors. To see warnings too, use the verbose mode option.
See “Review and Resolve Validation Errors and Warnings” for what to do with the output of running force:lightning:lint.
SEE ALSO:
force:lightning:lint Options
force:lightning:lint Options
Use options to modify the behavior of force:lightning:lint.
Common Options
Filtering Files
Sometimes, you just want to scan a particular kind of file. The --files argument allows you to set a pattern to match files against.
For example, the following command allows you to scan controllers only:
sfdx force:lightning:lint ./path/to/lightning/components/ --files **/*Controller.js
Verbose Mode
The default output shows only errors so you can focus on bigger issues. The --verbose argument allows you to see both warning
messages and errors during the linting process.
For a complete list of command line parameters and how they affect tool behavior, see the Salesforce CLI Command Reference.
force:lightning:lint has built-in help, which you can access with the following command:
SEE ALSO:
Use force:lightning:lint
238
Creating Apps Validation During Development Using the Salesforce CLI
Note: If failure of a custom rule generates a warning, the warning doesn’t appear in the default output. To see warnings, use the
--verbose flag.
The default style rules are provided below. Copy the rules to a new file, and modify them to match your preferred style rules. Alternatively,
you can use your existing ESLint rule configuration file directly. For example:
sfdx force:lightning:lint ./path/to/lightning/components/ --config ~/.eslintrc
Note: Not all ESLint rules can be added or modified using --config. Only rules that we consider benign are usable. And again,
you can’t override the security rules.
module.exports = {
rules: {
// code style rules, these are the default value, but the user can
// customize them via --config in the linter by providing custom values
// for each of these rules.
"no-trailing-spaces": 1,
"no-spaced-func": 1,
"no-mixed-spaces-and-tabs": 0,
"no-multi-spaces": 0,
"no-multiple-empty-lines": 0,
"no-lone-blocks": 1,
"no-lonely-if": 1,
"no-inline-comments": 0,
"no-extra-parens": 0,
"no-extra-semi": 1,
"no-warning-comments": [0, { "terms": ["todo", "fixme", "xxx"], "location": "start"
}],
"block-scoped-var": 1,
"brace-style": [1, "1tbs"],
"camelcase": 1,
"comma-dangle": [1, "never"],
"comma-spacing": 1,
"comma-style": 1,
"complexity": [0, 11],
239
Creating Apps Review and Resolve Validation Errors and Warnings
240
Creating Apps Lightning Component Validation Rules
Results vary in appearance depending on the tool you use to run validations. However, the essential elements are the same for each
issue found.
Issues are displayed, one for each warning or error. Each issue includes the line number, severity, and a brief description of the issue. It
also includes the rule name, which you can use to look up a more detailed description of the issue. See “Lightning Component Validation
Rules” for the rules applied by Lightning code validations, as well as possible resolutions and options for further reading.
Your mission is to review each issue, examine the code in question, and to revise it to eliminate all of the genuine problems.
While no automated tool is perfect, we expect that most errors and warnings generated by Lightning code validations will point to
genuine issues in your code, which you should plan to fix as soon as you can.
SEE ALSO:
Lightning Component Validation Rules
IN THIS SECTION:
Validation Rules Used at Save Time
The following rules are used for validations that are done when you save your Lightning component code.
Validate JavaScript Intrinsic APIs (ecma-intrinsics)
This rule deals with the intrinsic APIs in JavaScript, more formally known as ECMAScript.
Validate Aura API (aura-api)
This rule verifies that use of the framework APIs is according to the published documentation. The use of undocumented or private
features is disallowed.
Validate Lightning Component Public API (secure-component)
This rule validates that only public, supported framework API functions and properties are used.
241
Creating Apps Lightning Component Validation Rules
242
Creating Apps Lightning Component Validation Rules
243
Creating Apps Lightning Component Validation Rules
When LockerService is enabled, the framework prevents the use of unsupported API objects or calls. That means your Lightning
components code is allowed to use:
• Features built into JavaScript (“intrinsic” features)
• Published, supported features built into the Lightning Component framework
• Published, supported features built into LockerService SecureObject objects
What exactly are these “intrinsic APIs”? They’re the APIs defined in the ECMAScript Language Specification. That is, things built into
JavaScript. This includes Annex B of the specification, which deals with legacy browser features that aren’t part of the “core” of JavaScript,
but are nevertheless still supported for JavaScript running inside a web browser.
Note that some features of JavaScript that you might consider intrinsic—for example, the window and document global variables—are
superceded by SecureObject objects, which offer a more constrained API.
Rule Details
This rule verifies that use of the intrinsic JavaScript APIs is according to the published specification. The use of non-standard, deprecated,
and removed language features is disallowed.
Further Reading
• ECMAScript specification
• Annex B: Additional ECMAScript Features for Web Browsers
• Intrinsic Objects (JavaScript)
SEE ALSO:
Validate Aura API (aura-api)
Validate Lightning Component Public API (secure-component)
Validate Secure Document Public API (secure-document)
Validate Secure Window Public API (secure-window)
244
Creating Apps Lightning Component Validation Rules
Rule Details
The following patterns are considered problematic:
Aura.something(); // Use $A instead
$A.util.fake(); // fake is not available in $A.util
Further Reading
For details of all of the methods available in the framework, including $A, see the JavaScript API at
https://myDomain.lightning.force.com/auradocs/reference.app, where myDomain is the name of your
custom Salesforce domain.
SEE ALSO:
Validate Lightning Component Public API (secure-component)
Validate Secure Document Public API (secure-document)
Validate Secure Window Public API (secure-window)
Rule Details
The reference doc app lists the API for SecureComponent. Access the reference doc app at:
https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the name of
your custom Salesforce domain.
The API for SecureComponent is listed at JavaScript API > Component.
SEE ALSO:
Validate Aura API (aura-api)
Validate Secure Document Public API (secure-document)
Validate Secure Window Public API (secure-window)
245
Creating Apps Lightning Component Validation Rules
When LockerService is enabled, the framework prevents the use of unsupported API objects or calls. That means your Lightning
components code is allowed to use:
• Features built into JavaScript (“intrinsic” features)
• Published, supported features built into the Lightning Component framework
• Published, supported features built into LockerService SecureObject objects
Prior to LockerService, when you accessed the document global, you could call any function and access any property available. When
LockerService is enabled, the document global is “wrapped” by a new SecureDocument object, which controls access to document
and its functions and properties. SecureDocument restricts you to using only “safe” features of the document global.
SEE ALSO:
Validate Aura API (aura-api)
Validate Lightning Component Public API (secure-component)
Validate Secure Window Public API (secure-window)
SEE ALSO:
Validate Aura API (aura-api)
Validate Lightning Component Public API (secure-component)
Validate Secure Document Public API (secure-document)
246
Creating Apps Lightning Component Validation Rules
247
Creating Apps Salesforce Lightning CLI (Deprecated)
IN THIS SECTION:
Install Salesforce Lightning CLI (Deprecated)
Lightning CLI was a Heroku Toolbelt plugin to scan your code for general JavaScript coding issues and Lightning-specific issues.
Lightning CLI is deprecated in favor of the force:lightning:lint tool available in the Salesforce DX CLI.
Styling Apps
An app is a special top-level component whose markup is in a .app resource. Just like any other component, you can put CSS in its
bundle in a resource called <appName>.css.
For example, if the app markup is in notes.app, its CSS is in notes.css.
When viewed in Salesforce for Android, iOS, and mobile web and Lightning Experience, the UI components include styling that matches
those visual themes. For example, the ui:button includes the button--neutral class to display a neutral style. The input
components that extend ui:input include the uiInput--input class to display the input fields using a custom font in addition
to other styling.
Note: Styles added to UI components in Salesforce for Android, iOS, and mobile web and Lightning Experience don’t apply to
components in standalone apps.
IN THIS SECTION:
Using the Salesforce Lightning Design System in Apps
The Salesforce Lightning Design System provides a look and feel that’s consistent with Lightning Experience. Use Lightning Design
System styles to give your custom applications a UI that is consistent with Salesforce, without having to reverse-engineer our styles.
Using External CSS
To reference an external CSS resource that you’ve uploaded as a static resource, use a <ltng:require> tag in your .cmp or
.app markup.
248
Creating Apps Using the Salesforce Lightning Design System in Apps
SEE ALSO:
CSS in Components
Add Lightning Components as Custom Tabs in the Salesforce App
Note: We recommend extending force:slds instead so that you automatically get the latest Lightning Design System styles.
If you stick to a specific Lightning Design System version, your app’s styles will gradually start to drift from later versions in Lightning
Experience or incur the cost of duplicate CSS downloads.
To download the latest version of Lightning Design System, generate and download it.
We recommend that you name the Lightning Design System archive static resource using the name format SLDS###, where ### is
the Lightning Design System version number (for example, SLDS203). This lets you have multiple versions of the Lightning Design
System installed, and manage version usage in your components.
To use the static version of the Lightning Design System in a component, include it using <ltng:require/>. For example:
<aura:component>
<ltng:require
249
Creating Apps Using External CSS
styles="{!$Resource.SLDS203 + '/assets/styles/lightning-design-system-ltng.css'}"/>
</aura:component>
SEE ALSO:
Styling with Design Tokens
resourceName is the Name of the static resource. In a managed packaged, the resource name must include the package namespace
prefix, such as $Resource.yourNamespace__resourceName. For a stand-alone static resource, such as an individual graphic
or script, that’s all you need. To reference an item within an archive static resource, add the rest of the path to the item using string
concatenation.
Here are some considerations for loading styles:
Loading Sets of CSS
Specify a comma-separated list of resources in the styles attribute to load a set of CSS.
Note: Due to a quirk in the way $Resource is parsed in expressions, use the join operator to include multiple
$Resource references in a single attribute. For example, if you have more than one style sheet to include into a component
the styles attribute should be something like the following.
styles="{!join(',',
$Resource.myStyles + '/stylesheetOne.css',
$Resource.myStyles + '/moreStyles.css')}"
Loading Order
The styles are loaded in the order that they are listed.
One-Time Loading
The styles load only once, even if they’re specified in multiple <ltng:require> tags in the same component or across different
components.
Encapsulation
To ensure encapsulation and reusability, add the <ltng:require> tag to every .cmp or .app resource that uses the CSS
resource.
<ltng:require> also has a scripts attribute to load a list of JavaScript libraries. The afterScriptsLoaded event enables
you to call a controller action after the scripts are loaded. It's only triggered by loading of the scripts and is never triggered
when the CSS in styles is loaded.
For more information on static resources, see “Static Resources” in the Salesforce online help.
250
Creating Apps More Readable Styling Markup with the join Expression
Styling Components for Lightning Experience or Salesforce for Android, iOS, and
mobile web
To prevent styling conflicts in Lightning Experience or Salesforce for Android, iOS, and mobile web, prefix your external CSS with a unique
namespace. For example, if you prefix your external CSS declarations with .myBootstrap, wrap your component markup with a
<div> tag that specifies the myBootstrap class.
<ltng:require styles="{!$Resource.bootstrap}"/>
<div class="myBootstrap">
<c:myComponent />
<!-- Other component markup -->
</div>
Note: Prefixing your CSS with a unique namespace only applies to external CSS. If you’re using CSS within a component bundle,
the .THIS keyword becomes .namespaceComponentName during runtime.
SEE ALSO:
Using External JavaScript Libraries
CSS in Components
$Resource
Sometimes, if the markup is not broken into multiple lines, it can hurt your eyes or make you mutter profanities under your breath.
<li class="{! 'calendarEvent ' + v.zoomDirection + ' ' + (v.past ? 'pastEvent ' : '') +
(v.zoomed ? 'zoom ' : '') + (v.multiDayFragment ? 'multiDayFragment ' : '')}">
<!-- content here -->
</li>
Try using a join expression instead for easier-to-read markup. This example join expression sets ' ' as the first argument so that
you don’t have to specify it for each subsequent argument in the expression.
<li
class="{! join(' ',
'calendarEvent',
v.zoomDirection,
v.past ? 'pastEvent' : '',
v.zoomed ? 'zoom' : '',
251
Creating Apps Tips for CSS in Components
SEE ALSO:
Expression Functions Reference
Because they can be moved to different locations on the page as well as used on different pages entirely, components must rely on
the normal document flow. Using floats and absolute or fixed positions breaks the layout of the page the component is on. Even if
they don’t break the layout of the page you’re looking at, they will break the layout of some page the component can be put on.
Child elements shouldn’t be styled to be larger than the root element
The Lightning page maintains consistent spacing between components, and can’t do that if child elements are larger than the root
element.
For example, avoid these patterns:
<div style="height: 100px">
<div style="height: 200px">
<!--Other markup here-->
</div>
</div>
252
Creating Apps Vendor Prefixes
Vendor Prefixes
Vendor prefixes, such as —moz- and —webkit- among many others, are automatically added in Lightning.
You only need to write the unprefixed version, and the framework automatically adds any prefixes that are necessary when generating
the CSS output. If you choose to add them, they are used as-is. This enables you to specify alternative values for certain prefixes.
IN THIS SECTION:
Tokens Bundles
Tokens are a type of bundle, just like components, events, and interfaces.
Create a Tokens Bundle
Create a tokens bundle in your org using the Developer Console.
Defining and Using Tokens
A token is a name-value pair that you specify using the <aura:token> component. Define tokens in a tokens bundle, and then
use tokens in your components’ CSS styles resources.
Using Expressions in Tokens
Tokens support a restricted set of expressions. Use expressions to reuse one token value in another token, or to combine tokens to
form a more complex style property.
Extending Tokens Bundles
Use the extends attribute to extend one tokens bundle from another.
253
Creating Apps Styling with Design Tokens
Tokens Bundles
Tokens are a type of bundle, just like components, events, and interfaces.
A tokens bundle contains only one resource, a tokens collection definition.
Note: You can’t edit the tokens bundle name or description in the Developer Console after you create it. The bundle’s
AuraBundleDefinition can be modified using the Metadata API.
A tokens collection starts with the <aura:tokens> tag. It can only contain <aura:token> tags to define tokens.
Tokens collections have restricted support for expressions; see Using Expressions in Tokens. You can’t use other markup, renderers,
controllers, or anything else in a tokens collection.
SEE ALSO:
Using Expressions in Tokens
</aura:tokens>
Note: You can’t edit the tokens bundle name or description in the Developer Console after you create it. The bundle’s
AuraBundleDefinition can be modified using the Metadata API. Although you can set a version on a tokens bundle,
doing so has no effect.
254
Creating Apps Styling with Design Tokens
Defining Tokens
Add new tokens as child components of the bundle’s <aura:tokens> component. For example:
<aura:tokens>
<aura:token name="myBodyTextFontFace"
value="'Salesforce Sans', Helvetica, Arial, sans-serif"/>
<aura:token name="myBodyTextFontWeight" value="normal"/>
<aura:token name="myBackgroundColor" value="#f4f6f9"/>
<aura:token name="myDefaultMargin" value="6px"/>
</aura:tokens>
The only allowed attributes for the <aura:token> tag are name and value.
Using Tokens
Tokens created in the defaultTokens bundle are automatically available in components in your namespace. To use a design token,
reference it using the token() function and the token name in the CSS resource of a component bundle. For example:
.THIS p {
font-family: token(myBodyTextFontFace);
font-weight: token(myBodyTextFontWeight);
}
If you prefer a more concise function name for referencing tokens, you can use the t() function instead of token(). The two are
equivalent. If your token names follow a naming convention or are sufficiently descriptive, the use of the more terse function name
won’t affect the clarity of your CSS styles.
Cross-Referencing Tokens
To reference one token’s value in another token’s definition, wrap the token to be referenced in standard expression syntax.
In the following example, we’ll reference tokens provided by Salesforce in our custom tokens. Although you can’t see the standard tokens
directly, we’ll imagine they look something like the following.
<!-- force:base tokens (SLDS standard tokens) -->
<aura:tokens>
...
<aura:token name="colorBackground" value="rgb(244, 246, 249)" />
<aura:token name="fontFamily" value="'Salesforce Sans', Arial, sans-serif" />
...
</aura:tokens>
255
Creating Apps Styling with Design Tokens
With the preceding in mind, you can reference the standard tokens in your custom tokens, as in the following.
<!-- defaultTokens.tokens (your tokens) -->
<aura:tokens extends="force:base">
<aura:token name="mainColor" value="{! colorBackground }" />
<aura:token name="btnColor" value="{! mainColor }" />
<aura:token name="myFont" value="{! fontFamily }" />
</aura:tokens>
You can only cross-reference tokens defined in the same file or a parent.
Expression syntax in tokens resources is restricted to references to other tokens.
Combining Tokens
To support combining individual token values into more complex CSS style properties, the token() function supports string
concatenation. For example, if you have the following tokens defined:
<!-- defaultTokens.tokens (your tokens) -->
<aura:tokens>
<aura:token name="defaultHorizonalSpacing" value="12px" />
<aura:token name="defaultVerticalSpacing" value="6px" />
</aura:tokens>
You can combine these two tokens in a CSS style definition. For example:
/* myComponent.css */
.THIS div.notification {
margin: token(defaultVerticalSpacing + ' ' + defaultHorizonalSpacing);
/* more styles here */
}
You can mix tokens with strings as much as necessary to create the right style definition. For example, use margin:
token(defaultVerticalSpacing + ' ' + defaultHorizonalSpacing + ' 3px'); to hard code the bottom
spacing in the preceding definition.
The only operator supported within the token() function is “+” for string concatenation.
SEE ALSO:
Defining and Using Tokens
Overriding tokens values works mostly as you’d expect: tokens in a child tokens bundle override tokens with the same name from a
parent bundle. The exception is if you’re using standard tokens. You can’t override standard tokens in Lightning Experience or the
Salesforce app.
256
Creating Apps Styling with Design Tokens
Important: Overriding standard token values is undefined behavior and unsupported. If you create a token with the same name
as a standard token, it overrides the standard token’s value in some contexts, and has no effect in others. This behavior will change
in a future release. Don’t use it.
SEE ALSO:
Using Standard Design Tokens
Once added to defaultTokens (or another tokens bundle that defaultTokens extends) you can reference tokens from
force:base just like your own tokens, using the token() function and token name. For example:
.THIS p {
font-family: token(fontFamily);
font-weight: token(fontWeightRegular);
}
You can mix-and-match your tokens with the standard tokens. It’s a best practice to develop a naming system for your own tokens to
make them easily distinguishable from standard tokens. Consider prefixing your token names with “my”, or something else easily
identifiable.
IN THIS SECTION:
Overriding Standard Tokens (Developer Preview)
Standard tokens provide the look-and-feel of the Lightning Design System in your custom components. You can override standard
tokens to customize and apply branding to your Lightning apps.
Standard Design Tokens—force:base
The standard tokens available are a subset of the design tokens offered in the Salesforce Lightning Design System (SLDS). The
following tokens are available when extending from force:base.
Standard Design Tokens for Communities
Use a subset of the standard design tokens to make your components compatible with the Theme panel in Community Builder. The
Theme panel enables administrators to quickly style an entire community using these properties. Each property in the Theme panel
maps to one or more standard design tokens. When an administrator updates a property in the Theme panel, the system automatically
updates any Lightning components that use the tokens associated with that branding property.
SEE ALSO:
Extending Tokens Bundles
257
Creating Apps Styling with Design Tokens
Note: Overriding standard tokens is available as a developer preview. This feature isn’t generally available unless or until Salesforce
announces its general availability in documentation or in press releases or public statements. You can provide feedback and
suggestions for this feature on the IdeaExchange.
To override a standard token for your Lightning app, create a tokens bundle with a unique name, for example myOverrides. In the
tokens resource, redefine the value for a standard token:
<aura:tokens>
<aura:token name="colorTextBrand" value="#8d7d74"/>
</aura:tokens>
In your Lightning app, specify the tokens bundle in the tokens attribute:
<aura:application tokens="c:myOverrides">
<!-- Your app markup here -->
</aura:application>
Token overrides apply across your app, including resources and components provided by Salesforce and components of your own that
use tokens.
Packaging apps that use the tokens attribute is unsupported.
Important: Overriding standard token values within defaultTokens.tokens, a required resource in a tokens bundle, is
unsupported. If you create a token with the same name as a standard token, it overrides the standard token’s value in some contexts,
and has no effect in others. Overrides should only be done in a separate resource as described above.
SEE ALSO:
Standard Design Tokens—force:base
Available Tokens
Important: The standard token values evolve along with SLDS. Available tokens and their values can change without notice.
Token values presented here are for example only.
borderWidthThick 2px
spacingXxxSmall 0.125rem
spacingXxSmall 0.25rem
spacingXSmall 0.5rem
258
Creating Apps Styling with Design Tokens
spacingMedium 1rem
spacingLarge 1.5rem
spacingXLarge 2rem
sizeXxSmall 6rem
sizeXSmall 12rem
sizeSmall 15rem
sizeMedium 20rem
sizeLarge 25rem
sizeXLarge 40rem
sizeXxLarge 60rem
squareIconUtilitySmall 1rem
squareIconUtilityMedium 1.25rem
squareIconUtilityLarge 1.5rem
squareIconLargeBoundary 3rem
squareIconLargeBoundaryAlt 5rem
squareIconLargeContent 2rem
squareIconMediumBoundary 2rem
squareIconMediumBoundaryAlt 2.25rem
squareIconMediumContent 1rem
squareIconSmallBoundary 1.5rem
squareIconSmallContent .75rem
squareIconXSmallBoundary 1.25rem
squareIconXSmallContent .5rem
fontWeightLight 300
fontWeightRegular 400
fontWeightBold 700
lineHeightHeading 1.25
lineHeightText 1.375
lineHeightReset 1
259
Creating Apps Styling with Design Tokens
borderRadiusSmall .125rem
borderRadiusMedium .25rem
borderRadiusLarge .5rem
borderRadiusPill 15rem
borderRadiusCircle 50%
colorBorderButtonBrandDisabled rgba(0, 0, 0, 0)
260
Creating Apps Styling with Design Tokens
261
Creating Apps Styling with Design Tokens
262
Creating Apps Styling with Design Tokens
263
Creating Apps Styling with Design Tokens
durationInstantly 0s
durationImmediately 0.05s
durationQuickly 0.1s
durationPromptly 0.2s
durationSlowly 0.4s
durationPaused 3.2s
colorBackgroundButtonIcon rgba(0, 0, 0, 0)
264
Creating Apps Styling with Design Tokens
colorBackgroundButtonInverse rgba(0, 0, 0, 0)
colorBackgroundButtonInverseDisabled rgba(0, 0, 0, 0)
lineHeightButton 1.875rem
lineHeightButtonSmall 1.75rem
For a complete list of the design tokens available in the SLDS, see Design Tokens on the Lightning Design System site.
SEE ALSO:
Extending Tokens Bundles
265
Creating Apps Styling with Design Tokens
Important: The standard token values evolve along with SLDS. Available tokens and their values can change without notice.
266
Creating Apps Styling with Design Tokens
In addition, the following standard tokens are available for derived theme properties in the Customer Service (Napili) template. You can
indirectly access derived properties when you update the properties in the Theme panel. For example, if you change the Action Color
property in the Theme panel, the system automatically recalculates the Action Color Darker value based on the new value.
267
Creating Apps Using JavaScript
For a complete list of the design tokens available in the SLDS, see Design Tokens on the Lightning Design System site.
SEE ALSO:
Configure Components for Communities
Using JavaScript
Use JavaScript for client-side code. The $A namespace is the entry point for using the framework in JavaScript code.
For all the methods available in $A, see the JavaScript API at
https://<myDomain>.lightning.force.com/auradocs/reference.app, where <myDomain> is the name of
your custom Salesforce domain.
A component bundle can contain JavaScript code in a client-side controller, helper, or renderer. Client-side controllers are the most
commonly used of these JavaScript resources.
Note: Only use the {! } expression syntax in markup in .app or .cmp resources.
IN THIS SECTION:
Invoking Actions on Component Initialization
Use the init event to initialize a component or fire an event after component construction but before rendering.
Sharing JavaScript Code in a Component Bundle
Put functions that you want to reuse in the component’s helper. Helper functions also enable specialization of tasks, such as processing
data and firing server-side actions.
Sharing JavaScript Code Across Components
You can build simple Lightning components that are entirely self-contained. However, if you build more complex applications, you
probably want to share code, or even client-side data, between components.
Using External JavaScript Libraries
To reference a JavaScript library that you’ve uploaded as a static resource, use a <ltng:require> tag in your .cmp or .app
markup.
Working with Attribute Values in JavaScript
These are useful and common patterns for working with attribute values in JavaScript.
Working with a Component Body in JavaScript
These are useful and common patterns for working with a component’s body in JavaScript.
Working with Events in JavaScript
These are useful and common patterns for working with events in JavaScript.
268
Creating Apps Invoking Actions on Component Initialization
SEE ALSO:
Handling Events with Client-Side Controllers
<p>This value is set in the controller after the component initializes and before
269
Creating Apps Sharing JavaScript Code in a Component Bundle
rendering.</p>
<p><b>{!v.setMeOnInit}</b></p>
</aura:component>
Let's look at the Component source to see how this works. The magic happens in this line.
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
This registers an init event handler for the component. init is a predefined event sent to every component. After the component
is initialized, the doInit action is called in the component's controller. In this sample, the controller action sets an attribute value, but
it could do something more interesting, such as firing an event.
Setting value="{!this}" marks this as a value event. You should always use this setting for an init event.
SEE ALSO:
Handling Events with Client-Side Controllers
Create a Custom Renderer
Component Attributes
Detecting Data Changes with Change Handlers
helperMethod2 : function(component) {
// logic here
this.helperMethod3(var1, var2);
},
270
Creating Apps Sharing JavaScript Code in a Component Bundle
}
})
Creating a Helper
A helper resource is part of the component bundle and is auto-wired via the naming convention, <componentName>Helper.js.
To create a helper using the Developer Console, click HELPER in the sidebar of the component. This helper file is valid for the scope of
the component to which it’s auto-wired.
Helper functions are local to a component, improve code reuse, and move the heavy lifting of JavaScript logic away from the client-side
controller where possible. The following code shows the helper function, which takes in the value parameter set in the controller via
the item argument. The code walks through calling a server-side action and returning a callback but you can do something else in
the helper function.
/* helper */
({
updateItem : function(component, item, callback) {
//Update the items via a server-side action
var action = component.get("c.saveItem");
action.setParams({"item" : item});
//Set any optional callback and enqueue the action
if (callback) {
action.setCallback(this, callback);
}
$A.enqueueAction(action);
}
})
271
Creating Apps Sharing JavaScript Code Across Components
detailsRenderer.js
({
afterRender : function(component, helper){
helper.open(component, null, "new");
}
})
detailsHelper.js
({
open : function(component, note, mode, sort){
if(mode === "new") {
//do something
}
// do something else, such as firing an event
}
})
SEE ALSO:
Create a Custom Renderer
Component Bundles
Handling Events with Client-Side Controllers
272
Creating Apps Sharing JavaScript Code Across Components
getValue: function() {
return value;
}
};
}());
This code uses the JavaScript module pattern. Using this closure-based pattern, the value variable remains private to your library.
Components using the library can’t access value directly.
The most important line of the code to note is:
window._counter = (function() {
You must attach _counter to the window object as a requirement of JavaScript strict mode, which is implicitly enabled in
LockerService. Even though window._counter looks like a global declaration, _counter is attached to the LockerService secure
window object and therefore is a namespace variable, not a global variable.
If you use _counter instead of window._counter, _counter isn’t available. When you try to access it, you get an error similar
to:
Action failed: ... [_counter is not defined]
<h1>MyCounter</h1>
<p>{!v.value}</p>
<lightning:button label="Get Value" onclick="{!c.getValue}"/>
<lightning:button label="Increment" onclick="{!c.increment}"/>
</aura:component>
The <ltng:require> tag loads the counter library and calls the getValue action in the component’s client-side controller after
the library is loaded.
Here’s the client-side controller.
/* MyCounterController.js */
({
getValue : function(component, event, helper) {
component.set("v.value", _counter.getValue());
},
273
Creating Apps Using External JavaScript Libraries
You can access properties of the window object without having to type the window. prefix. Therefore, you can use
_counter.getValue() as shorthand for window._counter.getValue().
Click the buttons to get the value or increment it.
Our counter library shares the counter value between any components that use the library. If you need each component to have a
separate counter, you could modify the counter implementation. To see the per-component code and for more details, see this blog
post about Modularizing Code in Lightning Components.
SEE ALSO:
Using External JavaScript Libraries
ltng:require
JavaScript ES5 Strict Mode Enforcement
<ltng:require scripts="{!$Resource.resourceName}"
afterScriptsLoaded="{!c.afterScriptsLoaded}" />
resourceName is the Name of the static resource. In a managed packaged, the resource name must include the package namespace
prefix, such as $Resource.yourNamespace__resourceName. For a stand-alone static resource, such as an individual graphic
or script, that’s all you need. To reference an item within an archive static resource, add the rest of the path to the item using string
concatenation.
The afterScriptsLoaded action in the client-side controller is called after the scripts are loaded and the component is rendered.
Don't use the init event to access scripts loaded by <ltng:require>. These scripts load asynchronously and are most likely not
available when the init event handler is called.
Here are some considerations for loading scripts:
Loading Sets of Scripts
Specify a comma-separated list of resources in the scripts attribute to load a set of resources.
Note: Due to a quirk in the way $Resource is parsed in expressions, use the join operator to include multiple
$Resource references in a single attribute. For example, if you have more than one JavaScript library to include into a
component the scripts attribute should be something like the following.
scripts="{!join(',',
$Resource.jsLibraries + '/jsLibOne.js',
$Resource.jsLibraries + '/jsLibTwo.js')}"
Loading Order
The scripts are loaded in the order that they are listed.
One-Time Loading
Scripts load only once, even if they’re specified in multiple <ltng:require> tags in the same component or across different
components.
274
Creating Apps Working with Attribute Values in JavaScript
Parallel Loading
Use separate <ltng:require> tags for parallel loading if you have multiple sets of scripts that are not dependent on each
other.
Encapsulation
To ensure encapsulation and reusability, add the <ltng:require> tag to every .cmp or .app resource that uses the JavaScript
library.
<ltng:require> also has a styles attribute to load a list of CSS resources. You can set the scripts and styles attributes
in one <ltng:require> tag.
If you’re using an external library to work with your HTML elements after rendering, use afterScriptsLoaded to wire up a
client-side controller. The following example sets up a chart using the Chart.js library, which is uploaded as a static resource.
<ltng:require scripts="{!$Resource.chart}"
afterScriptsLoaded="{!c.setup}"/>
<canvas aura:id="chart" id="myChart" width="400" height="400"/>
The component’s client-side controller sets up the chart after component initialization and rendering.
setup : function(component, event, helper) {
var data = {
labels: ["January", "February", "March"],
datasets: [{
data: [65, 59, 80, 81, 56, 55, 40]
}]
};
var el = component.find("chart").getElement();
var ctx = el.getContext("2d");
var myNewChart = new Chart(ctx).Line(data);
}
SEE ALSO:
Component Library (Beta)
Content Security Policy Overview
Using External CSS
$Resource
<aura:component>
<aura:attribute name="buttonLabel" type="String"/>
<lightning:button aura:id="button1" label="Button 1"/>
{!v.buttonLabel}
275
Creating Apps Working with a Component Body in JavaScript
This controller action retrieves the label attribute value of a button in a component and sets its value on the buttonLabel
attribute.
({
getLabel : function(component, event, helper) {
var myLabel = component.find("button1").get("v.label");
component.set("v.buttonLabel", myLabel);
}
})
SEE ALSO:
Working with a Component Body in JavaScript
Note: When you use cmp.set("v.body", ...) to set the component body, you must explicitly include {!v.body}
in your component markup.
276
Creating Apps Working with Events in JavaScript
SEE ALSO:
Component Body
Working with Attribute Values in JavaScript
277
Creating Apps Working with Events in JavaScript
Fire an Event
Fire a component event or an application event that’s registered on a component.
//Fire a component event
var compEvent = cmp.getEvent("sampleComponentEvent");
compEvent.fire();
If the event hasn’t been fired, event.getPhase() returns undefined. Possible return values for component and application
events are capture, bubble, and default. Value events return default. For more information, see:
• Component Event Propagation
• Application Event Propagation
278
Creating Apps Working with Events in JavaScript
If paused, the event is not handled until event.resume() is called. You can pause an event in the capture or bubble phase
only. For more information, see:
• Handling Bubbled or Captured Component Events
• Handling Bubbled or Captured Application Events
For example, you can prevent a lightning:button component from submitting a form when it’s clicked.
You can resume a paused event in the capture or bubble phase only. For more information, see:
• Handling Bubbled or Captured Component Events
• Handling Bubbled or Captured Application Events
If the event has already been fired, setting a parameter value has no effect on the event.
If the event has already been fired, setting the parameter values has no effect on the event.
279
Creating Apps Modifying the DOM
You can stop event propagation in the capture or bubble phase only.
IN THIS SECTION:
Modifying DOM Elements Managed by the Lightning Component Framework
The framework creates and manages the DOM elements owned by a component. If you want to modify these DOM elements created
by the framework, modify the DOM elements in the handler for the component’s render event or in a custom renderer. Otherwise,
the framework will override your changes when the component is rerendered.
Modifying DOM Elements Managed by External Libraries
You can use different libraries, such as a charting library, to create and manage DOM elements. You don’t have to modify these DOM
elements within the render event handler or a renderer because they are managed by the external library.
IN THIS SECTION:
Handle the render Event
When a component is rendered or rerendered, the aura:valueRender event, also known as the render event, is fired.
Handle this event to perform post-processing on the DOM or react to component rendering or rerendering. The event is preferred
and easier to use than the alternative of creating a custom renderer.
280
Creating Apps Modifying the DOM
SEE ALSO:
Modifying DOM Elements Managed by External Libraries
Using Expressions
Dynamically Showing or Hiding Markup
In this example, the onRender action in your client-side controller handles initial rendering and rerendering of the component. You
can choose any name for the action attribute.
SEE ALSO:
Invoking Actions on Component Initialization
Create a Custom Renderer
Note: It’s preferred and easier to handle the render event rather than the alternative of creating a custom renderer.
281
Creating Apps Modifying the DOM
• afterRender()
• unrender()
The framework calls these functions as part of the rendering and rerendering lifecycles and we will learn more about them soon. You
can override the base rendering functions in a custom renderer.
Rendering Lifecycle
The rendering lifecycle happens once in the lifetime of a component unless the component gets explicitly unrendered. When you create
a component:
1. The framework fires an init event, enabling you to update a component or fire an event after component construction but before
rendering.
2. The render() method is called to render the component’s body.
3. The afterRender() method is called to enable you to interact with the DOM tree after the framework’s rendering service has
inserted DOM elements.
4. The framework fires a render event, enabling you to interact with the DOM tree after the framework’s rendering service has
inserted DOM elements. Handling the render event is preferred to creating a custom renderer and overriding afterRender().
Rerendering Lifecycle
The rerendering lifecycle automatically handles rerendering of components whenever the underlying data changes. Here is a typical
sequence.
1. A browser event triggers one or more Lightning events.
2. Each Lightning event triggers one or more actions that can update data. The updated data can fire more events.
3. The rendering service tracks the stack of events that are fired.
4. The framework rerenders all the components that own modified data by calling each component’s rerender() method.
5. The framework fires a render event, enabling you to interact with the DOM tree after the framework rerenders a component.
Handling the render event is preferred to creating a custom renderer and overriding rerender().
The component rerendering lifecycle repeats whenever the underlying data changes as long as the component is valid and not explicitly
unrendered.
For more information, see Events Fired During the Rendering Lifecycle .
Custom Renderer
You don’t normally have to write a custom renderer, but it’s useful when you want to interact with the DOM tree after the framework’s
rendering service has inserted DOM elements. If you want to customize rendering behavior and you can’t do it in markup or by using
the init event, you can create a client-side renderer.
A renderer file is part of the component bundle and is auto-wired if you follow the naming convention,
<componentName>Renderer.js. For example, the renderer for sample.cmp would be in sampleRenderer.js.
282
Creating Apps Modifying the DOM
Rerender Components
When an event is fired, it may trigger actions to change data and call rerender() on affected components. The rerender()
function enables components to update themselves based on updates to other components since they were last rendered. This function
doesn’t return a value.
If you update data in a component, the framework automatically calls rerender().
You generally want to extend default rerendering by calling superRerender() from your renderer() function before you
add your custom rerendering code. Calling superRerender() chains the rerendering to the components in the body attribute.
This code outlines a custom rerender() function.
rerender : function(cmp, helper){
this.superRerender();
// do custom rerendering here
}
283
Creating Apps Checking Component Validity
Unrender Components
The base unrender() function deletes all the DOM nodes rendered by a component’s render() function. It is called by the
framework when a component is being destroyed. Customize this behavior by overriding unrender() in your component’s renderer.
This method can be useful when you are working with third-party libraries that are not native to the framework.
You generally want to extend default unrendering by calling superUnrender() from your unrender() function before you
add your custom code.
This code outlines a custom unrender() function.
unrender: function () {
this.superUnrender();
// do custom unrendering here
}
SEE ALSO:
Modifying the DOM
Invoking Actions on Component Initialization
Component Bundles
Modifying Components Outside the Framework Lifecycle
Sharing JavaScript Code in a Component Bundle
SEE ALSO:
ltng:require
Using External JavaScript Libraries
Modifying DOM Elements Managed by the Lightning Component Framework
284
Creating Apps Checking Component Validity
In many scenarios, the cmp.isValid() call isn’t necessary because a null check on a value retrieved from cmp.get() is
sufficient. The main reason to call cmp.isValid() is if you’re making multiple calls against the component and you want to avoid
a null check for each result.
$A.enqueueAction(action);
}
})
The component wired to the client-side controller is passed into the doSomething action as the cmp parameter. When
cmp.get("v.displayResult) is called, we don’t need a cmp.isValid() check.
However, if you hold a reference to another component that may not be valid despite your component being valid, you might need a
cmp.isValid() check for the other component. Let’s look at another example of a component that has a reference to another
component with a local ID of child.
({
"doSomething" : function(cmp) {
var action = cmp.get("c.serverEcho");
var child = cmp.find("child");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
if (child.get("v.displayResult)) {
alert("From server: " + response.getReturnValue());
}
}
// other state handling omitted for brevity
});
$A.enqueueAction(action);
}
})
285
Creating Apps Modifying Components Outside the Framework Lifecycle
changed to:
if (child.get("v.displayResult)) {
You don’t need a child.isValid() call here as child.get("v.displayResult) will return null if the child component
is invalid. Add a child.isValid() check only if you’re making multiple calls against the child component and you want to avoid
a null check for each result.
SEE ALSO:
Handling Events with Client-Side Controllers
Invoking Actions on Component Initialization
Modifying Components Outside the Framework Lifecycle
You don't need to use $A.getCallback() if your code is executed as part of the framework's call stack; for example, your code is
handling an event or in the callback for a server-side controller action.
An example of where you need to use $A.getCallback() is calling window.setTimeout() in an event handler to execute
some logic after a time delay. This puts your code outside the framework's call stack.
This sample sets the visible attribute on a component to true after a five-second delay.
window.setTimeout(
$A.getCallback(function() {
cmp.set("v.visible", true);
286
Creating Apps Validating Fields
}), 5000
);
Note how the code updating a component attribute is wrapped in $A.getCallback(), which ensures that the framework rerenders
the modified component.
Note: You don't need a cmp.isValid() check within this setTimeout() call as the cmp.set() call doesn't do
anything when the component is invalid.
Warning: Don't save a reference to a function wrapped in $A.getCallback(). If you use the reference later to send actions,
the saved transaction state will cause the actions to be aborted.
SEE ALSO:
Handling Events with Client-Side Controllers
Checking Component Validity
Firing Lightning Events from Non-Lightning Code
Communicating with Events
Validating Fields
Validate user input, handle errors, and display error messages on input fields.
Client-side input validation is available for the following components:
• lightning:input
• lightning:select
• lightning:textarea
• ui:input*
Components in the lightning namespace simplify input validation by providing attributes to define error conditions, enabling you
to handle errors by checking the component’s validity state. For example, you can set a minimum length for a field , display an error
message when the condition is not met, and handle the error based on the given validity state. For more information, see the lightning
namespace components in the Component Reference.
Alternatively, input components in the ui namespace let you define and handle errors in a client-side controller, enabling you to iterate
through a list of errors.
The following sections discuss error handling for ui:input* components.
287
Creating Apps Validating Fields
// Is input numeric?
if (isNaN(value)) {
// Set error
inputCmp.set("v.errors", [{message:"Input not a number: " + value}]);
} else {
// Clear error
inputCmp.set("v.errors", null);
}
}
}
When you enter a value and click Submit, doAction in the controller validates the input and displays an error message if the input
is not a number. Entering a valid input clears the error. Add error messages to the input component using the errors attribute.
// is input numeric?
if (isNaN(value)) {
inputCmp.set("v.errors", [{message:"Input not a number: " + value}]);
} else {
inputCmp.set("v.errors", null);
}
},
288
Creating Apps Throwing and Handling Errors
When you enter a value and click Submit, doAction in the controller executes. However, instead of letting the framework handle
the errors, we define a custom error handler using the onError event in <ui:inputNumber>. If the validation fails, doAction
adds an error message using the errors attribute. This automatically fires the handleError custom error handler.
Similarly, you can customize clearing the errors by using the onClearErrors event. See the handleClearError handler in
the controller for an example.
SEE ALSO:
Handling Events with Client-Side Controllers
Component Events
Unrecoverable Errors
Use throw new Error("error message here") for unrecoverable errors, such as an error that prevents your app from
starting successfully. The error message is displayed.
Note: $A.error() is deprecated. Throw the native JavaScript Error object instead by using throw new Error().
This example shows you the basics of throwing an unrecoverable error in a JavaScript controller.
<!--c:unrecoverableError-->
<aura:component>
<lightning:button label="throw error" onclick="{!c.throwError}"/>
</aura:component>
289
Creating Apps Throwing and Handling Errors
Recoverable Errors
To handle recoverable errors, use a component, such as ui:message, to tell users about the problem.
This sample shows you the basics of throwing and catching a recoverable error in a JavaScript controller.
<!--c:recoverableError-->
<aura:component>
<p>Click the button to trigger the controller to throw an error.</p>
<div aura:id="div1"></div>
290
Creating Apps Calling Component Methods
}
}
})
The controller code always throws an error and catches it in this example. The message in the error is displayed to the user in a dynamically
created ui:message component. The body of the ui:message is a ui:outputText component containing the error text.
SEE ALSO:
Validating Fields
Dynamically Creating Components
Syntax
Use this syntax to call a method in JavaScript code.
cmp.sampleMethod(arg1, … argN);
Example
Let's look at an example app.
<!-- c:auraMethodCallerWrapper.app -->
<aura:application >
<c:auraMethodCaller />
</aura:application>
291
Creating Apps Calling Component Methods
...
</aura:component>
c:auraMethodCaller is the parent component. c:auraMethodCaller contains the child component, c:auraMethod.
We'll show how c:auraMethodCaller calls an aura:method defined in c:auraMethod.
We'll use c:auraMethodCallerWrapper.app to see how to return results from synchronous and asynchronous code.
IN THIS SECTION:
Return Result for Synchronous Code
aura:method executes synchronously. A synchronous method finishes executing before it returns. Use the return statement
to return a value from synchronous JavaScript code.
Return Result for Asynchronous Code
aura:method executes synchronously. Use the return statement to return a value from synchronous JavaScript code. JavaScript
code that calls a server-side action is asynchronous. Asynchronous code can continue to execute after it returns. You can’t use the
return statement to return the result of an asynchronous call because the aura:method returns before the asynchronous
code completes. For asynchronous code, use a callback instead of a return statement.
SEE ALSO:
aura:method
Component Events
292
Creating Apps Calling Component Methods
The logParam aura:method has an aura:attribute with a name of message. This attribute enables you to set a
message parameter when you call the logParam method.
The name attribute of logParam configures the aura:method to invoke logParam() in the client-side controller.
An aura:method can have multiple aura:attribute tags. Each aura:attribute corresponds to a parameter that you
can pass into the aura:method. For more details on the syntax, see aura:method.
You don’t explicitly declare a return value in the aura:method markup. You just use a return statement in the JavaScript controller.
logParam() simply logs the parameter passed in and returns the parameter value to demonstrate how to use the return statement.
If your code is synchronous, you can use a return statement; for example, you’re not making an asynchronous server-side action call.
callAuraMethod() finds the child component, c:auraMethod, and calls its logParam aura:method with an argument
for the message parameter of the aura:method.
childCmp.logParam("message sent by parent component");
293
Creating Apps Calling Component Methods
SEE ALSO:
Return Result for Asynchronous Code
Calling Component Methods
aura:method
The echo aura:method has an aura:attribute with a name of callback. This attribute enables you to set a callback that’s
invoked by the aura:method after execution of the server-side action in SimpleServerSideController.
294
Creating Apps Calling Component Methods
var callback;
if (params) {
callback = params.callback;
}
echo() calls the serverEcho() server-side controller action, which we’ll create next.
Note: You can’t return the result with a return statement. The aura:method returns before the asynchronous server-side
action call completes. Instead, we invoke the callback passed into the aura:method and set the result as a parameter in the
callback.
295
Creating Apps Using JavaScript Promises
callAuraMethodServerTrip() finds the child component, c:auraMethod, and calls its echo aura:method. echo()
passes a callback function into the aura:method.
The callback configured in auraMethodCallerController.js logs the result.
function(result) {
console.log("callback for aura:method was executed");
console.log("result: " + result);
}
SEE ALSO:
Return Result for Synchronous Code
Calling Component Methods
aura:method
296
Creating Apps Using JavaScript Promises
We assume that you are familiar with the fundamentals of promises. For a great introduction to promises, see
https://developers.google.com/web/fundamentals/getting-started/primers/promises.
Promises are an optional feature. Some people love them, some don’t. Use them if they make sense for your use case.
Create a Promise
This firstPromise function returns a Promise.
firstPromise : function() {
return new Promise($A.getCallback(function(resolve, reject) {
// do something
The promise constructor determines the conditions for calling resolve() or reject() on the promise.
Chaining Promises
When you need to coordinate or chain together multiple callbacks, promises can be useful. The generic pattern is:
firstPromise()
.then(
// resolve handler
$A.getCallback(function(result) {
return anotherPromise();
}),
// reject handler
$A.getCallback(function(error) {
console.log("Promise was rejected: ", error);
return errorRecoveryPromise();
})
)
.then(
// resolve handler
$A.getCallback(function() {
return yetAnotherPromise();
})
);
The then() method chains multiple promises. In this example, each resolve handler returns another promise.
then() is part of the Promises API. It takes two arguments:
1. A callback for a fulfilled promise (resolve handler)
2. A callback for a rejected promise (reject handler)
297
Creating Apps Making API Calls from Components
The first callback, function(result), is called when resolve() is called in the promise constructor. The result object in
the callback is the object passed as the argument to resolve().
The second callback, function(error), is called when reject() is called in the promise constructor. The error object in
the callback is the object passed as the argument to reject().
Note: The two callbacks are wrapped by $A.getCallback() in our example. What’s that all about? Promises execute their
resolve and reject functions asynchronously so the code is outside the Lightning event loop and normal rendering lifecycle. If the
resolve or reject code makes any calls to the Lightning Component framework, such as setting a component attribute, use
$A.getCallback() to wrap the code. For more information, see Modifying Components Outside the Framework Lifecycle
on page 286.
SEE ALSO:
Storable Actions
298
Creating Apps Create CSP Trusted Sites to Access Third-Party APIs
Important: You can’t load JavaScript resources from a third-party site, even a CSP Trusted Site. To use a JavaScript library from a
third-party site, add it to a static resource, and then add the static resource to your component. After the library is loaded from the
static resource, you can use it as normal.
Sometimes, you have to make API calls from server-side controllers rather than client-side code. In particular, you can’t make calls to
Salesforce APIs from client-side Lightning component code. For information about making API calls from server-side controllers, see
Making API Calls from Apex on page 333.
SEE ALSO:
Content Security Policy Overview
Create CSP Trusted Sites to Access Third-Party APIs
Important: You can’t load JavaScript resources from a third-party site, even a CSP Trusted Site. To use a JavaScript library from a
third-party site, add it to a static resource, and then add the static resource to your component. After the library is loaded from the
static resource, you can use it as normal.
1. From Setup, enter CSP in the Quick Find box, then select CSP Trusted Sites.
This page displays a list of any CSP Trusted Sites already registered, and provides additional information about each site, including
site name and URL.
2. Select New Trusted Site.
3. Name the Trusted Site.
For example, enter Google Maps.
299
Creating Apps JavaScript Cookbook
Warning: The default CSP requires secure (HTTPS) connections for external resources. Configuring a CSP Trusted Site with
an insecure (HTTP) URL is an anti-pattern, and compromises the security of your org.
Note: CSP Trusted Sites affect the CSP header only for Lightning Component framework requests. To enable corresponding access
for Visualforce or Apex, create a Remote Site.
CSP isn’t enforced by all browsers. For a list of browsers that enforce CSP, see caniuse.com.
IE11 doesn’t support CSP, so we recommend using other supported browsers for enhanced security.
SEE ALSO:
Content Security Policy Overview
Making API Calls from Components
Browser Support Considerations for Lightning Components
JavaScript Cookbook
This section includes code snippets and samples that can be used in various JavaScript files.
IN THIS SECTION:
Dynamically Creating Components
Create a component dynamically in your client-side JavaScript code by using the $A.createComponent() method. To create
multiple components, use $A.createComponents().
Detecting Data Changes with Change Handlers
Configure a component to automatically invoke a change handler, which is a client-side controller action, when a value in one of
the component's attributes changes.
Finding Components by ID
Retrieve a component by its ID in JavaScript code.
Dynamically Adding Event Handlers To a Component
You can dynamically add a handler for an event that a component fires.
Dynamically Showing or Hiding Markup
You can use CSS to toggle markup visibility. However, <aura:if> is the preferred approach because it defers the creation and
rendering of the enclosed element tree until needed.
Adding and Removing Styles
You can add or remove a CSS style on a component or element during runtime.
Which Button Was Pressed?
To find out which button was pressed in a component containing multiple buttons, use Component.getLocalId().
Formatting Dates in JavaScript
The AuraLocalizationService JavaScript API provides methods for formatting and localizing dates.
300
Creating Apps Dynamically Creating Components
Note: Use $A.createComponent() instead of the deprecated $A.newCmp() and $A.newCmpAsync() methods.
The client-side controller calls $A.createComponent() to create a ui:button with a local ID and a handler for the onclick
attribute. The function(newButton, ...) callback appends the button to the body of c:createComponent. The
newButton that’s dynamically created by $A.createComponent() is passed as the first argument to the callback.
/*createComponentController.js*/
({
doInit : function(cmp) {
$A.createComponent(
"lightning:button",
{
"aura:id": "findableAuraId",
"label": "Press Me",
"onclick": cmp.getReference("c.handlePress")
},
function(newButton, status, errorMessage){
//Add the new button to the body array
if (status === "SUCCESS") {
var body = cmp.get("v.body");
body.push(newButton);
cmp.set("v.body", body);
}
else if (status === "INCOMPLETE") {
301
Creating Apps Dynamically Creating Components
handlePress : function(cmp) {
// Find the button by the aura:id value
console.log("button: " + cmp.find("findableAuraId"));
console.log("button pressed");
}
})
Note: c:createComponent contains a {!v.body} expression. When you use cmp.set("v.body", ...) to set
the component body, you must explicitly include {!v.body} in your component markup.
302
Creating Apps Detecting Data Changes with Change Handlers
Note: A server-side controller isn’t a server-side dependency for component creation because controller actions are only called
after the component has been created.
A single call to createComponent() or createComponents() can result in many components being created. The call creates
the requested component and all its child components. In addition to performance considerations, server-side component creation has
a limit of 10,000 components that can be created in a single request. If you hit this limit, ensure you’re explicitly declaring component
dependencies with the <aura:dependency> tag or otherwise pre-loading dependent elements, so that your component can be
created on the client side instead.
There’s no limit on component creation on the client side.
Note: Creating components where the top-level components don’t have server dependencies but nested inner components do
isn’t currently supported.
SEE ALSO:
aura:dependency
Invoking Actions on Component Initialization
Dynamically Adding Event Handlers To a Component
The value attribute sets the component attribute that the change handler tracks.
The action attribute sets the client-side controller action to invoke when the attribute value changes.
303
Creating Apps Finding Components by ID
A component can have multiple <aura:handler name="change"> tags to detect changes to different attributes.
In the controller, define the action for the handler.
({
itemsChange: function(cmp, evt) {
console.log("numItems has changed");
console.log("old value: " + evt.getParam("oldValue"));
console.log("current value: " + evt.getParam("value"));
}
})
The valueChange event gives you access to the previous value (oldValue) and the current value (value) in the handler action.
When a change occurs to a value that is represented by the change handler, the framework handles the firing of the event and
rerendering of the component.
SEE ALSO:
Invoking Actions on Component Initialization
aura:valueChange
Finding Components by ID
Retrieve a component by its ID in JavaScript code.
Use aura:id to add a local ID of button1 to the lightning:button component.
<lightning:button aura:id="button1" label="button1"/>
You can find the component by calling cmp.find("button1"), where cmp is a reference to the component containing the
button. The find() function has one parameter, which is the local ID of a component within the markup.
find() returns different types depending on the result.
• If the local ID is unique, find() returns the component.
• If there are multiple components with the same local ID, find() returns an array of the components.
• If there is no matching local ID, find() returns undefined.
SEE ALSO:
Component IDs
Value Providers
304
Creating Apps Dynamically Adding Event Handlers To a Component
event
The first argument is the name of the event that triggers the handler. You can’t force a component to start firing events that it doesn’t
fire, so make sure that this argument corresponds to an event that the component fires. The <aura:registerEvent> tag in
a component’s markup advertises an event that the component fires.
• For a component event, set this argument to match the name attribute of the <aura:registerEvent> tag.
• For an application event, set this argument to match the event descriptor in the format namespace:eventName.
handler
The second argument is the action that handles the event. The format is similar to the value you would put in the action attribute
in the <aura:handler> tag if the handler was statically defined in the markup. There are two options for this argument.
• To use a controller action, use the format: cmp.getReference("c.actionName").
• To use an anonymous function, use the format:
function(auraEvent) {
// handling logic here
}
For a description of the other arguments, see the JavaScript API in the doc reference app.
You can also add an event handler to a component that is created dynamically in the callback function of $A.createComponent().
For more information, see Dynamically Creating Components.
Example
This component has buttons to fire and handle a component event and an application event.
<!--c:dynamicHandler-->
<aura:component >
<aura:registerEvent name="compEvent" type="c:sampleEvent"/>
<aura:registerEvent name="appEvent" type="c:appEvent"/>
<h1>Add dynamic handler for event</h1>
<p>
<lightning:button label="Fire component event" onclick="{!c.fireEvent}" />
<lightning:button label="Add dynamic event handler for component event"
onclick="{!c.addEventHandler}" />
</p>
<p>
<lightning:button label="Fire application event" onclick="{!c.fireAppEvent}" />
<lightning:button label="Add dynamic event handler for application event"
onclick="{!c.addAppEventHandler}" />
</p>
</aura:component>
305
Creating Apps Dynamically Adding Event Handlers To a Component
Notice the first parameter of the addEventHandler() calls. The syntax for a component event is:
cmp.addEventHandler("compEvent", cmp.getReference("c.handleEvent"));
For either a component or application event, you can use an anonymous function as a handler instead of using cmp.getReference()
for a controller action.
For example, the application event handler could be:
cmp.addEventHandler("c:appEvent", function(auraEvent) {
// add handler logic here
306
Creating Apps Dynamically Showing or Hiding Markup
SEE ALSO:
Handling Events with Client-Side Controllers
Handling Component Events
Component Library (Beta)
/*toggleCssController.js*/
({
toggle : function(component, event, helper) {
var toggleText = component.find("text");
$A.util.toggleClass(toggleText, "toggle");
}
})
/*toggleCss.css*/
.THIS.toggle {
display: none;
}
Click the Toggle button to hide or show the text by toggling the CSS class.
SEE ALSO:
Handling Events with Client-Side Controllers
Component Attributes
Adding and Removing Styles
307
Creating Apps Adding and Removing Styles
To append and remove CSS classes from a component or element, use the $A.util.addClass(cmpTarget, 'class')
and $A.util.removeClass(cmpTarget, 'class') methods.
Component source
<aura:component>
<div aura:id="changeIt">Change Me!</div><br />
<lightning:button onclick="{!c.applyCSS}" label="Add Style" />
<lightning:button onclick="{!c.removeCSS}" label="Remove Style" />
</aura:component>
CSS source
.THIS.changeMe {
background-color:yellow;
width:200px;
}
The buttons in this demo are wired to controller actions that append or remove the CSS styles. To append a CSS style to a component,
use $A.util.addClass(cmpTarget, 'class'). Similarly, remove the class by using
$A.util.removeClass(cmpTarget, 'class') in your controller. cmp.find() locates the component using the local
ID, denoted by aura:id="changeIt" in this demo.
Toggling a Class
To toggle a class, use $A.util.toggleClass(cmp, 'class'), which adds or removes the class.
The cmp parameter can be component or a DOM element.
Note: We recommend using a component instead of a DOM element. If the utility function is not used inside afterRender()
or rerender(), passing in cmp.getElement() might result in your class not being applied when the components are
rerendered. For more information, see Events Fired During the Rendering Lifecycle on page 216.
To hide or show markup dynamically, see Dynamically Showing or Hiding Markup on page 307.
To conditionally set a class for an array of components, pass in the array to $A.util.toggleClass().
mapClasses: function(arr, cssClass) {
for(var cmp in arr) {
$A.util.toggleClass(arr[cmp], cssClass);
308
Creating Apps Which Button Was Pressed?
}
}
SEE ALSO:
Handling Events with Client-Side Controllers
CSS in Components
Component Bundles
Note: We recommend that you use lightning:button, a button component that comes with Lightning Design System
styling.
Let’s look at an example with multiple ui:button components. Each button has a unique local ID, set by an aura:id attribute.
<!--c:buttonPressed-->
<aura:component>
<aura:attribute name="whichButton" type="String" />
Use event.getSource() in the client-side controller to get the button component that was clicked. Call getLocalId() to
get the aura:id of the clicked button.
/* buttonPressedController.js */
({
nameThatButton : function(cmp, event, helper) {
var whichOne = event.getSource().getLocalId();
console.log(whichOne);
cmp.set("v.whichButton", whichOne);
}
})
If you’re using lightning:button, use the onclick event handler instead of the press event handler.
<aura:component>
<aura:attribute name="whichButton" type="String" />
309
Creating Apps Formatting Dates in JavaScript
In the client-side controller, you can use one of the following methods to find out which button was clicked.
• event.getSource().getLocalId() returns the aura:id of the clicked button.
• event.getSource().get("v.name") returns the name of the clicked button.
SEE ALSO:
Component IDs
Finding Components by ID
The date parameter can be a String, Number, or most typically a JavaScript Date. If you provide a String value, use ISO 8601 format to
avoid parsing warnings.
The formatString parameter contains tokens to format a date and time. For example, "YYYY-MM-DD" formats 15th
January, 2017 as "2017-01-15". The default format string comes from the $Locale value provider.
This table shows the list of tokens supported in formatString.
Month M 1 ... 12
Year y 2017
Minute m 0 … 59
Second s 0 … 59
AM or PM a AM or PM
AM or PM (identical to a) A AM or PM
310
Creating Apps Using Apex
Week of year w 1 … 53
There are similar methods that differ in their default output values.
• formatDateTime()—The default formatString outputs datetime instead of date.
• formatDateTimeUTC()—Formats a datetime in UTC standard time.
• formatDateUTC()—Formats a date in UTC standard time.
For more information on all the methods in AuraLocalizationService, see the JavaScript API in the Component Library (Beta).
SEE ALSO:
Localization
Using Apex
Use Apex to write server-side code, such as controllers and test classes.
Server-side controllers handle requests from client-side controllers. For example, a client-side controller might handle an event and call
a server-side controller action to persist a record. A server-side controller can also load your record data.
311
Creating Apps Creating Server-Side Logic with Controllers
IN THIS SECTION:
Creating Server-Side Logic with Controllers
The framework supports client-side and server-side controllers. An event is always wired to a client-side controller action, which can
in turn call a server-side controller action. For example, a client-side controller might handle an event and call a server-side controller
action to persist a record.
Working with Salesforce Records
It’s easy to work with your Salesforce records in Apex.
Testing Your Apex Code
Before you can upload a managed package, you must write and execute tests for your Apex code to meet minimum code coverage
requirements. Also, all tests must run without errors when you upload your package to AppExchange.
Making API Calls from Apex
Make API calls from an Apex controller. You can’t make Salesforce API calls from JavaScript code.
Creating Components in Apex
Creating components on the server side in Apex, using the Cmp.<myNamespace>.<myComponent> syntax, is deprecated.
Use $A.createComponent() in client-side JavaScript code instead.
IN THIS SECTION:
Apex Server-Side Controller Overview
Create a server-side controller in Apex and use the @AuraEnabled annotation to enable access to the controller method.
Creating an Apex Server-Side Controller
Use the Developer Console to create an Apex server-side controller.
Returning Data from an Apex Server-Side Controller
Return results from a server-side controller to a client-side controller using the return statement. Results data must be serializable
into JSON format.
Returning Errors from an Apex Server-Side Controller
Create and throw a System.AuraHandledException from your server-side controller to return a custom error message.
AuraEnabled Annotation
The AuraEnabled annotation provides support for Apex methods and properties to be used with the Lightning Component
framework.
Calling a Server-Side Action
Call a server-side controller action from a client-side controller. In the client-side controller, you set a callback, which is called after
the server-side action is completed. A server-side action can return any object containing serializable JSON data.
312
Creating Apps Creating Server-Side Logic with Controllers
In addition to using the @AuraEnabled annotation, your Apex controller must follow these requirements.
• Methods must be static and marked public or global. Non-static methods aren’t supported.
• If a method returns an object, instance methods that retrieve the value of the object’s instance field must be public.
• Use unique names for client-side and server-side actions in a component. A JavaScript function (client-side action) with the same
name as an Apex method (server-side action ) can lead to hard-to-debug issues. In debug mode, the framework logs a browser
console warning about the clashing client-side and server-side action names.
Tip: Don’t store component state in your controller (client-side or server-side). Store state in a component’s client-side attributes
instead.
For more information, see Classes in the Apex Developer Guide.
SEE ALSO:
Calling a Server-Side Action
Creating an Apex Server-Side Controller
AuraEnabled Annotation
313
Creating Apps Creating Server-Side Logic with Controllers
SEE ALSO:
Salesforce Help: Open the Developer Console
Returning Data from an Apex Server-Side Controller
AuraEnabled Annotation
@AuraEnabled
public static List<SimpleAccount> getAccounts() {
314
Creating Apps Creating Server-Side Logic with Controllers
List<Account> accounts = [SELECT Id, Name, Phone FROM Account LIMIT 5];
for (Account acct : accounts) {
simpleAccounts.add(new SimpleAccount(acct.Id, acct.Name, acct.Phone));
}
return simpleAccounts;
}
}
When an instance of an Apex class is returned from a server-side action, the instance is serialized to JSON by the framework. Only the
values of public instance properties and methods annotated with @AuraEnabled are serialized and returned.
For example, here’s a simple “wrapper” Apex class that contains a few details for an account record. This class is used to package a few
details of an account record in a serializable format.
public class SimpleAccount {
When returned from a remote Apex controller action, the Id and Name properties are defined on the client-side. However, because it
doesn’t have the @AuraEnabled annotation, the Phone property isn’t serialized on the server side, and isn’t returned as part of the
result data.
SEE ALSO:
AuraEnabled Annotation
Custom Apex Class Types
315
Creating Apps Creating Server-Side Logic with Controllers
The benefit of throwing AuraHandledException, instead of letting a system exception be returned, is that you have a chance
to handle the exception more gracefully in your client code. System exceptions have important details stripped out for security purposes,
and result in the dreaded “An internal server error has occurred…” message. Nobody likes that. When you use an
AuraHandledException you have an opportunity to add some detail back into the response returned to your client-side code.
More importantly, you can choose a better message to show your users.
Here’s an example of creating and throwing an AuraHandledException in response to bad input. However, the real benefit of
using AuraHandledException comes when you use it in response to a system exception. For example, throw an
AuraHandledException in response to catching a DML exception, instead of allowing that to propagate down to your client
component code.
public with sharing class SimpleErrorController {
@AuraEnabled
public static String helloOrThrowAnError(String name) {
AuraEnabled Annotation
The AuraEnabled annotation provides support for Apex methods and properties to be used with the Lightning Component
framework.
The AuraEnabled annotation is overloaded, and is used for two separate and distinct purposes.
• Use @AuraEnabled on Apex class static methods to make them accessible as remote controller actions in your Lightning
components.
• Use @AuraEnabled on Apex instance methods and properties to make them serializable when an instance of the class is
returned as data from a server-side action.
Important:
• Don’t mix-and-match these different uses of @AuraEnabled in the same Apex class.
316
Creating Apps Creating Server-Side Logic with Controllers
• Only static @AuraEnabled Apex methods can be called from client-side code. Visualforce-style instance properties and
getter/setter methods aren’t available. Use client-side component attributes instead.
SEE ALSO:
Returning Data from an Apex Server-Side Controller
Custom Apex Class Types
This client-side controller includes an echo action that executes a serverEcho method on a server-side controller.
Tip: Use unique names for client-side and server-side actions in a component. A JavaScript function (client-side action) with the
same name as an Apex method (server-side action ) can lead to hard-to-debug issues. In debug mode, the framework logs a
browser console warning about the clashing client-side and server-side action names.
({
"echo" : function(cmp) {
// create a one-time use instance of the serverEcho action
// in the server-side controller
var action = cmp.get("c.serverEcho");
action.setParams({ firstName : cmp.get("v.firstName") });
317
Creating Apps Creating Server-Side Logic with Controllers
In the client-side controller, we use the value provider of c to invoke a server-side controller action. We also use the c syntax in markup
to invoke a client-side controller action.
The cmp.get("c.serverEcho") call indicates that we’re calling the serverEcho method in the server-side controller. The
method name in the server-side controller must match everything after the c. in the client-side call. In this case, that’s serverEcho.
Use action.setParams() to set data to be passed to the server-side controller. The following call sets the value of the firstName
argument on the server-side controller’s serverEcho method based on the firstName attribute value.
action.setParams({ firstName : cmp.get("v.firstName") });
action.setCallback() sets a callback action that is invoked after the server-side action returns.
The server-side action results are available in the response variable, which is the argument of the callback.
response.getState() gets the state of the action returned from the server.
Note: You don’t need a cmp.isValid() check in the callback in a client-side controller when you reference the component
associated with the client-side controller. The framework automatically checks that the component is valid.
response.getReturnValue() gets the value returned from the server. In this example, the callback function alerts the user
with the value returned from the server.
$A.enqueueAction(action) adds the server-side controller action to the queue of actions to be executed. All actions that are
enqueued will run at the end of the event loop. Rather than sending a separate request for each individual action, the framework
processes the event chain and batches the actions in the queue into one request. The actions are asynchronous and have callbacks.
Tip: If your action is not executing, make sure that you’re not executing code outside the framework’s normal rerendering lifecycle.
For example, if you use window.setTimeout() in an event handler to execute some logic after a time delay, wrap your
code in $A.getCallback(). You don't need to use $A.getCallback() if your code is executed as part of the framework's
call stack; for example, your code is handling an event or in the callback for a server-side controller action.
318
Creating Apps Creating Server-Side Logic with Controllers
IN THIS SECTION:
Action States
Call a server-side controller action from a client-side controller. The action can have different states during processing.
SEE ALSO:
Handling Events with Client-Side Controllers
Queueing of Server-Side Actions
Action States
Checking Component Validity
Action States
Call a server-side controller action from a client-side controller. The action can have different states during processing.
The possible action states are:
NEW
The action was created but is not in progress yet
RUNNING
The action is in progress
SUCCESS
The action executed successfully
ERROR
The server returned an error
INCOMPLETE
The server didn’t return a response. The server might be down or the client might be offline. The framework guarantees that an
action’s callback is always invoked as long as the component is valid. If the socket to the server is never successfully opened, or closes
abruptly, or any other network error occurs, the XHR resolves and the callback is invoked with state equal to INCOMPLETE.
ABORTED
The action was aborted. This action state is deprecated. A callback for an aborted action is never executed so you can’t do anything
to handle this state.
SEE ALSO:
Calling a Server-Side Action
319
Creating Apps Creating Server-Side Logic with Controllers
The framework uses a stack to keep track of the actions to send to the server. When the browser finishes processing events and JavaScript
on the client, the enqueued actions on the stack are sent to the server in a batch.
Tip: If your action is not executing, make sure that you’re not executing code outside the framework’s normal rerendering lifecycle.
For example, if you use window.setTimeout() in an event handler to execute some logic after a time delay, wrap your
code in $A.getCallback().
There are some properties that you can set on an action to influence how the framework manages the action while it’s in the queue
waiting to be sent to the server. For more information, see:
• Foreground and Background Actions on page 320
• Storable Actions on page 321
• Abortable Actions on page 324
SEE ALSO:
Modifying Components Outside the Framework Lifecycle
Batching of Actions
Multiple queued foreground actions are batched in a single request (XHR) to minimize network traffic. The batching of actions is also
known as boxcar’ing, similar to a train that couples boxcars together.
The server sends the XHR response to the client when all actions have been processed on the server. If a long-running action is in the
boxcar, the XHR response is held until that long-running action completes. Marking an action as background results in that action being
sent separately from any foreground actions. The separate transmission ensures that the background action doesn’t impact the response
time of the foreground actions.
When the server-side actions in the queue are executed, the foreground actions execute first and then the background actions execute.
Background actions run in parallel with foreground actions and responses of foreground and background actions may come back in
either order.
We don’t make any guarantees for the order of execution of action callbacks. XHR responses may return in a different order than the
order in which the XHR requests were sent due to server processing time.
Note: Don’t rely on each background action being sent in its own request as that behavior isn’t guaranteed and it can lead to
performance issues. Remember that the motivation for background actions is to isolate long-running requests into a separate
request to avoid slowing the response for foreground actions.
If two actions must be executed sequentially, the component must orchestrate the ordering. The component can enqueue the first
action. In the first action’s callback, the component can then enqueue the second action.
320
Creating Apps Creating Server-Side Logic with Controllers
Even with separate throttling, background actions might affect performance in some conditions, such as an excessive number of requests
to the server.
Note: A background action can’t be set back to a foreground action. In other words, calling setBackground to set it to
false will have no effect.
SEE ALSO:
Queueing of Server-Side Actions
Calling a Server-Side Action
Storable Actions
Enhance your component’s performance by marking actions as storable to quickly show cached data from client-side storage without
waiting for a server trip. If the cached data is stale, the framework retrieves the latest data from the server. Caching is especially beneficial
for users on high latency, slow, or unreliable connections such as 3G networks.
Warning:
• A storable action might result in no call to the server. Never mark as storable an action that updates or deletes data.
• For storable actions in the cache, the framework returns the cached response immediately and also refreshes the data if it’s
stale. Therefore, storable actions might have their callbacks invoked more than once: first with cached data, then with updated
data from the server.
Most server requests are read-only and idempotent, which means that a request can be repeated or retried as often as necessary without
causing data changes. The responses to idempotent actions can be cached and quickly reused for subsequent identical actions. For
storable actions, the key for determining an identical action is a combination of:
• Apex controller name
• Method name
• Method parameter values
The setStorable function takes an optional argument, which is a configuration map of key-value pairs representing the storage
options and values to set. You can only set the following property:
321
Creating Apps Creating Server-Side Logic with Controllers
ignoreExisting
Set to true to bypass the cache. The default value is false.
This property is useful when you know that any cached data is invalid, such as after a record modification. This property should be
used rarely because it explicitly defeats caching.
To set the storage options for the action response, pass this configuration map into setStorable(configObj).
IN THIS SECTION:
Lifecycle of Storable Actions
This image describes the sequence of callback execution for storable actions.
Enable Storable Actions in an Application
Storable actions are automatically configured in Lightning Experience and the Salesforce mobile app. To use storable actions in a
standalone app (.app resource), you must configure client-side storage for cached action responses.
Storage Service Adapters
The Storage Service supports multiple implementations of storage and selects an adapter at runtime based on browser support and
specified characteristics of persistence and security. Storage can be persistent and secure. With persistent storage, cached data is
preserved between user sessions in the browser. With secure storage, cached data is encrypted.
Note: An action might have its callback invoked more than once:
• First with the cached response, if it’s in storage.
• Second with updated data from the server, if the stored response has exceeded the time to refresh entries.
Cache Miss
If the action is not a cache hit as it doesn’t match a storage entry:
322
Creating Apps Creating Server-Side Logic with Controllers
Cache Hit
If the action is a cache hit as it matches a storage entry:
1. The callback in the client-side controller is executed with the cached action response.
2. If the response has been cached for longer than the refresh time, the storage entry is refreshed.
When an application enables storable actions, a refresh time is configured. The refresh time is the duration in seconds before an
entry is refreshed in storage. The refresh time is automatically configured in Lightning Experience and the Salesforce mobile app.
SEE ALSO:
Storable Actions
Enable Storable Actions in an Application
name
The storage name must be actions. Storable actions are the only currently supported type of storage.
persistent
Set to true to preserve cached data between user sessions in the browser.
secure
Set to true to encrypt cached data.
323
Creating Apps Creating Server-Side Logic with Controllers
maxsize
The maximum size in KB of the storage.
defaultExpiration
The duration in seconds that an entry is retained in storage.
defaultAutoRefreshInterval
The duration in seconds before an entry is refreshed in storage.
Storable actions use the Storage Service. The Storage Service supports multiple implementations of storage and selects an adapter at
runtime based on browser support and specified characteristics of persistence and security.
SEE ALSO:
Storage Service Adapters
IndexedDB
(Persistent but not secure) Provides access to an API for client-side storage and search of structured data. For more information, see
the Indexed Database API.
Memory
(Not persistent but secure) Provides access to JavaScript memory for caching data. The stored cache persists only per browser page.
Browsing to a new page resets the cache.
The Storage Service selects a storage adapter on your behalf that matches the persistent and secure options you specify when initializing
the service. For example, if you request a persistent and insecure storage service, the Storage Service returns the IndexedDB storage if
the browser supports it.
Abortable Actions
Mark an action as abortable to make it potentially abortable while it's queued to be sent to the server. An abortable action in the queue
is not sent to the server if the component that created the action is no longer valid, that is cmp.isValid() == false. A component
is automatically destroyed and marked invalid by the framework when it is unrendered.
Note: We recommend that you only use abortable actions for read-only operations as they are not guaranteed to be sent to the
server.
An abortable action is sent to the server and executed normally unless the component that created the action is invalid before the action
is sent to the server.
A non-abortable action is always sent to the server and can't be aborted in the queue.
324
Creating Apps Working with Salesforce Records
If an action response returns from the server and the associated component is now invalid, the logic has been executed on the server
but the action callback isn’t executed. This is true whether or not the action is marked as abortable.
SEE ALSO:
Creating Server-Side Logic with Controllers
Queueing of Server-Side Actions
Calling a Server-Side Action
For more information on working on records with Apex, see Working with Data in Apex.
This example controller persists an updated Account record. Note that the update method has the @AuraEnabled annotation,
which enables it to be called as a server-side controller action.
public with sharing class AccountController {
@AuraEnabled
public static void updateAnnualRevenue(String accountId, Decimal annualRevenue) {
Account acct = [SELECT Id, Name, BillingCity FROM Account WHERE Id = :accountId];
acct.AnnualRevenue = annualRevenue;
For an example of calling Apex code from JavaScript code, see the Quick Start on page 8.
325
Creating Apps Working with Salesforce Records
@AuraEnabled
public static List<Opportunity> getOpportunities() {
List<Opportunity> opportunities =
[SELECT Id, Name, CloseDate FROM Opportunity];
return opportunities;
}
@AuraEnabled
public static Opportunity getOpportunity(Id id) {
Opportunity opportunity = [
SELECT Id, Account.Name, Name, CloseDate,
Owner.Name, Amount, Description, StageName
FROM Opportunity
WHERE Id = :id
];
This example component uses the previous server-side controller to display a list of opportunity records when you press a button.
<aura:component controller="OpportunityController">
<aura:attribute name="opportunities" type="Opportunity[]"/>
When you press the button, the following client-side controller calls the getOpportunities() server-side controller and sets the
opportunities attribute on the component. For more information about calling server-side controller methods, see Calling a
Server-Side Action on page 317.
({
getOpps: function(cmp){
var action = cmp.get("c.getOpportunities");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.opportunities", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
326
Creating Apps Working with Salesforce Records
Note: To load record data during component initialization, use the init handler.
@AuraEnabled
public static List<MyObj__c> getMyObjects() {
This example component uses the previous controller to display a list of records from the myObj__c custom object.
<aura:component controller="MyObjController"/>
<aura:attribute name="myObjects" type="namespace.MyObj__c[]"/>
<aura:iteration items="{!v.myObjects}" var="obj">
{!obj.Name}, {!obj.namespace__myField__c}
</aura:iteration>
This client-side controller sets the myObjects component attribute with the record data by calling the getMyObjects() method
in the server-side controller. This step can also be done during component initialization using the init handler.
getMyObjects: function(cmp){
var action = cmp.get("c.getMyObjects");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.myObjects", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
For an example on loading and updating records using controllers, see the Quick Start on page 8.
IN THIS SECTION:
CRUD and Field-Level Security (FLS)
Lightning components don’t automatically enforce CRUD and FLS when you reference objects or retrieve the objects from an Apex
controller. This means that the framework continues to display records and fields for which users don’t have CRUD access and FLS
visibility. You must manually enforce CRUD and FLS in your Apex controllers.
Saving Records
You can take advantage of the built-in create and edit record pages in Salesforce for Android, iOS, and mobile web to create or edit
records via a Lightning component.
327
Creating Apps Working with Salesforce Records
Deleting Records
You can delete records via a Lightning component to remove them from both the view and database.
SEE ALSO:
CRUD and Field-Level Security (FLS)
328
Creating Apps Working with Salesforce Records
Note: For more information, see the articles on Enforcing CRUD and FLS and Lightning Security.
Saving Records
You can take advantage of the built-in create and edit record pages in Salesforce for Android, iOS, and mobile web to create or edit
records via a Lightning component.
The following component contains a button that calls a client-side controller to display the edit record page.
<aura:component>
<lightning:button label="Edit Record" onclick="{!c.edit}"/>
</aura:component>
The client-side controller fires the force:recordEdit event, which displays the edit record page for a given contact ID. For this
event to be handled correctly, the component must be included in Salesforce for Android, iOS, and mobile web.
edit : function(component, event, helper) {
var editRecordEvent = $A.get("e.force:editRecord");
editRecordEvent.setParams({
"recordId": component.get("v.contact.Id")
});
editRecordEvent.fire();
}
Note: If you create a custom form to handle record updates, you must provide your own field validation.
Create an Apex controller to save your updates with the upsert operation. The following example is an Apex controller for upserting
record data.
@AuraEnabled
public static Expense__c saveExpense(Expense__c expense) {
// Perform isUpdateable() check here
upsert expense;
return expense;
}
329
Creating Apps Working with Salesforce Records
Call a client-side controller from your component. For example, <lightning:button label="Submit"
onclick="{!c.createExpense}"/>.
In your client-side controller, provide any field validation and pass the record data to a helper function.
createExpense : function(component, event, helper) {
// Validate form fields
// Pass form data to a helper function
var newExpense = component.get("v.newExpense");
helper.createExpense(component, newExpense);
}
In your component helper, get an instance of the server-side controller and set a callback. The following example upserts a record on a
custom object. Recall that setParams() sets the value of the expense argument on the server-side controller’s saveExpense()
method.
createExpense: function(component, expense) {
//Save the expense and update the view
this.upsertExpense(component, expense, function(a) {
var expenses = component.get("v.expenses");
expenses.push(a.getReturnValue());
component.set("v.expenses", expenses);
});
},
upsertExpense : function(component, expense, callback) {
var action = component.get("c.saveExpense");
action.setParams({
"expense": expense
});
if (callback) {
action.setCallback(this, callback);
}
$A.enqueueAction(action);
}
SEE ALSO:
CRUD and Field-Level Security (FLS)
Deleting Records
You can delete records via a Lightning component to remove them from both the view and database.
Create an Apex controller to delete a specified record with the delete operation. The following Apex controller deletes an expense
object record.
@AuraEnabled
public static Expense__c deleteExpense(Expense__c expense) {
// Perform isDeletable() check here
delete expense;
return expense;
}
Depending on how your components are set up, you might need to create an event to tell another component that a record has been
deleted. For example, you have a component that contains a sub-component that is iterated over to display the records. Your
330
Creating Apps Working with Salesforce Records
sub-component contains a button (1), which when pressed fires an event that’s handled by the container component (2), which deletes
the record that’s clicked on.
<aura:registerEvent name="deleteExpenseItem" type="c:deleteExpenseItem"/>
<lightning:button label="Delete" onclick="{!c.delete}"/>
Create a component event to capture and pass the record that’s to be deleted. Name the event deleteExpenseItem.
<aura:event type="COMPONENT">
<aura:attribute name="expense" type="Expense__c"/>
</aura:event>
Then, pass in the record to be deleted and fire the event in your client-side controller.
delete : function(component, evt, helper) {
var expense = component.get("v.expense");
var deleteEvent = component.getEvent("deleteExpenseItem");
deleteEvent.setParams({ "expense": expense }).fire();
}
In the container component, include a handler for the event. In this example, c:expenseList is the sub-component that displays
records.
<aura:handler name="deleteExpenseItem" event="c:deleteExpenseItem" action="c:deleteEvent"/>
<aura:iteration items="{!v.expenses}" var="expense">
331
Creating Apps Testing Your Apex Code
<c:expenseList expense="{!expense}"/>
</aura:iteration>
And handle the event in the client-side controller of the container component.
deleteEvent : function(component, event, helper) {
// Call the helper function to delete record and update view
helper.deleteExpense(component, event.getParam("expense"));
}
Finally, in the helper function of the container component, call your Apex controller to delete the record and update the view.
deleteExpense : function(component, expense, callback) {
// Call the Apex controller and update the view in the callback
var action = component.get("c.deleteExpense");
action.setParams({
"expense": expense
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
// Remove only the deleted expense from view
var expenses = component.get("v.expenses");
var items = [];
for (i = 0; i < expenses.length; i++) {
if(expenses[i]!==expense) {
items.push(expenses[i]);
}
}
component.set("v.expenses", items);
// Other client-side logic
}
});
$A.enqueueAction(action);
}
The helper function calls the Apex controller to delete the record in the database. In the callback function,
component.set("v.expenses", items) updates the view with the updated array of records.
SEE ALSO:
CRUD and Field-Level Security (FLS)
Component Events
Calling a Server-Side Action
332
Creating Apps Making API Calls from Apex
– When deploying Apex to a production organization, each unit test in your organization namespace is executed by default.
– Calls to System.debug are not counted as part of Apex code coverage.
– Test methods and test classes are not counted as part of Apex code coverage.
– While only 75% of your Apex code must be covered by tests, your focus shouldn't be on the percentage of code that is covered.
Instead, you should make sure that every use case of your application is covered, including positive and negative cases, as well
as bulk and single records. This should lead to 75% or more of your code being covered by unit tests.
For more information on distributing Apex code, see the Apex Code Developer's Guide.
SEE ALSO:
Distributing Applications and Components
Note: By security policy, sessions created by Lightning components aren’t enabled for API access. This prevents even your Apex
code from making API calls to Salesforce. Using a named credential for specific API calls allows you to carefully and selectively
bypass this security restriction.
The restrictions on API-enabled sessions aren’t accidental. Carefully review any code that uses a named credential to ensure you’re
not creating a vulnerability.
333
Creating Apps Creating Components in Apex
For information about making API calls from Apex, see the Apex Developer Guide.
SEE ALSO:
Apex Developer Guide: Named Credentials as Callout Endpoints
Making API Calls from Components
Create CSP Trusted Sites to Access Third-Party APIs
Content Security Policy Overview
SEE ALSO:
Dynamically Creating Components
IN THIS SECTION:
Loading a Record
Loading a record is the simplest operation in Lightning Data Service. You can accomplish it entirely in markup.
Saving a Record
To save a record using Lightning Data Service, call saveRecord on the force:recordData component, and pass in a
callback function to be invoked after the save operation completes.
334
Creating Apps Loading a Record
Creating a Record
To create a record using Lightning Data Service, declare force:recordData without assigning a recordId. Next, load a
record template by calling the getNewRecord function on force:recordData. Finally, apply values to the new record,
and save the record by calling the saveRecord function on force:recordData.
Deleting a Record
To delete a record using Lightning Data Service, call deleteRecord on the force:recordData component, and pass in
a callback function to be invoked after the delete operation completes.
Record Changes
To perform tasks beyond rerendering the record when the record changes, handle the recordUpdated event. You can handle
record loaded, updated, and deleted changes, applying different actions to each change type.
Errors
To act when an error occurs, handle the recordUpdated event and handle the case where the changeType is “ERROR”.
Considerations
Lightning Data Service is powerful and simple to use. However, it’s not a complete replacement for writing your own data access
code. Here are some considerations to keep in mind when using it.
Lightning Data Service Example
Here’s a longer, more detailed example of using Lightning Data Service to create a Quick Contact action panel.
SaveRecordResult
Represents the result of a Lightning Data Service operation that makes a persistent change to record data.
Loading a Record
Loading a record is the simplest operation in Lightning Data Service. You can accomplish it entirely in markup.
To load a record using Lightning Data Service, add the force:recordData tag to your component. In the force:recordData
tag, specify the ID of the record to be loaded, a list of fields, and the attribute to which to assign the loaded record. force:recordData
must specify the following.
• The ID of the record to load
• Which component attribute to assign the loaded record
• A list of fields to load
You can explicitly specify the list of fields to load with the fields attribute. For example,
fields="Name,BillingCity,BillingState".
Alternatively, you can specify a layout using the layoutType attribute. All fields on that layout are loaded for the record. Layouts are
typically modified by administrators. Loading record data using layoutType allows your component to adapt to those layout
definitions. Valid values for layoutType are FULL and COMPACT.
<aura:component
implements="flexipage:availableForRecordHome,force:lightningQuickActionWithoutHeader,
force:hasRecordId">
335
Creating Apps Loading a Record
<force:recordData aura:id="recordLoader"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v.record}"
targetFields="{!v.simpleRecord}"
targetError="{!v.recordError}"
recordUpdated="{!c.handleRecordUpdated}"
/>
ldsLoadController.js
({
handleRecordUpdated: function(component, event, helper) {
var eventParams = event.getParams();
if(eventParams.changeType === "LOADED") {
// record is loaded (render other component which needs record data value)
336
Creating Apps Saving a Record
}
})
SEE ALSO:
Configure Components for Lightning Experience Record Pages
Configure Components for Record-Specific Actions
force:recordPreview
Saving a Record
To save a record using Lightning Data Service, call saveRecord on the force:recordData component, and pass in a callback
function to be invoked after the save operation completes.
The Lightning Data Service save operation is used in two cases.
• To save changes to an existing record
• To create and save a new record
To save changes to an existing record, load the record in EDIT mode and call saveRecord on the force:recordData component.
To save a new record, and thus create it, create the record from a record template, as described in Creating a Record. Then call
saveRecord on the force:recordData component.
Note: Since Lightning Data Service records are shared across multiple components, loading records load the component with a
copy of the record instead of a direct reference. If a component loads a record in VIEW mode, Lightning Data Service will automatically
overwrite that copy with a newer copy of the record when the record is changed. If a record is loaded in EDIT mode, the record is
not updated when the record is changed. This prevents unsaved changes from appearing in components that reference the record
while the record is being edited, and prevents any edits in progress from being overwritten. Notifications are still sent in both
modes.
<<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId">
337
Creating Apps Saving a Record
<force:recordData aura:id="recordHandler"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v.record}"
targetFields="{!v.simpleRecord}"
targetError="{!v.recordError}"
mode="EDIT"
recordUpdated="{!c.handleRecordUpdated}"
/>
Note: If you’re using this component with an object that has a first and last name, such as contacts, create a separate
lightning:input component for {!v.simpleRecord.FirstName} and
{!v.simpleRecord.LastName}.
This component loads a record using force:recordData set to EDIT mode, and provides a form for editing record values.
(In this simple example, just the record name field.)
ldsSaveController.js
({
handleSaveRecord: function(component, event, helper) {
component.find("recordHandler").saveRecord($A.getCallback(function(saveResult)
{
// NOTE: If you want a specific behavior(an action or UI behavior) when
this action is successful
// then handle that in a callback (generic logic when record is changed
should be handled in recordUpdated event handler)
if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
338
Creating Apps Saving a Record
/**
* Control the component behavior here when record is changed (via any component)
*/
handleRecordUpdated: function(component, event, helper) {
var eventParams = event.getParams();
if(eventParams.changeType === "CHANGED") {
// get the fields that changed for this record
var changedFields = eventParams.changedFields;
console.log('Fields that are changed: ' + JSON.stringify(changedFields));
The handleSaveRecord action here is a minimal version. There’s no form validation or real error handling. Whatever is
entered in the form is attempted to be saved to the record.
SEE ALSO:
SaveRecordResult
Configure Components for Lightning Experience Record Pages
Configure Components for Record-Specific Actions
force:recordPreview
339
Creating Apps Creating a Record
Creating a Record
To create a record using Lightning Data Service, declare force:recordData without assigning a recordId. Next, load a record
template by calling the getNewRecord function on force:recordData. Finally, apply values to the new record, and save the
record by calling the saveRecord function on force:recordData.
1. Call getNewRecord to create an empty record from a record template. You can use this record as the backing store for a form
or otherwise have its values set to data intended to be saved.
2. Call saveRecord to commit the record. This is described in Saving a Record.
recordTypeId String The 18 character ID of the record type for the new record.
If not specified, the default record type for the object is used, as defined in the
user’s profile.
skipCache Boolean Whether to load the record template from the server instead of the client-side
Lightning Data Service cache. Defaults to false.
callback Function A function invoked after the empty record is created. This function receives no
arguments.
getNewRecord doesn’t return a result. It simply prepares an empty record and assigns it to the targetRecord attribute.
<force:recordData aura:id="contactRecordCreator"
layoutType="FULL"
targetRecord="{!v.newContact}"
targetFields="{!v.simpleNewContact}"
340
Creating Apps Creating a Record
targetError="{!v.newContactError}" />
</aura:component>
This component doesn’t set the recordId attribute of force:recordData. This tells Lightning Data Service to expect a
new record. Here, that’s created in the component’s init handler.
ldsCreateController.js
({
doInit: function(component, event, helper) {
// Prepare a new record from template
component.find("contactRecordCreator").getNewRecord(
"Contact", // sObject type (objectApiName)
null, // recordTypeId
false, // skip cache?
$A.getCallback(function() {
var rec = component.get("v.newContact");
var error = component.get("v.newContactError");
if(error || (rec === null)) {
console.log("Error initializing record template: " + error);
return;
}
console.log("Record template initialized: " + rec.sobjectType);
})
);
},
341
Creating Apps Creating a Record
component.find("contactRecordCreator").saveRecord(function(saveResult) {
if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
The doInit init handler calls getNewRecord() on the force:recordData component, passing in a simple callback
handler. This call creates a new, empty contact record, which is used by the contact form in the component’s markup.
Note: The callback passed to getNewRecord() must be wrapped in $A.getCallback() to ensure correct access
context when the callback is invoked. If the callback is passed in without being wrapped in $A.getCallback(), any
attempt to access private attributes of your component results in access check failures.
Even if you’re not accessing private attributes, it’s a best practice to always wrap the callback function for getNewRecord()
in $A.getCallback(). Never mix (contexts), never worry.
The handleSaveContact handler is called when the Save Contact button is clicked. It’s a straightforward application of
saving the contact, as described in Saving a Record, and then updating the user interface.
342
Creating Apps Deleting a Record
Note: The helper function, validateContactForm, isn’t shown. It simply validates the form values. For an example
of this validation, see Lightning Data Service Example.
SEE ALSO:
Saving a Record
Configure Components for Lightning Experience Record Pages
Configure Components for Record-Specific Actions
Controlling Access
force:recordPreview
Deleting a Record
To delete a record using Lightning Data Service, call deleteRecord on the force:recordData component, and pass in a
callback function to be invoked after the delete operation completes.
Delete operations with Lightning Data Service are straightforward. The force:recordData tag can include minimal details. If you
don’t need any record data, set the fields attribute to just Id. If you know that the only operation is a delete, any mode can be
used.
To perform the delete operation, call deleteRecord on the force:recordData component from the appropriate controller
action handler. deleteRecord takes one argument, a callback function to be invoked when the operation completes. This callback
function receives a SaveRecordResult as its only parameter. SaveRecordResult includes a state attribute that indicates
success or error, and other details you can use to handle the result of the operation.
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId">
<force:recordData aura:id="recordHandler"
recordId="{!v.recordId}"
fields="Id"
targetError="{!v.recordError}"
recordUpdated="{!c.handleRecordUpdated}" />
<div class="slds-form-element">
343
Creating Apps Deleting a Record
<lightning:button
label="Delete Record"
onclick="{!c.handleDeleteRecord}"
variant="brand" />
</div>
</aura:component>
Notice that the force:recordData tag includes only the recordId and a nearly empty fields list—the absolute
minimum required. If you want to display record values in the user interface, for example, as part of a confirmation message, define
the force:recordData tag as you would for a load operation instead of this minimal delete example.
ldsDeleteController.js
({
handleDeleteRecord: function(component, event, helper) {
component.find("recordHandler").deleteRecord($A.getCallback(function(deleteResult) {
// NOTE: If you want a specific behavior(an action or UI behavior) when
this action is successful
// then handle that in a callback (generic logic when record is changed
should be handled in recordUpdated event handler)
if (deleteResult.state === "SUCCESS" || deleteResult.state === "DRAFT") {
// record is deleted
console.log("Record is deleted.");
} else if (deleteResult.state === "INCOMPLETE") {
console.log("User is offline, device doesn't support drafts.");
} else if (deleteResult.state === "ERROR") {
console.log('Problem deleting record, error: ' +
JSON.stringify(deleteResult.error));
} else {
console.log('Unknown problem, state: ' + deleteResult.state + ', error:
' + JSON.stringify(deleteResult.error));
}
}));
},
/**
* Control the component behavior here when record is changed (via any component)
*/
handleRecordUpdated: function(component, event, helper) {
var eventParams = event.getParams();
if(eventParams.changeType === "CHANGED") {
// record is changed
} else if(eventParams.changeType === "LOADED") {
// record is loaded in the cache
} else if(eventParams.changeType === "REMOVED") {
// record is deleted, show a toast UI message
var resultsToast = $A.get("e.force:showToast");
resultsToast.setParams({
"title": "Deleted",
"message": "The record was deleted."
});
resultsToast.fire();
344
Creating Apps Record Changes
When the record is deleted, navigate away from the record page. Otherwise, you see a “record not found” error when the component
refreshes. Here the controller uses the objectApiName property in the SaveRecordResult provided to the callback
function, and navigates to the object home page.
SEE ALSO:
SaveRecordResult
Configure Components for Lightning Experience Record Pages
Configure Components for Record-Specific Actions
force:recordPreview
Record Changes
To perform tasks beyond rerendering the record when the record changes, handle the recordUpdated event. You can handle
record loaded, updated, and deleted changes, applying different actions to each change type.
If a component performs logic that is record data specific, it must run that logic again when the record changes. A common example is
a business process in which the actions that apply to a record change depending on the record’s values. For example, different actions
apply to opportunities at different stages of the sales cycle.
Note: Lightning Data Service notifies listeners about data changes only if the changed fields are the same as in the listener’s fields
or layout.
<force:recordData aura:id="forceRecord"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v._record}"
targetFields="{!v.simpleRecord}"
targetError="{!v._error}"
recordUpdated="{!c.recordUpdated}" />
345
Creating Apps Errors
When loading a record in edit mode, the record is not automatically updated to prevent edits currently in progress from being
overwritten. To update the record, use the reloadRecord method in the action handler.
<force:recordData aura:id="forceRecord"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v._record}"
targetFields="{!v.simpleRecord}"
targetError="{!v._error}"
mode=”EDIT”
recordUpdated="{!c.recordUpdated}" />
({
recordUpdated : function(component, event, helper) {
Errors
To act when an error occurs, handle the recordUpdated event and handle the case where the changeType is “ERROR”.
<force:recordData aura:id="forceRecord"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v._record}"
targetFields="{!v.simpleRecord}"
targetError="{!v._error}"
recordUpdated="{!c.recordUpdated}" />
346
Creating Apps Considerations
If an error occurs when the record begins to load, targetError is set to a localized error message. An error occurs if:
• Input is invalid because of an invalid attribute value, or combination of attribute values. For example, an invalid recordId,
or omitting both the layoutType and the fields attributes.
• The record isn’t in the cache and the server is unreachable (offline).
If the record becomes inaccessible on the server, the recordUpdated event is fired with changeType set to "REMOVED."
No error is set on targetError, since records becoming inaccessible is sometimes the expected outcome of an operation.
For example, after lead convert the lead record becomes inaccessible.
Records can become inaccessible for the following reasons.
• Record or entity sharing or visibility settings
• Record or entity being deleted
When the record becomes inaccessible on the server, the record’s JavaScript object assigned to targetRecord is unchanged.
Considerations
Lightning Data Service is powerful and simple to use. However, it’s not a complete replacement for writing your own data access code.
Here are some considerations to keep in mind when using it.
Lightning Data Service is only available in Lightning Experience and the Salesforce app. Using Lightning Data Service in other containers,
such as Lightning Components for Visualforce, Lightning Out, or Communities isn’t supported. This is true even if these containers are
accessed inside Lightning Experience or the Salesforce mobile app, for example, a Visualforce page added to Lightning Experience.
Lightning Data Service supports primitive DML operations—create, read, update, and delete. It operates on one record at a time, which
you retrieve or modify using the record ID. Lightning Data Service supports spanned fields with a maximum depth of five levels. Support
for working with collections of records or for querying for a record by anything other than the record ID isn’t available. If you must support
higher-level operations or multiple operations in one transaction, use standard @AuraEnabled Apex methods.
Lightning Data Service shared data storage provides notifications to all components that use a record whenever a component changes
that record. It doesn’t notify components if that record is changed on the server, for example, if someone else modifies it. Records
changed on the server aren’t updated locally until they’re reloaded. Lightning Data Service notifies listeners about data changes only if
the changed fields are the same as in the listener’s fields or layout.
Supported Objects
Lightning Data Service supports custom objects and the following.
• Account
• AccountTeamMember
• Asset
• AssetRelationship
• AssignedResource
• AttachedContentNote
• BusinessAccount
• Campaign
347
Creating Apps Considerations
• CampaignMember
• Case
• Contact
• ContentDocument
• ContentNote
• ContentVersion
• ContentWorkspace
• Contract
• ContractContactRole
• ContractLineItem
• Custom Object
• Entitlement
• EnvironmentHubMember
• Lead
• LicensingRequest
• MaintenanceAsset
• MaintenancePlan
• MarketingAction
• MarketingResource
• Note
• OperatingHours
• Opportunity
• OpportunityLineItem
• OpportunityTeamMember
• Order
• OrderItem
• PersonAccount
• Pricebook2
• PricebookEntry
• Product2
• Quote
• QuoteDocument
• QuoteLineItem
• ResourceAbsence
• ResourcePreference
• ServiceAppointment
• ServiceContract
• ServiceCrew
• ServiceCrewMember
• ServiceResource
348
Creating Apps Lightning Data Service Example
• ServiceResourceCapacity
• ServiceResourceSkill
• ServiceTerritory
• ServiceTerritoryLocation
• ServiceTerritoryMember
• Shipment
• SkillRequirement
• SocialPost
• Tenant
• TimeSheet
• TimeSheetEntry
• TimeSlot
• UsageEntitlement
• UsageEntitlementPeriod
• User
• WorkOrder
• WorkOrderLineItem
• WorkType
Example: This example is intended to be added as a Lightning action on the account object. Clicking the action’s button on the
account layout opens a panel to create a new contact.
349
Creating Apps Lightning Data Service Example
This example is similar to the example provided in Configure Components for Record-Specific Actions. Compare the two examples
to better understand the differences between using @AuraEnabled Apex controllers and using Lightning Data Service.
ldsQuickContact.cmp
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">
350
Creating Apps Lightning Data Service Example
</aura:component>
ldsQuickContactController.js
({
doInit: function(component, event, helper) {
351
Creating Apps Lightning Data Service Example
component.find("contactRecordCreator").getNewRecord(
"Contact", // objectApiName
null, // recordTypeId
false, // skip cache?
$A.getCallback(function() {
var rec = component.get("v.newContact");
var error = component.get("v.newContactError");
if(error || (rec === null)) {
console.log("Error initializing record template: " + error);
}
else {
console.log("Record template initialized: " + rec.sobjectType);
}
})
);
},
component.find("contactRecordCreator").saveRecord(function(saveResult) {
if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
// Update the UI: close panel, show toast, refresh account page
$A.get("e.force:closeQuickAction").fire();
resultsToast.fire();
352
Creating Apps SaveRecordResult
Note: The callback passed to getNewRecord() must be wrapped in $A.getCallback() to ensure correct access
context when the callback is invoked. If the callback is passed in without being wrapped in $A.getCallback(), any
attempt to access private attributes of your component results in access check failures.
Even if you’re not accessing private attributes, it’s a best practice to always wrap the callback function for getNewRecord()
in $A.getCallback(). Never mix (contexts), never worry.
ldsQuickContactHelper.js
({
validateContactForm: function(component) {
var validContact = true;
if (allValid) {
// Verify we have an account to attach it to
var account = component.get("v.account");
if($A.util.isEmpty(account)) {
validContact = false;
console.log("Quick action context doesn't have a valid account.");
}
return(validContact);
}
}
})
SEE ALSO:
Configure Components for Record-Specific Actions
Controlling Access
force:recordPreview
SaveRecordResult
Represents the result of a Lightning Data Service operation that makes a persistent change to record data.
353
Creating Apps Lightning Container
SaveRecordResult Object
Callback functions for the saveRecord and deleteRecord functions receive a SaveRecordResult object as their only
argument.
entityLabel String The label for the name of the sObject of the record.
state String The result state of the operation. Possible values are:
• SUCCESS—The operation completed on the server successfully.
• DRAFT—The server wasn’t reachable, so the operation was saved locally as
a draft. The change is applied to the server when it’s reachable.
• INCOMPLETE—The server wasn’t reachable, and the device doesn’t support
drafts. (Drafts are supported only in the Salesforce app.) Try this operation
again later.
• ERROR—The operation couldn’t be completed. Check the error attribute
for more information.
Lightning Container
Upload an app developed with a third-party framework as a static resource, and host the content in a Lightning component using
lightning:container. Use lightning:container to use third-party frameworks like AngularJS or React within your
Lightning pages.
The lightning:container component hosts content in an iframe. You can implement communication to and from the framed
application, allowing it to interact with the Lightning component. lightning:container provides the message() method,
which you can use in the JavaScript controller to send messages to the application. In the component, specify a method for handling
messages with the onmessage attribute.
IN THIS SECTION:
Lightning Container Component Limits
Understand the limits of lightning:container.
The Lightning Realty App
The Lightning Realty App is a more robust example of messaging between the Lightning Container Component and Salesforce.
354
Creating Apps Using a Third-Party Framework
<aura:component>
<lightning:container src="{!$Resource.myApp + '/index.html'}" />
</aura:component>
The contents of the static resource are up to you. It should include the JavaScript that makes up your app, any associated assets, and a
launch page.
As in other Lightning components, you can specify custom attributes. This example references the same static resource, myApp, and
has three attributes, messageToSend, messageReceived, and error. Because this component includes
implements="flexipage:availableForAllPageTypes", it can be used in the Lightning App Builder and added to
Lightning pages.
Note: The examples in this section are accessible on the Developerforce Github Repository.
<div>
<lightning:input name="messageToSend" value="{!v.messageToSend}" label="Message
to send to React app: "/>
<lightning:button label="Send" onclick="{!c.sendMessage}"/>
<br/>
<lightning:textarea value="{!v.messageReceived}" label="Message received from React
app: "/>
<br/>
<aura:if isTrue="{! !empty(v.error)}">
<lightning:textarea name="errorTextArea" value="{!v.error}" label="Error: "/>
</aura:if>
<lightning:container aura:id="ReactApp"
src="{!$Resource.SendReceiveMessages + '/index.html'}"
onmessage="{!c.handleMessage}"
onerror="{!c.handleError}"/>
</div>
</aura:component>
355
Creating Apps Using a Third-Party Framework
The component includes a lightning:input element, allowing users to enter a value for messageToSend. When a user hits
Send, the component calls the controller method sendMessage. This component also provides methods for handling messages
and errors.
This snippet doesn’t include the component’s controller or other code, but don’t worry. We’ll dive in, break it down, and explain how to
implement message and error handling as we go in Sending Messages from the Lightning Container Component and Handling Errors
in Your Container.
SEE ALSO:
Lightning Container
Sending Messages from the Lightning Container Component
Handling Errors in Your Container
<div>
<lightning:input name="messageToSend" value="{!v.messageToSend}" label="Message
to send to React app: "/>
<lightning:button label="Send" onclick="{!c.sendMessage}"/>
<br/>
<lightning:textarea value="{!v.messageReceived}" label="Message received from React
app: "/>
<br/>
<aura:if isTrue="{! !empty(v.error)}">
<lightning:textarea name="errorTextArea" value="{!v.error}" label="Error: "/>
</aura:if>
<lightning:container aura:id="ReactApp"
src="{!$Resource.SendReceiveMessages + '/index.html'}"
onmessage="{!c.handleMessage}"
onerror="{!c.handleError}"/>
</div>
</aura:component>
messageToSend represents a message sent from Salesforce to the framed app, while messageReceived represents a message
sent by the app to the Lightning component. lightning:container includes the required src attribute, an aura:id, and
356
Creating Apps Using a Third-Party Framework
the onmessage attribute. The onmessage attribute specifies the message-handling method in your JavaScript controller, and the
aura:id allows that method to reference the component.
This example shows the component’s JavaScript controller.
({
sendMessage : function(component, event, helper) {
var msg = {
name: "General",
value: component.get("v.messageToSend")
};
component.find("ReactApp").message(msg);
},
This code does a couple of different things. The sendMessage action sends a message from the enclosing Lightning component to
the embedded app. It creates a variable, msg, that has a JSON definition including a name and a value. This definition of the message
is user-defined—the message’s payload can be a value, a structured JSON response, or something else. The messageToSend attribute
of the Lightning component populates the value of the message. The method then uses the component’s aura:id and the
message() function to send the message back to the Lightning component.
The handleMessage method receives a message from the embedded app and handles it appropriately. It takes a component, a
message, and a helper as arguments. The method uses conditional logic to parse the message. If this is the message with the name
and value we’re expecting, the method sets the Lightning component’s messageReceived attribute to the value of the
message. Although this code only defines one message, the conditional statement allows you to handle different types of message,
which are defined in the sendMessage method.
The handler code for sending and receiving messages can be complicated. It helps to understand the flow of a message between the
Lightning component, its controller, and the app. The process begins when user enters a message as the messageToSend attribute.
When the user clicks Send, the component calls sendMessage. sendMessage defines the message payload and uses the
message() method to send it to the app. Within the static resource that defines the app, the specified message handler function
receives the message. Specify the message handling function within your JavaScript code using the lightning-container module’s
addMessageHandler() method. See the lightning-container NPM Module Reference for more information.
When lightning:container receives a message from the framed app, it calls the component controller’s handleMessage
method, as set in the onmessage attribute of lightning:container. The handleMessage method takes the message,
and sets its value as the messageReceived attribute. Finally, the component displays messageReceived in a
lightning:textarea.
357
Creating Apps Using a Third-Party Framework
This is a simple example of message handling across the container. Because you implement the controller-side code and the functionality
of the app, you can use this functionality for any kind of communication between Salesforce and the app embedded in
lightning:container.
Important: Don't send cryptographic secrets like an API key in a message. It's important to keep your API key secure.
SEE ALSO:
Lightning Container
Using a Third-Party Framework
Handling Errors in Your Container
This code, part of the static resource, sends a message as an object containing a name and a value, which is user-defined.
When the app receives a message, it’s handled by the function mounted by the addMessageHandler() method. In a React app,
functions must be mounted to be part of the document-object model and rendered in the output.
The lightning-container module provides similar methods for defining a function to handle errors in the messaging framework. For more
information, see lightning-container NPM Module Reference
Important: Don't send cryptographic secrets like an API key in a message. It's important to keep your API key secure.
358
Creating Apps Using a Third-Party Framework
<div>
<lightning:input name="messageToSend" value="{!v.messageToSend}" label="Message
to send to React app: "/><lightning:button label="Send" onclick="{!c.sendMessage}"/>
<br/>
<br/>
<lightning:container aura:id="ReactApp"
src="{!$Resource.SendReceiveMessages + '/index.html'}"
onmessage="{!c.handleMessage}"
onerror="{!c.handleError}"/>
</div>
</aura:component>
var msg = {
name: "General",
value: component.get("v.messageToSend")
};
component.find("ReactApp").message(msg);
},
359
Creating Apps Using a Third-Party Framework
}
})
If the Lightning container application throws an error, the error handling function sets the error attribute. Then, in the component
markup, the conditional expression checks if the error attribute is empty. If it isn’t, the component populates a lightning:textarea
element with the error message stored in error.
SEE ALSO:
Lightning Container
Using a Third-Party Framework
Sending Messages from the Lightning Container Component
<div>
<aura:if isTrue="{! !empty(v.error)}">
<lightning:textarea name="errorTextArea" value="{!v.error}" label="Error: "/>
</aura:if>
<lightning:container aura:id="ReactApp"
src="/ApexController/index.html"
onerror="{!c.handleError}"/>
</div>
</aura:component>
Note: You can download the complete version of this example from the Developerforce Github Repository.
There’s not a lot going on in the component’s JavaScript controller—the real action is in the JavaScript app, uploaded as a static resource,
that the Lightning container references.
import React, { Component } from 'react';
import LCC from "lightning-container";
360
Creating Apps Using a Third-Party Framework
callApex() {
LCC.callApex("lcc1.ApexController.getAccount",
this.state.name,
this.handleAccountQueryResponse,
{escape: true});
}
handleAccountQueryResponse(result, event) {
if (event.status) {
this.setState({account: result});
}
else if (event.type === "exception") {
console.log(event.message + " : " + event.where);
}
}
render() {
var account = this.state.account;
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to LCC</h2>
</div>
<p className="App-intro">
Account Name: <input type="text" id="accountName" value={this.state.name}
onChange={e => this.onAccountNameChange(e)}/><br/>
<input type="submit" value="Call Apex Controller" onClick={this.callApex}/><br/>
Id: {account.Id}<br/>
Phone: {account.Phone}<br/>
Type: {account.Type}<br/>
Number of Employees: {account.NumberOfEmployees}<br/>
</p>
</div>
);
}
constructor(props) {
super(props);
this.state = {
name: "",
account: {}
};
this.handleAccountQueryResponse = this.handleAccountQueryResponse.bind(this);
this.onAccountNameChange = this.onAccountNameChange.bind(this);
this.callApex = this.callApex.bind(this);
361
Creating Apps Lightning Container Component Limits
onAccountNameChange(e) {
this.setState({name: e.target.value});
}
}
The first function, callApex(), uses the LCC.callApex method to call getAccount, an Apex method that gets and displays
an account’s information.
SEE ALSO:
Lightning Container
362
Creating Apps The Lightning Realty App
Let’s look at the Lightning component first. Although the code that defines the Realty component is simple, it allows the JavaScript of
the realty app to communicate with Salesforce and load sample data.
<aura:component access="global" implements="flexipage:availableForAllPageTypes" >
<div>
<aura:if isTrue="{! !empty(v.messageReceived)}">
<lightning:textarea name="messageReceivedTextArea" value="{!v.messageReceived}"
label=" "/>
</aura:if>
</aura:if>
<lightning:container aura:id="ReactApp"
src="{!$Resource.Realty + '/index.html?mainTitle=' +
v.mainTitle}"
onmessage="{!c.handleMessage}"
onerror="{!c.handleError}"/>
</div>
</aura:component>
This code is similar to the example code in Sending Messages from the Lightning Container Component and Handling Errors in Your
Container.
There’s also code in the Lightning component’s controller and in the source JavaScript that allows the iframed app to communicate
with Salesforce. In PropertyHome.js, part of the source, the realty app calls LCC.sendMessage. This segment of code filters
the list of properties, then creates a message to send back to the container that includes the selected property’s address, price, city, state,
zip code, and description.
saveHandler(property) {
let filteredProperty = propertyService.filterProperty(property);
propertyService.createItem(filteredProperty).then(() => {
propertyService.findAll(this.state.sort).then(properties => {
let filteredProperties = propertyService.filterFoundProperties(properties);
this.setState({addingProperty: false, properties:filteredProperties});
});
let message = {};
message.address = property.address;
message.price = property.price;
message.city = property.city;
message.state = property.state;
message.zip = property.zip;
message.description = property.description;
LCC.sendMessage({name: "PropertyCreated", value: message});
363
Creating Apps The Lightning Realty App
});
},
Then, the JavaScript calls LCC.sendMessage with a name-value pair. This code uses the sendMessage method, which is part
of the messaging API provided by the lightning-container NPM module. For more information, see Sending Messages to the Lightning
Container Component.
The last bit of action happens in the component’s controller, in the handleMessage() function.
handleMessage: function(component, message, helper) {
var payload = message.getParams().payload;
var name = payload.name;
if (name === "PropertyCreated") {
var value = payload.value;
var messageToUser;
if (value.price > 1000000) {
messageToUser = "Big Real Estate Opportunity in " + value.city + ", " +
value.state + " : $" + value.price;
}
else {
messageToUser = "Small Real Estate Opportunity in " + value.city + ", " +
value.state + " : $" + value.price;
}
var log = component.get("v.log");
log.push(messageToUser);
component.set("v.log", log);
}
},
This function takes a message as an argument, and checks that the name is "PropertyCreated". This is the same name set by
LCC.sendMessage in the app’s JavaScript.
This function takes the message payload—in this case, a JSON array describing a property—and checks the value of the property. If the
value is over $1 million, it sends a message to the user telling him or her that there’s a big real estate opportunity. Otherwise, it returns
a message telling the user that there’s a smaller real estate opportunity.
IN THIS SECTION:
Install the Example Lightning Realty App
See further examples of lightning:container in the Developerforce Git repository.
364
Creating Apps lightning-container NPM Module Reference
1. Clone the Git repository. From the command line, enter git clone
https://github.com/developerforce/LightningContainerExamples
2. From the command line, navigate to LightningContainerExamples/ReactJS/Javascript/Realty and build
the project’s dependencies by entering npm install.
3. From the command line, build the app by entering npm run build.
4. Edit package.json and add your Salesforce login credentials where indicated.
5. From the command line, enter npm run deploy.
6. Log in to Salesforce and activate the new Realty Lightning page in the Lightning App Builder by adding it to a Lightning app.
7. To upload sample data to your org, enter npm run load from the command line.
See the Lightning realty app in action in your org. The app uses lightning:container to embed a React app in a Lightning
page, displaying sample real estate listing data.
The component and handler code are similar to the examples in Sending Messages from the Lightning Container Component and
Handling Errors in Your Container.
365
Creating Apps lightning-container NPM Module Reference
IN THIS SECTION:
addMessageErrorHandler()
Mounts an error handling function, to be called when the messaging framework encounters an error.
addMessageHandler()
Mounts a message handling function, used to handle messages sent from the Lightning component to the framed JavaScript app.
callApex()
Makes an Apex call.
getRESTAPISessionKey()
Returns the Salesforce REST API session key.
removeMessageErrorHandler()
Unmounts the error handling function.
removeMessageHandler()
Unmounts the message-handling function.
sendMessage()
Sends a message from the framed JavaScript code to the Lightning component.
addMessageErrorHandler()
Mounts an error handling function, to be called when the messaging framework encounters an error.
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example mounts a
message error handling function. In a React app, functions must be mounted to be part of the document-object model and rendered
in the output.
componentDidMount() {
LCC.addMessageErrorHandler(this.onMessageError);
}
You can view and download this example in the Developerforce Github Repository.
Arguments
Response
None.
addMessageHandler()
Mounts a message handling function, used to handle messages sent from the Lightning component to the framed JavaScript app.
366
Creating Apps lightning-container NPM Module Reference
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example mounts a
message handling function. In a React app, functions must be mounted to be part of the document-object model and rendered in the
output.
componentDidMount() {
LCC.addMessageHandler(this.onMessage);
}
onMessage(msg) {
let name = msg.name;
if (name === "General") {
let value = msg.value;
this.setState({messageReceived: value});
}
else if (name === "Foo") {
// A different response
}
}
You can view and download this example in the Developerforce Github Repository.
Arguments
Response
None.
callApex()
Makes an Apex call.
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example calls the Apex
method getAccount.
callApex() {
LCC.callApex("lcc1.ApexController.getAccount",
this.state.name,
this.handleAccountQueryResponse,
{escape: true});
}
You can view and download this example in the Developerforce Github Repository.
367
Creating Apps lightning-container NPM Module Reference
Arguments
Response
None.
getRESTAPISessionKey()
Returns the Salesforce REST API session key.
Use this method when your embedded app needs to interact with the Salesforce REST API, such as executing a SOQL query.
Don’t use the session key to manage custom objects or fields. You can use the session key to create and update object records. Apps
that use lightning:container should work with data, not metadata.
Important: It's important to keep your API key secure. Don't give this key to code you don't trust, and don't include it in URLs or
hyperlinks, even to another page in your app.
Salesforce uses the no-referrer policy to protect against leaking your app's URL to outside servers, such as image hosts. However,
this policy doesn't protect some browsers, meaning your app's URLs could be included in outside requests.
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example gets the REST
API session key and uses it to execute a SOQL query.
componentDidMount() {
let sid = LCC.getRESTAPISessionKey();
let conn = new JSForce.Connection({accessToken: sid});
conn.query("SELECT Id, Name from Account LIMIT 50", this.handleAccountQueryResponse);
}
You can view and download this example in the Developerforce Github Repository.
Arguments
None.
Response
368
Creating Apps lightning-container NPM Module Reference
removeMessageErrorHandler()
Unmounts the error handling function.
When using React, it’s necessary to unmount functions to remove them from the DOM and perform necessary cleanup.
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example unmounts a
message error handling function. In a React app, functions must be mounted to be part of the document-object model and rendered
in the output.
componentWillUnmount() {
LCC.removeMessageErrorHandler(this.onMessageError);
}
You can view and download this example in the Developerforce Github Repository.
Arguments
Response
None.
removeMessageHandler()
Unmounts the message-handling function.
When using React, it’s necessary to unmount functions to remove them from the DOM and perform necessary cleanup.
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example unmounts a
message handling function.
componentWillUnmount() {
LCC.removeMessageHandler(this.onMessage);
}
You can view and download this example in the Developerforce Github Repository.
Arguments
369
Creating Apps Controlling Access
Response
None.
sendMessage()
Sends a message from the framed JavaScript code to the Lightning component.
Sample
Used within a JavaScript app uploaded as a static resource and referenced by lightning:container, this example sends a
message from the app to lightning:container.
sendMessage() {
LCC.sendMessage({name: "General", value: this.state.messageToSend});
}
You can view and download this example in the Developerforce Github Repository.
Arguments
Response
None.
Controlling Access
The framework enables you to control access to your applications, attributes, components, events, interfaces, and methods via the
access system attribute. The access system attribute indicates whether the resource can be used outside of its own namespace.
Use the access system attribute on these tags:
• <aura:application>
• <aura:attribute>
• <aura:component>
• <aura:event>
• <aura:interface>
• <aura:method>
Access Values
You can specify these values for the access system attribute.
370
Creating Apps Controlling Access
private
Available within the component, app, interface, event, or method and can’t be referenced outside the resource. This value can only
be used for <aura:attribute> or <aura:method>.
Marking an attribute as private makes it easier to refactor the attribute in the future as the attribute can only be used within the
resource.
Accessing a private attribute returns undefined unless you reference it from the component in which it’s declared. You can’t
access a private attribute from a sub-component that extends the component containing the private attribute.
public
Available within your org only. This is the default access value.
global
Available in all orgs.
Note: Mark your resources, such as a component, with access="global" to make the resource usable outside of your
own org. For example, if you want a component to be usable in an installed package or by a Lightning App Builder user or a
Community Builder user in another org.
Example
This sample component has global access.
<aura:component access="global">
...
</aura:component>
Access Violations
If your code accesses a resource, such as a component, that doesn’t have an access system attribute allowing you to access the
resource:
• Client-side code doesn’t execute or returns undefined. If you enabled debug mode, you see an error message in your browser
console.
• Server-side code results in the component failing to load. If you enabled debug mode, you see a popup error message.
371
Creating Apps Controlling Access
You can fix access check errors using one or more of these techniques.
• Add appropriate access system attributes to the resources that you own.
• Remove references in your code to resources that aren’t available. In the earlier example, markup://c:targetComponent
doesn’t have an access value allowing markup://c:sourceComponent to access it.
• Ensure that an attribute that you’re accessing exists by looking at its <aura:attribute> definition. Confirm that you’re using
the correct case-sensitive spelling for the name.
Accessing an undefined attribute or an attribute that is out of scope, for example a private attribute, triggers the same access violation
message. The access context doesn’t know whether the attribute is undefined or inaccessible.
The key word in this error message is undefined, which indicates that the framework has lost context. This happens when your code
accesses a component outside the normal framework lifecycle, such as in a setTimeout() or setInterval() call or in an ES6
Promise.
Fix this error by wrapping the code in a $A.getCallback() call. For more information, see Modifying Components Outside the
Framework Lifecycle.
This error message happens when you reference a property on a variable with a value of undefined. The error can happen in many
contexts, one of which is the side-effect of an access check failure. For example, let’s see what happens when you try to access an
undefined attribute, imaginaryAttribute, in JavaScript.
var whatDoYouExpect = cmp.get("v.imaginaryAttribute");
This is an access check error and whatDoYouExpect is set to undefined. Now, if you try to access a property on
whatDoYouExpect, you get an error.
The c$sourceComponent$controller$doInit portion of the error message tells you that the error is in the doInit
method of the controller of the sourceComponent component in the c namespace.
IN THIS SECTION:
Application Access Control
The access attribute on the aura:application tag controls whether the app can be used outside of the app’s namespace.
Interface Access Control
The access attribute on the aura:interface tag controls whether the interface can be used outside of the interface’s
namespace.
372
Creating Apps Application Access Control
SEE ALSO:
Enable Debug Mode for Lightning Components
Modifier Description
public Available within your org only. This is the default access value.
Modifier Description
public Available within your org only. This is the default access value.
A component can implement an interface using the implements attribute on the aura:component tag.
Modifier Description
public Available within your org only. This is the default access value.
373
Creating Apps Attribute Access Control
Modifier Description
global Available in all orgs.
Note: Components aren’t directly addressable via a URL. To check your component output, embed your component in a .app
resource.
Access Description
private Available within the component, app, interface, event, or method and can’t be referenced outside
the resource.
Note: Accessing a private attribute returns undefined unless you reference it from the
component in which it’s declared. You can’t access a private attribute from a sub-component
that extends the component containing the private attribute.
public Available within your org only. This is the default access value.
Modifier Description
public Available within your org only. This is the default access value.
374
Creating Apps What is Inherited?
What is Inherited?
This topic lists what is inherited when you extend a definition, such as a component.
When a component contains another component, we refer in the documentation to parent and child components in the containment
hierarchy. When a component extends another component, we refer to sub and super components in the inheritance hierarchy.
Component Attributes
A sub component that extends a super component inherits the attributes of the super component. Use <aura:set> in the markup
of a sub component to set the value of an attribute inherited from a super component.
Events
A sub component that extends a super component can handle events fired by the super component. The sub component automatically
inherits the event handlers from the super component.
The super and sub component can handle the same event in different ways by adding an <aura:handler> tag to the sub component.
The framework doesn't guarantee the order of event handling.
Helpers
A sub component's helper inherits the methods from the helper of its super component. A sub component can override a super
component's helper method by defining a method with the same name as an inherited method.
Controllers
A sub component that extends a super component can call actions in the super component's client-side controller. For example, if the
super component has an action called doSomething, the sub component can directly call the action using the {!c.doSomething}
syntax.
Note: We don't recommend using inheritance of client-side controllers as this feature may be deprecated in the future to preserve
better component encapsulation. We recommend that you put common code in a helper instead.
SEE ALSO:
Component Attributes
Communicating with Events
Sharing JavaScript Code in a Component Bundle
Handling Events with Client-Side Controllers
aura:set
375
Creating Apps Inherited Component Attributes
Let's start with a simple example. c:super has a description attribute with a value of "Default description",
<!--c:super-->
<aura:component extensible="true">
<aura:attribute name="description" type="String" default="Default description" />
{!v.body}
</aura:component>
Don’t worry about the {!v.body} expression for now. We’ll explain that when we talk about the body attribute.
c:sub extends c:super by setting extends="c:super" in its <aura:component> tag.
<!--c:sub-->
<aura:component extends="c:super">
<p>sub.cmp description: {!v.description}</p>
</aura:component
Note that sub.cmp has access to the inherited description attribute and it has the same value in sub.cmp and super.cmp.
Use <aura:set> in the markup of a sub component to set the value of an inherited attribute.
<!--c:superBody-->
<aura:component extensible="true">
Parent body: {!v.body}
</aura:component>
At this point, c:superBody doesn’t output anything for {!v.body} as it’s just a placeholder for data that will be passed in by a
component that extends c:superBody.
c:subBody extends c:superBody by setting extends="c:superBody" in its <aura:component> tag.
<!--c:subBody-->
<aura:component extends="c:superBody">
Child body: {!v.body}
</aura:component>
376
Creating Apps Abstract Components
c:subBody outputs:
In other words, c:subBody sets the value for {!v.body} in its super component, c:superBody.
c:containerBody contains a reference to c:subBody.
<!--c:containerBody-->
<aura:component>
<c:subBody>
Body value
</c:subBody>
</aura:component>
In c:containerBody, we set the body attribute of c:subBody to Body value. c:containerBody outputs:
Parent body: Child body: Body value
SEE ALSO:
aura:set
Component Body
Component Markup
Abstract Components
Object-oriented languages, such as Java, support the concept of an abstract class that provides a partial implementation for an object
but leaves the remaining implementation to concrete sub-classes. An abstract class in Java can't be instantiated directly, but a non-abstract
subclass can.
Similarly, the Lightning Component framework supports the concept of abstract components that have a partial implementation but
leave the remaining implementation to concrete sub-components.
To use an abstract component, you must extend it and fill out the remaining implementation. An abstract component can't be used
directly in markup.
The <aura:component> tag has a boolean abstract attribute. Set abstract="true" to make the component abstract.
SEE ALSO:
Interfaces
Interfaces
Object-oriented languages, such as Java, support the concept of an interface that defines a set of method signatures. A class that
implements the interface must provide the method implementations. An interface in Java can't be instantiated directly, but a class that
implements the interface can.
Similarly, the Lightning Component framework supports the concept of interfaces that define a component's shape by defining its
attributes.
An interface starts with the <aura:interface> tag. It can only contain these tags:
• <aura:attribute> tags to define the interface's attributes.
377
Creating Apps Inheritance Rules
Note: Use <aura:set> in a sub component to set the value of any attribute that is inherited from the super component. This
usage works for components and abstract components, but it doesn't work for interfaces. To set the value of an attribute inherited
from an interface, redefine the attribute in the sub component using <aura:attribute> and set the value in its default
attribute.
Since there are fewer restrictions on the content of abstract components, they are more common than interfaces. A component can
implement multiple interfaces but can only extend one abstract component, so interfaces can be more useful for some design patterns.
SEE ALSO:
Setting Attributes Inherited from an Interface
Abstract Components
Marker Interfaces
You can use an interface as a marker interface that is implemented by a set of components that you want to easily identify for specific
usage in your app.
In JavaScript, you can determine if a component implements an interface by using
myCmp.isInstanceOf("mynamespace:myinterface").
Inheritance Rules
This table describes the inheritance rules for various elements.
SEE ALSO:
Interfaces
378
Creating Apps Using the AppCache
SEE ALSO:
aura:application
SEE ALSO:
Testing Your Apex Code
379
CHAPTER 7 Debugging
In this chapter ... There are a few basic tools and techniques that can help you to debug applications.
Use Chrome DevTools to debug your client-side code.
• Enable Debug Mode
for Lightning • To open DevTools on Windows and Linux, press Control-Shift-I in your Google Chrome browser. On
Components Mac, press Option-Command-I.
• Salesforce Lightning • To quickly find which line of code is failing, enable the Pause on all exceptions option before
Inspector Chrome running your code.
Extension
To learn more about debugging JavaScript on Google Chrome, refer to the Google Chrome's DevTools
• Log Messages website.
380
Debugging Enable Debug Mode for Lightning Components
Important: Debug mode has a significant performance impact. The setting affects all users in your org. For this reason, we
recommend using it only in sandbox and Developer Edition orgs. Don’t leave debug mode on permanently in your production
org.
To enable debug mode for your org:
1. From Setup, enter Lightning Components in the Quick Find box, then select Lightning Components.
2. Select the Enable Debug Mode checkbox.
3. Click Save.
381
Debugging Install Salesforce Lightning Inspector
IN THIS SECTION:
Install Salesforce Lightning Inspector
Install the Google Chrome DevTools extension to help you debug and profile component performance.
Salesforce Lightning Inspector
The Chrome extension adds a Lightning tab to the DevTools menu. Use it to inspect different aspects of your app.
To get information quickly about an element on a Lightning page, right-click the element and select Inspect Lightning Component.
You can also click a Lightning component in the DevTools Elements tab or an element with a data-aura-rendered-by
attribute to see a description and attributes.
382
Debugging Salesforce Lightning Inspector
IN THIS SECTION:
Component Tree Tab
This tab shows the component markup including the tree of nested components.
Performance Tab
The Performance tab shows a flame graph of the creation time for your components. Look at longer and deeper portions of the
graph for potential performance bottlenecks.
Transactions Tab
Some apps delivered by Salesforce include transaction markers that enable you to see fine-grained metrics for actions within those
transactions. You can’t create your own transactions.
Event Log Tab
This tab shows all the events fired. The event graph helps you to understand the sequence of events and handlers for one or more
actions.
Actions Tab
This tab shows the server-side actions executed. The list automatically refreshes when the page updates.
Storage Tab
This tab shows the client-side storage for Lightning applications. Actions marked as storable are stored in the actions store. Use
this tab to analyze storage in the Salesforce mobile app and Lightning Experience.
383
Debugging Salesforce Lightning Inspector
384
Debugging Salesforce Lightning Inspector
• Rerendered—The number of times the component has been rerendered since you opened the Inspector. Changing properties
on a component makes it dirty, which triggers a rerender. Rerendering can be an expensive operation, and you generally want
to avoid it, if possible.
• Attribute & Facet Value Provider—The attribute value provider and facet value provider are usually the same component. If
so, they are consolidated into one entry.
The attribute value provider is the component that provides attribute values for expressions. In the following example, the name
attribute of <c:myComponent> gets its value from the avpName attribute of its attribute value provider.
<c:myComponent name="{!v.avpName}" />
The facet value provider is the value provider for facet attributes (attributes of type Aura.Component[]). The facet value
provider can be different than the attribute value provider for the component. We won't get into that here as it's complicated!
However, it's important to know that if you have expressions in facets, the expressions use the facet value provider instead of
the attribute value provider.
Attributes
Shows the attribute values for a component. Use v.attributeName when you reference an attribute in an expression or code.
[[Super]]
When a component extends another component, the sub component creates an instance of the super component during its creation.
Each of these super components has their own set of properties. While a super component has its own attributes section, the super
component only has a body attribute. All other attribute values are shared in the extension hierarchy.
Model
Some components you see might have a Model section. Models are a deprecated feature and they are included simply for debugging
purposes. Don't reference models or your code will break.
These commands are useful to explore the component contents using the $auraTemp variable.
$auraTemp+""
Returns the component descriptor.
$auraTemp.get("v.attributeName")
Returns the value for the attributeName attribute.
385
Debugging Salesforce Lightning Inspector
$auraTemp.getElement()
Returns the corresponding DOM element.
inspect($auraTemp.getElement())
Opens the Elements tab and inspects the DOM element for the component.
Performance Tab
The Performance tab shows a flame graph of the creation time for your components. Look at longer and deeper portions of the graph
for potential performance bottlenecks.
The flame graph for your actions displays. To see the graph before you stop recording, press the button.
Aggregated self time All invocations of the function across the recorded timeline. It
excludes the completion time for functions it invoked.
Total time The current function and all functions that it invoked.
Aggregated total time All invocations of the function across the recorded timeline,
including completion time for functions it invoked.
386
Debugging Salesforce Lightning Inspector
Transactions Tab
Some apps delivered by Salesforce include transaction markers that enable you to see fine-grained metrics for actions within those
transactions. You can’t create your own transactions.
387
Debugging Salesforce Lightning Inspector
Measure Description
Duration The page duration since the page start time, in milliseconds
Start Time The start time when the page was last loaded or refreshed, in milliseconds
Timeline The start and end times of a transaction, represented by a colored bar:
• Green — How long the action took on the server
• Yellow — XMLHttpRequest transaction
• Blue — Queued time until the XMLHttpRequest transaction was sent
• Purple — Custom transaction
Record Events
Use the Toggle recording and Clear buttons to capture specific user actions or collections of user actions.
1. To start gathering event data, press .
388
Debugging Salesforce Lightning Inspector
389
Debugging Salesforce Lightning Inspector
SEE ALSO:
Communicating with Events
Actions Tab
This tab shows the server-side actions executed. The list automatically refreshes when the page updates.
390
Debugging Salesforce Lightning Inspector
• Cached—Storable actions whose responses are cached. Toggle this button off to show cache misses and non-storable actions. This
information can be valuable if you're investigating performance bottlenecks.
• Background—Not supported for Lightning components. Available in the open-source Aura framework.
• Success—Actions that were executed successfully.
• Incomplete—Actions with no server response. The server might be down or the client might be offline.
• Error—Actions that returned a server error.
• Aborted—Actions that were aborted.
Enter a search string in the Filter field to match any substring.
Invert the filter by starting the search string with !. For example, !aura returns all actions that don't contain the string aura and
filters out many framework-level actions.
IN THIS SECTION:
Manually Override Server Responses
The Overrides panel on the right side of the Actions tab lets you manually tweak the server responses and investigate the fault
tolerance of your app.
SEE ALSO:
Calling a Server-Side Action
Drag an action from the list on the left side to the PENDING OVERRIDES section.
391
Debugging Salesforce Lightning Inspector
The next time the same action is enqueued to be sent to the server, the framework won't send it. Instead, the framework mocks the
response based on the override option that you choose. Here are the override options.
• Override the Result
• Error Response Next Time
• Drop the Action
Note: The same action means an action with the same name. The action parameters don't have to be identical.
IN THIS SECTION:
Modify an Action Response
Modify an action response in the Salesforce Lightning Inspector by changing one of the JSON object values and see how the UI is
affected. The server returns a JSON object when you call a server-side action.
Set an Error Response
Your app should degrade gracefully when an error occurs so that users understand what happened or know how to proceed. Use
the Salesforce Lightning Inspector to simulate an error condition and see how the user experience is affected.
Drop an Action Response
Your app should degrade gracefully when a server-side action times out or the response is dropped. Use the Salesforce Lightning
Inspector to simulate a dropped action response and see how the user experience is affected.
5. Click Save.
6. To trigger execution of the action, refresh the page.
The modified action response moves from the PENDING OVERRIDES section to the PROCESSED OVERRIDES section.
392
Debugging Salesforce Lightning Inspector
5. Click Save.
6. To trigger execution of the action, refresh the page.
• The modified action response moves from the PENDING OVERRIDES section to the PROCESSED OVERRIDES section.
• The action response displays in the COMPLETED section in the left panel with a State equals ERROR.
393
Debugging Salesforce Lightning Inspector
7. Note the UI change, if any, related to your change. The UI should handle errors by alerting the user or allowing them to continue
using the app.
To degrade gracefully, make sure that your action response callback handles an error response (response.getState() ===
"ERROR").
SEE ALSO:
Calling a Server-Side Action
394
Debugging Log Messages
4. Note the UI change, if any, related to your change. The UI should handle the dropped action by alerting the user or allowing them
to continue using the app.
To degrade gracefully, make sure that your action response callback handles an incomplete response (response.getState()
=== "INCOMPLETE").
SEE ALSO:
Calling a Server-Side Action
Storage Tab
This tab shows the client-side storage for Lightning applications. Actions marked as storable are stored in the actions store. Use this
tab to analyze storage in the Salesforce mobile app and Lightning Experience.
Log Messages
To help debug your client-side code, you can write output to the JavaScript console of a web browser using console.log() if your
browser supports it..
For instructions on using the JavaScript console, refer to the instructions for your web browser.
395
CHAPTER 8 Fixing Performance Warnings
In this chapter ... A few common performance anti-patterns in code prompt the framework to log warning messages to
the browser console. Fix the warning messages to speed up your components!
• <aura:if>—Clean
Unrendered Body
The warnings display in the browser console only if you enabled debug mode.
• <aura:iteration>—Multiple
Items Set SEE ALSO:
Enable Debug Mode for Lightning Components
396
Fixing Performance Warnings <aura:if>—Clean Unrendered Body
Example
This component shows the anti-pattern.
<!--c:ifCleanUnrendered-->
<aura:component>
<aura:attribute name="isVisible" type="boolean" default="true"/>
<aura:handler name="init" value="{!this}" action="{!c.init}"/>
<aura:if isTrue="{!v.isVisible}">
<p>I am visible</p>
</aura:if>
</aura:component>
When the component is created, the isTrue attribute of the <aura:if> tag is evaluated. The value of the isVisible attribute
is true by default so the framework creates the body of the <aura:if> tag. After the component is created but before rendering,
the init event is triggered.
The init() function in the client-side controller toggles the isVisible value from true to false. The isTrue attribute
of the <aura:if> tag is now false so the framework must destroy the body of the <aura:if> tag. This warning displays in
the browser console only if you enabled debug mode.
WARNING: [Performance degradation] markup://aura:if ["5:0"] in c:ifCleanUnrendered ["3:0"]
needed to clear unrendered body.
Click the expand button beside the warning to see a stack trace for the warning.
Click the link for the ifCleanUnrendered entry in the stack trace to see the offending line of code in the Sources pane of the
browser console.
397
Fixing Performance Warnings <aura:iteration>—Multiple Items Set
<aura:if isTrue="{!v.isVisible}">
<p>I am visible</p>
</aura:if>
</aura:component>
SEE ALSO:
aura:if
Enable Debug Mode for Lightning Components
Example
This component shows the anti-pattern.
<!--c:iterationMultipleItemsSet-->
<aura:component>
<aura:attribute name="groceries" type="List"
default="[ 'Eggs', 'Bacon', 'Bread' ]"/>
398
Fixing Performance Warnings <aura:iteration>—Multiple Items Set
When the component is created, the items attribute of the <aura:iteration> tag is set to the default value of the groceries
attribute. After the component is created but before rendering, the init event is triggered.
The init() function in the client-side controller sets the groceries attribute, which resets the items attribute of the
<aura:iteration> tag. This warning displays in the browser console only if you enabled debug mode.
Click the expand button beside the warning to see a stack trace for the warning.
Click the link for the iterationMultipleItemsSet entry in the stack trace to see the offending line of code in the Sources
pane of the browser console.
399
Fixing Performance Warnings <aura:iteration>—Multiple Items Set
SEE ALSO:
aura:iteration
Enable Debug Mode for Lightning Components
400
CHAPTER 9 Reference
In this chapter ... This section contains reference documentation including details of the various tags available in the
framework.
• Component Library
(Beta)
Note that the the Lightning Component framework provides a subset of what’s available in the
open-source Aura framework, in addition to components and events that are specific to Salesforce.
• Supported
aura:attribute Types
• System Tag
Reference
• Component
Reference
• Messaging
Component
Reference
• Interface Reference
• Event Reference
• System Event
Reference
• Supported HTML
Tags
401
Reference Component Library (Beta)
Note: If you find something in the Aura framework documentation that’s not available in the Component Library, we recommend
that you don’t use it as the support might change in future releases.
402
Reference Supported aura:attribute Types
Lightning Design
System support
Components in
custom namespaces
and packages
JavaScript API
Messaging component
reference (lightning:notificationsLibrary
etc.)
Event documentation
System event
documentation
Interface
documentation
Components in custom namespaces display both global and non-global attributes and methods. Components in managed and
unmanaged packages display global attributes and methods only.
Note: The Reference Documentation site is available in your org and as an open-source project at
http://documentation.auraframework.org/. Not everything in the open-source site is available to you in your
org with Lightning Components. If you find something in the open-source site that’s not available in the Component Library or
Dev Guide, don’t use it as it’s not supported.
name String Required. The name of the attribute. For example, if you set
<aura:attribute name="isTrue" type="Boolean" />
on a component called aura:newCmp, you can set this attribute when you
instantiate the component; for example,<aura:newCmp
isTrue="false" />.
403
Reference Basic Types
default String The default value for the attribute, which can be overwritten as needed. When
setting a default value, expressions using the $Label, $Locale, and
$Browser global value providers are supported. Alternatively, to set a
dynamic default, use an init event. See Invoking Actions on Component
Initialization on page 269.
All <aura:attribute> tags have name and type values. For example:
<aura:attribute name="whom" type="String" />
Note: Although type values are case insensitive, case sensitivity should be respected as your markup interacts with JavaScript,
CSS, and Apex.
SEE ALSO:
Component Attributes
Basic Types
Here are the supported basic type values. Some of these types correspond to the wrapper objects for primitives in Java. Since the
framework is written in Java, defaults, such as maximum size for a number, for these basic types are defined by the Java objects that
they map to.
404
Reference Basic Types
You can use arrays for each of these basic types. For example:
<aura:attribute name="favoriteColors" type="String[]" default="['red','green','blue']" />
@AuraEnabled
public static List<String> getStringArray() {
String[] arrayItems = new String[]{ 'red', 'green', 'blue' };
return arrayItems;
}
405
Reference Function Type
This client-side controller retrieves the string array from the Apex controller and displays it using the {!v.favoriteColors}
expression.
({
getString : function(component, event) {
var action = component.get("c.getStringArray");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var stringItems = response.getReturnValue();
component.set("v.favoriteColors", stringItems);
}
});
$A.enqueueAction(action);
}
})
Function Type
An attribute can have a type corresponding to a JavaScript function. If a child component has an attribute of this type, you can pass a
callback from a parent component that contains the child component.
<aura:attribute name="callback" type="Function" />
For an example of using this type with aura:method, see Return Result for Asynchronous Code.
Note: Don’t send attributes with type="Function" to the server. These attributes are intended to only be used on the
client side.
The most robust way to communicate between components is to use an event. If you get an error in a component with an attribute
of type Function, fire an event in the child component instead and handle it in the parent component.
Object Types
An attribute can have a type corresponding to an Object. For example:
<aura:attribute name="data" type="Object" />
Warning: We recommend using type="Map" instead of type="Object" to avoid some deserialization issues on the
server. For example, when an attribute of type="Object" is serialized to the server, everything is converted to a string. Deep
expressions, such as v.data.property can throw an exception when they are evaluated as a string on the server. Using
type="Map" avoids these exceptions for deep expressions, and other deserialization issues.
SEE ALSO:
Working with Salesforce Records
406
Reference Standard and Custom Object Types
SEE ALSO:
Working with Salesforce Records
Collection Types
Here are the supported collection type values.
407
Reference Custom Apex Class Types
This example retrieves a list of numbers from a client-side controller when a button is clicked.
<aura:attribute name="numbers" type="List"/>
<lightning:button onclick="{!c.getNumbers}" label="Display Numbers" />
<aura:iteration var="num" items="{!v.numbers}">
{!num.value}
</aura:iteration>
Component attribute types can be custom Apex classes, and the following standard Apex classes.
• List
• Map
To make use of values held in other Apex built-in classes, create a custom Apex class, and copy needed values from instances of the
standard class into your custom class.
When an instance of an Apex class is returned from a server-side action, the instance is serialized to JSON by the framework. Only the
values of public instance properties and methods annotated with @AuraEnabled are serialized and returned.
The following Apex data types can be serialized from @AuraEnabled properties and methods.
• Primitive types except for BLOB
• Object, subject to limitations described above
408
Reference Framework-Specific Types
• sObject
• Collections types (List and Map) when they hold elements of a supported type
Note: Custom classes used for component attributes shouldn’t be inner classes or use inheritance. While these Apex language
features might work in some situations, there are known issues, and their use is unsupported in all cases.
Using Arrays
If an attribute can contain more than one element, use an array.
This aura:attribute tag shows the syntax for an array of Apex objects:
<aura:attribute name="colorPalette" type="docSampleNamespace.Color[]" />
SEE ALSO:
Returning Data from an Apex Server-Side Controller
AuraEnabled Annotation
Working with Salesforce Records
Apex Developer Guide: Data Types
Framework-Specific Types
Here are the supported type values that are specific to the framework.
<aura:component>
<aura:attribute
name="detail"
type="Aura.Component[]">
<p>default
paragraph1</p>
</aura:attribute>
Default value is:
{!v.detail}
</aura:component>
409
Reference Framework-Specific Types
SEE ALSO:
Component Body
Component Facets
Warning: Although Aura.Action works for passing an action handler to a child component, we recommend registering an
event in the child component and firing the event in the child’s controller instead. Then, handle the event in the parent component.
The event approach requires a few extra steps in creating or choosing an event and firing it but events are the standard way to
communicate between components.
Aura.Action shouldn’t be used for other use cases. Here are some known limitations of Aura.Action.
• Don’t use cmp.set() in JavaScript code to reset an attribute of type="Aura.Action" after it’s previously been set.
Doing so generates an error.
Unable to set value for key 'c.passedAction'. Value provider does not implement
'set(key, value)'. : false
• Don’t use $A.enqueueAction() in the child component to enqueue the action passed to the Aura.Action attribute.
Example
This example demonstrates how to pass an action handler from a parent component to a child component.
Here’s the child component with the Aura.Action attribute. The onclick handler for the button uses the value of the onclick
attribute, which has type of Aura.Action.
<!-- child.cmp -->
<aura:component>
<aura:attribute name="onclick" type="Aura.Action"/>
Here’s the parent component that contains the child component in its markup.
<!-- parent.cmp -->
<aura:component>
<p>Parent component passes handler action to c:child</p>
<c:child onclick="{!c.parentAction}"/>
</aura:component>
410
Reference System Tag Reference
When you click the button in c:child, the parentAction action in the controller of c:parent is executed.
Instead of an Aura.Action attribute, you could use <aura:registerEvent> to register an onclick event in the child
component. You’d have to define the event and create an action in the child’s controller to fire the event. This event-based approach
requires a few extra steps but it’s more in line with standard practices for communicating between components.
SEE ALSO:
Framework-Specific Types
Handling Events with Client-Side Controllers
aura:application
An app is a special top-level component whose markup is in a .app resource.
The markup looks similar to HTML and can contain components as well as a set of supported HTML tags. The .app resource is a
standalone entry point for the app and enables you to define the overall application layout, style sheets, and global JavaScript includes.
It starts with the top-level <aura:application> tag, which contains optional system attributes. These system attributes tell the
framework how to configure the app.
controller String The server-side controller class for the app. The format is
namespace.myController.
extensible Boolean Indicates whether the app is extensible by another app. Defaults to false.
template Component The name of the template used to bootstrap the loading of the framework and
the app. The default value is aura:template. You can customize the template
by creating your own component that extends the default template. For example:
<aura:component extends="aura:template" ... >
tokens String A comma-separated list of tokens bundles for the application. For example,
tokens="ns:myAppTokens". Tokens make it easy to ensure that your
design is consistent, and even easier to update it as your design evolves. Define
the token values once and reuse them throughout your application.
411
Reference aura:component
aura:application also includes a body attribute defined in a <aura:attribute> tag. Attributes usually control the output
or behavior of a component, but not the configuration information in system attributes.
SEE ALSO:
Creating Apps
Using the AppCache
Application Access Control
aura:component
The root of the component hierarchy. Provides a default rendering implementation.
Components are the functional units of Aura, which encapsulate modular and reusable sections of UI. They can contain other components
or HTML markup. The public parts of a component are its attributes and events. Aura provides out-of-the-box components in the aura
and ui namespaces.
Every component is part of a namespace. For example, the button component is saved as button.cmp in the ui namespace
can be referenced in another component with the syntax <ui:button label="Submit"/>, where label="Submit" is
an attribute setting.
To create a component, follow this syntax.
<aura:component>
<!-- Optional coponent attributes here -->
<!-- Optional HTML markup -->
<div class="container">
Hello world!
<!-- Other components -->
</div>
</aura:component>
412
Reference aura:dependency
controller String The server-side controller class for the component. The format is
namespace.myController.
extensible Boolean Set to true if the component can be extended. The default is
false.
isTemplate Boolean Set to true if the component is a template. The default is false.
A template must have isTemplate="true" set in its
<aura:component> tag.
<aura:component isTemplate="true"
extends="aura:template">
template Component The template for this component. A template bootstraps loading of
the framework and app. The default template is aura:template.
You can customize the template by creating your own component
that extends the default template. For example:
<aura:component extends="aura:template" ...
>
aura:component includes a body attribute defined in a <aura:attribute> tag. Attributes usually control the output or
behavior of a component, but not the configuration information in system attributes.
aura:dependency
The <aura:dependency> tag enables you to declare dependencies, which improves their discoverability by the framework.
The framework automatically tracks dependencies between definitions, such as components, defined in markup. This enables the
framework to send the definitions to the browser. However, if a component’s JavaScript code dynamically instantiates another component
or fires an event that isn’t directly referenced in the component’s markup, use <aura:dependency> in the component’s markup
to explicitly tell the framework about the dependency. Adding the <aura:dependency> tag ensures that a definition, such as a
component, and its dependencies are sent to the client, when needed.
For example, adding this tag to a component marks the sampleNamespace:sampleComponent component as a dependency.
<aura:dependency resource="markup://sampleNamespace:sampleComponent" />
413
Reference aura:event
Use the <aura:dependency> tag if you fire an event in JavaScript code and you’re not registering the event in component markup
using <aura:registerEvent>. Using an <aura:registerEvent> tag is the preferred approach.
The <aura:dependency> tag includes these system attributes.
Note: Using an asterisk (*) for wildcard matching is deprecated. Instead, add an
<aura:dependency> tag for each resource that’s not directly referenced in the
component’s markup. Wildcard matching can cause save validation errors when no
resources match. Wildcard matching can also slow page load time because it sends more
definitions than needed to the client.
type The type of resource that the component depends on. The default value is COMPONENT.
Note: Using an asterisk (*) for wildcard matching is deprecated. Instead, add an
<aura:dependency> tag for each resource that’s not directly referenced in the
component’s markup. Be as selective as possible in the types of definitions that you send
to the client.
The most commonly used values are:
• COMPONENT
• EVENT
• INTERFACE
• APPLICATION
Use a comma-separated list for multiple types; for example: COMPONENT,APPLICATION.
SEE ALSO:
Dynamically Creating Components
Fire Component Events
Fire Application Events
aura:event
An event is represented by the aura:event tag, which has the following attributes.
414
Reference aura:interface
SEE ALSO:
Communicating with Events
Event Access Control
aura:interface
The aura:interface tag has the following optional attributes.
SEE ALSO:
Interfaces
Interface Access Control
aura:method
Use <aura:method> to define a method as part of a component's API. This enables you to directly call a method in a component’s
client-side controller instead of firing and handling a component event. Using <aura:method> simplifies the code needed for a
parent component to call a method on a child component that it contains.
The <aura:method> tag has these system attributes.
415
Reference aura:method
access String The access control for the method. Valid values are:
• public—Any component in the same namespace can call the
method. This is the default access level.
• global—Any component in any namespace can call the
method.
Declaring Parameters
An <aura:method> can optionally include parameters. Use an <aura:attribute> tag within an <aura:method> to
declare a parameter for the method. For example:
<aura:method name="sampleMethod" action="{!c.doAction}"
description="Sample method with parameters">
<aura:attribute name="param1" type="String" default="parameter 1"/>
<aura:attribute name="param2" type="Object" />
</aura:method>
Note: You don’t need an access system attribute in the <aura:attribute> tag for a parameter.
Retrieve the arguments using event.getParam('arguments'). It returns an object if there are arguments or an empty array
if there are no arguments.
Returning a Value
aura:method executes synchronously.
416
Reference aura:set
• A synchronous method finishes executing before it returns. Use the return statement to return a value from synchronous JavaScript
code. See Return Result for Synchronous Code.
• An asynchronous method may continue to execute after it returns. Use a callback to return a value from asynchronous JavaScript
code. See Return Result for Asynchronous Code.
SEE ALSO:
Calling Component Methods
Component Events
aura:set
Use <aura:set> in markup to set the value of an attribute inherited from a super component, event, or interface.
To learn more, see:
• Setting Attributes Inherited from a Super Component
• Setting Attributes on a Component Reference
• Setting Attributes Inherited from an Interface
c:setTagSuper outputs:
setTagSuper address1:
The address1 attribute doesn't output any value yet as it hasn't been set.
Here is the c:setTagSub component that extends c:setTagSuper.
<!--c:setTagSub-->
<aura:component extends="c:setTagSuper">
<aura:set attribute="address1" value="808 State St" />
</aura:component>
c:setTagSub outputs:
sampleSetTagExc:setTagSub sets a value for the address1 attribute inherited from the super component,
c:setTagSuper.
Warning: This usage of <aura:set> works for components and abstract components, but it doesn’t work for interfaces. For
more information, see Setting Attributes Inherited from an Interface on page 419.
417
Reference aura:set
If you’re using a component by making a reference to it in your component, you can set the attribute value directly in the markup. For
example, c:setTagSuperRef makes a reference to c:setTagSuper and sets the address1 attribute directly without using
aura:set.
<!--c:setTagSuperRef-->
<aura:component>
<c:setTagSuper address1="1 Sesame St" />
</aura:component>
c:setTagSuperRef outputs:
SEE ALSO:
Component Body
Inherited Component Attributes
Setting Attributes on a Component Reference
<ui:button label="Save">
<aura:set attribute="buttonTitle" value="Click to save the record"/>
</ui:button>
The latter syntax without aura:set makes more sense in this simple example. You can also use this simpler syntax in component
references to set values for attributes that are inherited from parent components.
aura:set is more useful when you want to set markup as the attribute value. For example, this sample specifies the markup for the
else attribute in the aura:if tag.
<aura:component>
<aura:attribute name="display" type="Boolean" default="true"/>
<aura:if isTrue="{!v.display}">
Show this if condition is true
<aura:set attribute="else">
<ui:button label="Save" press="{!c.saveRecord}" />
</aura:set>
</aura:if>
</aura:component>
SEE ALSO:
Setting Attributes Inherited from a Super Component
418
Reference Component Reference
<p>myBoolean: {!v.myBoolean}</p>
</aura:component>
Component Reference
Use out-of-the-box components for Lightning Experience, Salesforce mobile app, or for your Lightning apps. These components belong
to different namespaces, including:
aura
Provides components that are part of the framework’s building blocks.
force
Provides components for field- and record-specific implementations.
forceChatter
Provides components for the Chatter feed.
forceCommunity
Provides components for Communities.
lightning
Provides components with Lightning Design System styling. For components in this namespace that are used in standalone Lightning
apps, extend force:slds to implement Lightning Design System styling. In instances where there are matching ui and
lightning namespace components, we recommend that you use the lightning namespace component. The lightning
namespace components are optimized for common use cases. Event handling for lightning namespace components follows
standard HTML practices and are simpler than that for the ui namespace components. For more information, see Event Handling
in Base Lightning Components.
ui
Provides an older implementation of user interface components that don’t match the look and feel of Lightning Experience and the
Salesforce mobile app. Components in this namespace support multiple styling mechanism, and are usually more complex.
aura:expression
Renders the value to which an expression evaluates. Creates an instance of this component which renders the referenced "property
reference value" set to the value attribute when expressions are found in free text or markup.
An expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. It is used for
dynamic output or passing a value into components by assigning them to attributes.
419
Reference aura:html
The syntax for an expression is {!expression}. expression is evaluated and dynamically replaced when the component is
rendered or when the value is used by the component. The resulting value can be a primitive (integer, string, and so on), a boolean, a
JavaScript or Aura object, an Aura component or collection, a controller method such as an action method, and other useful results.
An expression uses a value provider to access data and can also use operators and functions for more complex expressions. Value
providers include m (data from model), v(attribute data from component), and c (controller action). This example show an expression
{!v.num} whose value is resolved by the attribute num.
Attributes
Attribute Name Attribute Type Description Required?
value String The expression to evaluate and render.
aura:html
A meta component that represents all html elements. Any html found in your markup causes the creation of one of these.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
tag String The name of the html element that should be rendered.
aura:if
Conditionally instantiates and renders either the body or the components in the else attribute.
aura:if evaluates the isTrue expression on the server and instantiates components in either its body or else attribute. Only
one branch is created and rendered. Switching condition unrenders and destroys the current branch and generates the other
<aura:component>
<aura:if isTrue="{!v.truthy}">
True
<aura:set attribute="else">
False
</aura:set>
</aura:if>
</aura:component>
420
Reference aura:iteration
Attributes
Attribute Name Attribute Type Description Required?
body ComponentDefRef[] The components to render when isTrue evaluates to true. Yes
else ComponentDefRef[] The alternative to render when isTrue evaluates to false, and the body is
not rendered. Should always be set using the aura:set tag.
isTrue Boolean An expression that must be fulfilled in order to display the body. Yes
aura:iteration
Renders a view of a collection of items. Supports iterations containing components that can be created exclusively on the client-side.
aura:iteration iterates over a collection of items and renders the body of the tag for each item. Data changes in the collection
are rerendered automatically on the page. It also supports iterations containing components that are created exclusively on the client-side
or components that have server-side dependencies.
This example shows a basic way to use aura:iteration exclusively on the client-side.
<aura:component>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body ComponentDefRef[] Template to use when creating components for each iteration. Yes
indexVar String The name of variable to use for the index of each item inside the iteration
loaded Boolean True if the iteration has finished loading the set of templates.
template ComponentDefRef[] The template that is used to generate components. By default, this is set
from the body markup on first load.
var String The name of the variable to use for each item inside the iteration Yes
421
Reference aura:renderIf
aura:renderIf
Deprecated. Use aura:if instead. This component allows you to conditionally render its contents. It renders its body only if isTrue evaluates
to true. The else attribute allows you to render an alternative when isTrue evaluates to false.
The expression in isTrue is re-evaluated every time any value used in the expression changes. When the results of the expression
change, it triggers a re-rendering of the component. Use aura:renderIf if you expect to show the components for both the true
and false states, and it would require a server round trip to instantiate the components that aren't initially rendered. Switching condition
unrenders current branch and renders the other. Otherwise, use aura:if instead if you want to instantiate the components in either
its body or the else attribute, but not both.
<aura:component>
<aura:renderIf isTrue="{!v.truthy}">
True
<aura:set attribute="else">
False
</aura:set>
</aura:renderIf>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
else Component[] The alternative content to render when isTrue evaluates to false, and the
body is not rendered. Set using the <aura:set> tag.
isTrue Boolean An expression that must evaluate to true to display the body of the Yes
component.
aura:template
Default template used to bootstrap Aura framework. To use another template, extend aura:template and set attributes using aura:set.
Attributes
Attribute Name Attribute Type Description Required?
auraPreInitBlock Component[] The block of content that is rendered before Aura initialization.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
422
Reference aura:text
aura:text
Renders plain text. When any free text (not a tag or attribute value) is found in markup, an instance of this component is created with
the value attribute set to the text found in the markup.
Attributes
Attribute Name Attribute Type Description Required?
value String The String to be rendered.
aura:unescapedHtml
The value assigned to this component will be rendered as-is, without altering its contents. It's intended for outputting pre-formatted
HTML, for example, where the formatting is arbitrary, or expensive to calculate. The body of this component is ignored, and won't be
rendered. Warning: this component outputs value as unescaped HTML, which introduces the possibility of security vulnerabilities in
your code. You must sanitize user input before rendering it unescaped, or you will create a cross-site scripting (XSS) vulnerability. Only
use <aura:unescapedHtml> with trusted or sanitized sources of data.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of <aura:unescapedHtml> is ignored and won't be rendered.
auraStorage:init
Initializes a storage instance using an adapter that satisfies the provided criteria.
Use auraStorage:init to initialize storage in your app’s template for caching server-side action response values.
This example uses a template to initialize storage for server-side action response values. The template contains an auraStorage:init
tag that specifies storage initialization properties.
423
Reference force:canvasApp
When you initialize storage, you can set certain options, such as the name, maximum cache size, and the default expiration time.
Storage for server-side actions caches action response values. The storage name must be actions.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
clearStorageOnInit Boolean Set to true to delete all previous data on initialization (relevant for
persistent storage only). This value defaults to true.
debugLoggingEnabled Boolean Set to true to enable debug logging with $A.log(). This value defaults to
false.
defaultAutoRefreshInterval Integer The default duration (seconds) before an auto refresh request will be
initiated. Actions may override this on a per-entry basis with
Action.setStorable(). This value defaults to 30.
defaultExpiration Integer The default duration (seconds) that an object will be retained in storage.
Actions may override this on a per-entry basis with Action.setStorable().
This value defaults to 10.
maxSize Integer Maximum size (KB) of the storage instance. Existing items will be evicted
to make room for new items; algorithm is adapter-specific. This value
defaults to 1000.
name String The programmatic name for the storage instance. Yes
persistent Boolean Set to true if this storage desires persistence. This value defaults to false.
secure Boolean Set to true if this storage requires secure storage support. This value
defaults to false.
force:canvasApp
Enables you to include a Force.com Canvas app in a Lightning component.
A force:canvasApp component represents a canvas app that's embedded in your Lightning component. You can create a web
app in the language of your choice and expose it in Salesforce as a canvas app. Use the Canvas App Previewer to test and debug the
canvas app before embedding it in a Lightning component.
424
Reference force:canvasApp
If you have a namespace prefix, specify it using the namespacePrefix attribute. Either the developerName or
applicationName attribute is required. This example embeds a canvas app in a Lightning component.
<aura:component>
<force:canvasApp developerName="MyCanvasApp" namespacePrefix="myNamespace" />
</aura:component />
For more information on building canvas apps, see the Force.com Canvas Developer's Guide.
Attributes
Attribute Name Attribute Type Description Required?
applicationName String Name or label of the canvas app. Used to display the app's name while
Canvas is loading.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
border String Width of the canvas app border, in pixels. If not specified, defaults to 0
px.
canvasId String An unique label within a page for the Canvas app window. This should
be used when targeting events to this canvas app.
containerId String An html element id in which canvas app is rendered. The container needs
to be defined before canvasApp cmp usage.
developerName String API name of the canvas app. This name is defined when the canvas app
is created and can be viewed in the Canvas App Previewer. Either
developerName or referenceId is required.
displayLocation String The location in the application where the canvas app is currently being
called from.
height String Canvas app window height, in pixels. If not specified, defaults to 900 px.
maxHeight String The maximum height of the Canvas app window in pixels. Defaults to
2000 px; 'infinite' is also a valid value.
maxWidth String The maximum width of the Canvas app window in pixels. Defaults to
1000 px; 'infinite' is also a valid value.
namespacePrefix String Namespace value of the Developer Edition organization in which the
canvas app was created. Optional if the canvas app wasn’t created in a
Developer Edition organization. If not specified, defaults to null.
onCanvasAppError String Name of the JavaScript function to be called if the canvas app fails to
render.
onCanvasAppLoad String Name of the JavaScript function to be called after the canvas app loads.
onCanvasSubscribed String Name of the JavaScript function to be called after the canvas app registers
with the parent.
425
Reference force:inputField
sublocation String The sublocation is the location in the application where the canvas app
is currently being called from, for ex, displayLocation can be PageLayout
and sublocation can be S1MobileCardPreview or S1MobileCardFullview,
etc
width String Canvas app window width, in pixels. If not specified, defaults to 800 px.
force:inputField
A component that provides a concrete type-specific input component implementation based on the data to which it is bound.
Represents an input field that corresponds to a field on a Salesforce object. This component respects the attributes of the associated
field. For example, if the component is a number field with 2 decimal places, then the default input value contains the same number of
decimal places. It loads the input field according to the field type. If the component corresponds to a date field, a date picker is displayed
in the field. Dependent picklists and rich text fields are not supported. Required fields are not enforced client-side.
This example creates an input field that displays data for a contact name. Bind the field using the value attribute and provide a default
value to initialize the object.
<aura:component controller="ContactController">
<aura:attribute name="contact" type="Contact"
default="{ 'sobjectType': 'Contact' }"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<force:inputField value="{!v.contact.Name}"/>
</aura:component>
In this example, the v.contact.Name expression bounds the value to the Name field on the contact. To load record data, wire up
the container component to an Apex controller that returns the contact.
public with sharing class ContactController {
@AuraEnabled
public static Contact getContact() {
return [select Id, Name from Contact Limit 1];
}
}
426
Reference force:outputField
This component doesn't use the Lightning Design System styling. Use lightning:input if you want an input field that inherits
the Lightning Design System styling.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
errorComponent Component[] For internal use only. Displays error messages for the field.
Events
Event Name Event Type Description
change COMPONENT The event fired when the user changes the content of the input.
force:outputField
A component that provides a concrete type-specific output component implementation based on the data to which it is bound.
Represents a read-only display of a value for a field on a Salesforce object. This component respects the attributes of the associated field
and how it should be displayed. For example, if the component contains a date and time value, then the default output value contains
the date and time in the user's locale.
As of Winter '18, we recommend using lightning:outputField instead.
This example displays data for a contact name. Bind the field using the value attribute and provide a default value to initialize the
object.
<aura:component controller="ContactController">
<aura:attribute name="contact" type="Contact"
default="{ 'sobjectType': 'Contact' }"/>
427
Reference force:recordData
To load record data, wire up the container component to an Apex controller that returns the contact.
public with sharing class ContactController {
@AuraEnabled
public static Contact getContact() {
return [select Id, Name from Contact Limit 1];
}
}
This component doesn't use the Lightning Design System styling. Use lightning:input if you want an input field that inherits
the Lightning Design System styling.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
force:recordData
Provides the ability to create, read, update, and delete Salesforce records in Lightning.
A force:recordData component defines the parameters for accessing, modifying, or creating a record using Lightning Data
Service.
<aura:component>
<force:recordData aura:id="forceRecordCmp"
recordId="{!v.recordId}"
428
Reference force:recordData
layoutType="{!v.layout}"
fields="{!v.fieldsToQuery}"
mode="VIEW"
targetRecord="{!v.record}"
targetFields="{!v.simpleRecord}"
targetError="{!v.error}" />
</aura:component>
Methods
This component supports the following methods.
• getNewRecord: Loads a record template and sets it to the targetRecord attribute, including predefined values for the
object and record type.
• reloadRecord: Performs the same load function as on init using the current configuration values (recordId, layoutType,
mode, and others). Doesn’t force a server trip unless required.
• saveRecord: Saves the record.
• deleteRecord: Deletes the record.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
layoutType String Name of the layout to query, which determines the fields included. Valid
values are FULL or COMPACT. The layoutType and/or fields attribute must
be specified.
mode String The mode in which to load the record: VIEW (default) or EDIT.
targetError String Will be set to the localized error message if the record can't be provided.
targetFields Object A simplified view of the fields in targetRecord, to reference record fields
in component markup.
targetRecord Object The provided record. This attribute will contain only the fields relevant
to the requested layoutType and/or fields atributes.
Events
Event Name Event Type Description
recordUpdated COMPONENT Event fired when the record has changed.
429
Reference force:recordEdit
force:recordEdit
Generates an editable view of the specified Salesforce record.
A force:recordEdit component represents the record edit UI for the specified recordId.
This component displays fields in the order they appear on the corresponding page layout and record details page. If you want granular
control over displaying of specific fields, we recommend using lightning:inputField instead.
This example displays the record edit UI and a button, which when pressed saves the record.
<force:recordEdit aura:id="edit" recordId="a02D0000006V8Ni"/>
<lightning:button label="Save" onclick="{!c.save}"/>
This client-side controller fires the recordSave event, which saves the record.
save : function(component, event, helper) {
component.find("edit").get("e.recordSave").fire();
}
You can provide a dynamic ID for the recordId attribute using the format {!v.myObject.recordId}. To load record data,
wire up the container component to an Apex controller that returns the data. See Working with Salesforce Records in the Lightning
Components Developer Guide for more information.
To indicate that the record has been successfully saved, handle the onSaveSuccess event.
To use this component in a standalone app, extend force:slds for the component to be styled correctly.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
Events
Event Name Event Type Description
recordSave COMPONENT User fired event to indicate request to save the record.
force:recordPreview
force:recordPreview has been deprecated. Use force:recordData instead.
Methods
This component supports the following methods.
getNewRecord: Loads a record template and sets it to force:recordPreview’s targetRecord attribute, including
predefined values for the entity and record type.
430
Reference force:recordPreview
reloadRecord: Performs the same load function as on init using the current configuration values (recordId, layoutType,
mode, and others). Doesn’t force a server trip unless required.
saveRecord: Saves the record.
deleteRecord: Deletes the record.
Attributes
Attribute Name Attribute Type Description Required?
fields String[] List of fields to query.
This attribute or layoutType must be specified. If you specify both,
the list of fields queried is the union of fields from fields and
layoutType.
ignoreExistingAction Boolean Whether to skip the cache and force a server request. Defaults to false.
Setting this attribute to true is useful for handling user-triggered
actions such as pull-to-refresh.
layoutType String Name of the layout to query, which determines the fields included. Valid
values are the following.
• FULL
• COMPACT
This attribute or fields must be specified. If you specify both, the list
of fields queried is the union of fields from fields and layoutType.
mode String The mode in which to access the record. Valid values are the following.
• VIEW
• EDIT
Defaults to VIEW.
431
Reference force:recordView
Events
Event Name Event Type Description
recordUpdated COMPONENT The event fired when the record is loaded, changed, updated, or removed.
force:recordView
Generates a view of the specified Salesforce record.
A force:recordView component represents a read-only view of a record. You can display the record view using different layout
types. By default, the record view uses the full layout to display all fields of the record. The mini layout displays fields corresponding to
the compact layout. You can change the fields and the order they appear in the component by going to Compact Layouts in Setup for
the particular object.
If you want granular control over displaying of specific fields, we recommend using lightning:outputField instead.
This example shows a record view with a mini layout.
<force:recordView recordId="a02D0000006V8Ov" type="MINI"/>
You can provide a dynamic ID for the recordId attribute using the format {!v.myObject.recordId}. To load record data,
wire up the container component to an Apex controller that returns the data. See Working with Salesforce Records in the Lightning
Components Developer Guide for more information.
To use this component in a standalone app, extend force:slds for the component to be styled correctly. Linking and hover overlays
on lookup values are not supported in standalone apps.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
record SObjectRow The record (SObject) to load, optional if recordId attribute is specified.
recordId String The Id of the record to load, optional if record attribute is specified.
type String The type of layout to use to display the record. Possible values: FULL,
MINI. The default is FULL.
forceChatter:feed
Represents a Chatter Feed
A forceChatter:feed component represents a feed that's specified by its type. Use the type attribute to display a specific feed
type. For example, set type="groups" to display the feed from all groups the context user either owns or is a member of.
<aura:component implements="force:appHostable">
<forceChatter:feed type="groups"/>
</aura:component>
432
Reference forceChatter:feed
You can also display a feed depending on the type selected. This example provides a drop-down menu that controls the type of feed
to display.
<aura:component implements="force:appHostable">
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="options" type="List" />
<aura:attribute name="type" type="String" default="News" description="The type of feed"
access="GLOBAL"/>
<aura:attribute name="types" type="String[]"
default="Bookmarks,Company,DirectMessages,Feeds,Files,Filter,Groups,Home,Moderation,Mute,News,PendingReview,Record,Streams,To,Topics,UserProfile"
</aura:iteration>
</lightning:select>
<div aura:id="feedContainer" class="feed-container">
<forceChatter:feed />
</div>
</aura:component>
The types attribute specifies the feed types, which are set on the lightning:select component during component initialization.
When a user selects a feed type, the feed is dynamically created and displayed.
({
// Handle component initialization
doInit : function(component, event, helper) {
var type = component.get("v.type");
var types = component.get("v.types");
var opts = new Array();
433
Reference forceChatter:fullFeed
The feed component is supported for Lightning Experience and communities based on the Customer Service template.
For a list of feed types, see the Chatter REST API Developer's Guide.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
feedDesign String Valid values include DEFAULT ( shows inline comments on desktop, a bit
more detail ) or BROWSE ( primarily an overview of the feed items )
subjectId String For most feeds tied to an entity, this is used specified the desired entity.
Defaults to the current user if not specified
type String The strategy used to find items associated with the subject. Valid values
include: Bookmarks, Company, DirectMessages, Feeds, Files, Filter, Groups,
Home, Moderation, Mute, News, PendingReview, Record, Streams, To,
Topics, UserProfile.
forceChatter:fullFeed
A Chatter feed that is full length.
The fullFeed component is still considered BETA and as such shouldn't be considered ready for production.
The fullFeed component is intended for use with Lightning Out or other apps outside of Salesforce for Android, iOS, and mobile web
and Lightning Experience.
Including the fullFeed component in Lightning Experience at this time will result in unexpected behaviour such as posts being duplicated
(temporarily in the UI). To implement a Chatter feed in Lightning Experience, use forceChatter:publisher and
forceChatter:feed instead.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
handleNavigationEvents Boolean Should this component handle navigation events for entities and urls. If
true then navigation events will result in the entity or url being opened
in a new window.
subjectId String For most feeds tied to an entity, this is used specified the desired entity.
Defaults to the current user if not specified
type String The strategy used to find items associated with the subject. Valid values
include: News, Home, Record, To.
434
Reference forceChatter:publisher
forceChatter:publisher
Lets users create posts on records or groups and upload attachments from their desktops in Lightning Experience and communities and
from their mobile devices in communities. Note that this component is not available to mobile devices in Lightning Experience.
The forceChatter:publisher component is a standalone publisher component you can place on a record page. It works
together with the forceChatter:feed component available in the Lightning App Builder to provide a complete Chatter experience.
The advantage of having separate components for publisher and feed is the flexibility it gives you in arranging page components. The
connection between publisher and feed is automatic and requires no additional coding.
The forceChatter:publisher component includes the context attribute, which determines what type of feed is shown.
Use RECORD for a record feed, and GLOBAL for all other feed types.
<aura:component implements="flexipage:availableForAllPageTypes" description="Sample
Component">
<forceChatter:publisher context="GLOBAL" />
<forceChatter:feed type="Company" />
</aura:component>
This component is supported for Lightning Experience and communities based on the Customer Service template.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
context String The context in which the component is being displayed (RECORD or Yes
GLOBAL). RECORD is for a record feed, and GLOBAL is for all other feed
types. This attribute is case-sensitive.
forceCommunity:appLauncher
Displays the App Launcher in Lightning communities to make it easy for members to move between their communities and their
Salesforce org. Add this component to any custom Lightning component in communities.
A forceCommunity:appLauncher component represents an App Launcher icon. Clicking this icon presents users with tiles
that link to their communities, connected apps, Salesforce apps, and on-premises applications. Members see only the communities and
apps that they’re authorized to see according to their profile or permission sets. To let members see the App Launcher, you must also
enable the Show App Launcher in Communities permission in user profiles in Setup. This component is not available in the Salesforce
mobile app or in Salesforce Tabs + Visualforce communities.
<aura:component>
<forceCommunity:appLauncher/>
</aura:component>
If you include the App Launcher in a custom theme layout, it is visible to all pages that use that custom theme layout.
435
Reference forceCommunity:appLauncher
Here’s an example custom theme layout component that uses the default Navigation Menu and includes
forceCommunity:appLauncher.
You can either use the App Launcher that’s included in the default Navigation Menu, or include it in the custom theme layout and hide
the App Launcher in the default Navigation Menu. To remove the App Launcher in the default Navigation Menu, select Hide App Launcher
in community header in the Navigation Menu property editor in Community Builder.
Alternatively, you could create a custom Navigation Menu that includes a forceCommunity:appLauncher component. Then
you could use this menu in a custom theme layout.
Here's an example custom navigation menu component that includes the forceCommunity:appLauncher component.
<aura:component extends="forceCommunity:navigationMenuBase"
implements="forceCommunity:availableForAllPageTypes">
<ul onclick="{!c.onClick}">
<li><forceCommunity:appLauncher/></li>
<aura:iteration items="{!v.menuItems}" var="item">
<aura:if isTrue="{!item.subMenu}">
<li>{!item.label}</li>
<ul>
<aura:iteration items="{!item.subMenu}" var="subItem">
<li><a data-menu-item-id="{!subItem.id}"
href="">{!subItem.label}</a></li>
</aura:iteration>
</ul>
<aura:set attribute="else">
<li><a data-menu-item-id="{!item.id}" href="">{!item.label}</a></li>
436
Reference forceCommunity:navigationMenuBase
</aura:set>
</aura:if>
</aura:iteration>
</ul>
</aura:component>
Here’s an example custom theme layout component that uses a custom Navigation Menu that includes the
forceCommunity:appLauncher component. The custom Navigation Menu is provided by the custom component
c:CustomNavMenu for this example.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
forceCommunity:navigationMenuBase
An abstract component for customizing the navigation menu in a community, which loads menu data and handles navigation. The
menu’s look and feel is controlled by the component that's extending it.
Extend the forceCommunity:navigationMenuBase component to create a customized navigation component for the
Customer Service (Napili) or custom community templates. Provide navigation menu data using the menu editor in Community Builder
or via the NavigationMenuItem entity.
The menuItems attribute is automatically populated with an array of top-level menu items, each with the following properties:
437
Reference forceCommunity:navigationMenuBase
<aura:component extends="forceCommunity:navigationMenuBase"
implements="forceCommunity:availableForAllPageTypes">
<ul onclick="{!c.onClick}">
<aura:iteration items="{!v.menuItems}" var="item" >
<aura:if isTrue="{!item.subMenu}">
<li>{!item.label}</li>
<ul>
<aura:iteration items="{!item.subMenu}" var="subItem">
<li><a data-menu-item-id="{!subItem.id}"
href="">{!subItem.label}</a></li>
</aura:iteration>
</ul>
<aura:set attribute="else">
<li><a data-menu-item-id="{!item.id}" href="">{!item.label}</a></li>
</aura:set>
</aura:if>
</aura:iteration>
</ul>
</aura:component>
({
onClick : function(component, event, helper) {
var id = event.target.dataset.menuItemId;
if (id) {
component.getSuper().navigate(id);
}
}
})
Methods
navigate(menuItemId): Navigates to the page the menu item points to. Takes the id of the menu item as a parameter.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
menuItems Object Automatically populated with menu item’s data. This attribute is
read-only.
438
Reference forceCommunity:notifications
forceCommunity:notifications
The Notifications tool lets your members receive notifications wherever they are working, whether in their communities or in their apps.
Members receive notifications on any screen—mobile, tablet, and desktop. All events that trigger notifications (@mentions and group
posts) are supported. When a member clicks a notification, the originating detail page or other appropriate location is displayed for
seamless collaboration across communities and apps.
A forceCommunity:notifications component represents a Notifications icon. Notifications alert users when key events
occur, such as when they are mentioned in Chatter posts. This component is supported for Lightning Experience, Salesforce mobile app,
and Lightning communities.
<aura:component>
<forceCommunity:notifications/>
</aura:component>
Notifications let users receive notifications wherever they are working, whether in their communities, or in their apps. All events that
trigger notifications (@mentions and group posts) are supported. Users can even trigger notifications on record feeds For example, an
internal user can trigger a notification from the Salesforce org by @mentioning an external user on a lead or opportunity.
Here’s an example custom theme layout component that includes forceCommunity:notifications.
<aura:component implements="forceCommunity:themeLayout" access="global" description="Sample
Custom Theme Layout">
<aura:attribute name="search" type="Aura.Component[]" required="false"/>
<aura:attribute name="profileMenu" type="Aura.Component[]" required="false"/>
<aura:attribute name="navBar" type="Aura.Component[]" required="false"/>
<aura:attribute name="newHeader" type="Aura.Component[]" required="false"/>
<div>
<div class="notifications">
<forceCommunity:notifications/>
</div>
<div class="searchRegion">
{!v.search}
</div>
<div class="profileMenuRegion">
{!v.profileMenu}
</div>
<div class="navigation">
{!v.navBar}
</div>
<div class="newHeader">
{!v.newHeader}
</div>
<div class="mainContentArea">
{!v.body}
</div>
</div>
</aura:component>
439
Reference forceCommunity:routeLink
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
forceCommunity:routeLink
Sets an HTML anchor tag with an href attribute that’s automatically generated from the provided record ID. Use it to improve SEO link
equity in template-based communities.
Because the href attribute is automatically generated from the provided record ID, forceCommunity:routeLink is only
suitable for creating internal links to recordId-based pages in your community, such as the Article Detail or the Case Detail pages.
Internal links help establish an SEO-friendly site hierarchy and spread link equity (or link juice) to your community’s pages.
Here's an example of a forceCommunity:routeLink component:
<aura:component implements="forceCommunity:availableForAllPageTypes">
<aura:attribute name="recordId" type="String" default="500xx000000YkvU" />
<aura:attribute name="routeInput" type="Map"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<forceCommunity:routeLink id="myCaseId" class="caseClass" title="My Case Tooltip"
label="My Case Link Text" routeInput="{!v.routeInput}" onClick="{!c.onClick}"/>
</aura:component>
To create the link, the client-side controller sets the record ID on the routeInput attribute during initialization. Clicking the link
enables you to navigate to the record page.
({
doInit : function(component, event, helper) {
component.set('v.routeInput', {recordId: component.get('v.recordId')});
},
440
Reference forceCommunity:waveDashboard
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
routeInput HashMap The map of dynamic parameters that create the link. Only recordId-based Yes
routes are supported.
forceCommunity:waveDashboard
Use this component to add a Salesforce Analytics dashboard to a Community page.
Add Analytics Wave dashboard components to community pages to provide interactive visualizations of your data. Users can drill in and
explore the dashboard within the frame on the community page or in an Analytics window.
The Wave dashboard component is available in the Customer Service (Napili) template as a drag-and-drop component, however, you
can also create your own Wave dashboard component using forceCommunity:waveDashboard.
Here's an example of a forceCommunity:waveDashboard component:
<aura:component implements="forceCommunity:availableForAllPageTypes">
<forceCommunity:waveDashboard dashboardId="0FKxx000000000uGAA" />
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
accessToken String A valid access token obtained by logging into Salesforce. Useful when
the component is used by Lightning Out in a non-Salesforce domain.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
dashboardId String The unique ID of the dashboard. You can get a dashboard’s ID, an
18-character code beginning with 0FK, from the dashboard's URL, or you
can request it through the API. This attribute can be used instead of the
developer name, but it can't be included if the name has been set. One
of the two is required.
441
Reference lightning:accordion
filter String Adds selections or filters to the embedded dashboard at runtime. The
filter attribute is configured using JSON. For filtering by dimension, use
this syntax: {'datasets' : {'dataset1': [ {'fields': ['field1'], 'selection': ['$value1',
'$value2']}, {'fields': ['field2'], 'filter': { 'operator': 'operator1', 'values':
['$value3', '$value4']}}]}}. For filtering on measures, use this syntax:
{'datasets' : {'dataset1': [ {'fields': ['field1'], 'selection': ['$value1', '$value2']},
{'fields': ['field2'], 'filter': { 'operator': 'operator1', 'values': [[$value3]]}}]}}.
With the selection option, the dashboard is shown with all its data, and
the specified dimension values are highlighted. With the filter option,
the dashboard is shown with only filtered data. For more information,
see
https://help.salesforce.com/articleView?id=bi_embed_community_builder.htm.
hideOnError Boolean Controls whether or not users see a dashboard that has an error. When
this attribute is set to true, if the dashboard has an error, it won’t appear
on the page. When set to false, the dashboard appears but doesn’t show
any data. An error can occur when a user doesn't have access to the
dashboard or it has been deleted.
openLinksInNewWindow Boolean If false, links to other dashboards will be opened in the same window.
recordId String Id of the current entity in the context of which the component is being
displayed.
showHeader Boolean If true, the dashboard is displayed with a header bar that includes
dashboard information and controls. If false, the dashboard appears
without a header bar. Note that the header bar automatically appears
when either showSharing or showTitle is true.
showSharing Boolean If true, and the dashboard is shareable, then the dashboard shows the
Share icon. If false, the dashboard doesn't show the Share icon. To show
the Share icon in the dashboard, the smallest supported frame size is 800
x 612 pixels.
showTitle Boolean If true, the dashboard’s title is included above the dashboard. If false, the
dashboard appears without a title.
lightning:accordion
A collection of vertically stacked sections with multiple content areas. This component requires version 41.0 and later.
A lightning:accordion component groups related content in a single container. Only one accordion section is expanded at a
time. When you select a section, it's expanded or collapsed. Each section can hold one or more Lightning components.
442
Reference lightning:accordionSection
This component inherits styling from accordion in the Lightning Design System.
To additionally style this component, use the Lightning Design System helper classes.
This example creates a basic accordion with three sections, where section B is expanded by default.
<aura:component>
<lightning:accordion activeSectionName="B">
<lightning:accordionSection name="A" label="Accordion Title A">This is the content
area for section A</lightning:accordionSection>
<lightning:accordionSection name="B" label="Accordion Title B">This is the content
area for section B</lightning:accordionSection>
<lightning:accordionSection name="C" label="Accordion Title C">This is the content
area for section C</lightning:accordionSection>
</lightning:accordion>
</aura:component>
Usage Considerations
The first section in the lightning:accordion is expanded by default. To change the default, use the activeSectionName
attribute. This attribute is case-sensitive.
If two or more sections use the same name and that name is also specified as the activeSectionName, the first section is expanded
by default.
Attributes
Attribute Name Attribute Type Description Required?
activeSectionName String The activeSectionName changes the default expanded section. The first
section in the accordion is expanded by default.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
lightning:accordionSection
A single section that is nested in a lightning:accordion component. This component requires version 41.0 and later.
A lightning:accordionSection component keeps related content in a single container. When you select a section, it's
expanded or collapsed. Each section can hold one or more Lightning components. This component is intended to be used with
lightning:accordion.
This component inherits styling from accordion in the Lightning Design System.
To additionally style this component, use the Lightning Design System helper classes.
This example creates a basic accordion with three sections, where section B is expanded by default.
<aura:component>
443
Reference lightning:accordionSection
<lightning:accordion activeSectionName="B">
<lightning:accordionSection label="Accordion Title A" name="A">This is the content
area for section A</lightning:accordionSection>
<lightning:accordionSection label="Accordion Title B" name="B">This is the content
area for section B</lightning:accordionSection>
<lightning:accordionSection label="Accordion Title C" name="C">This is the content
area for section C</lightning:accordionSection>
</lightning:accordion>
</aura:component>
This example creates the same basic accordion with an added buttonMenu on the first section.
<aura:component>
<lightning:accordion>
<lightning:accordionSection label="Accordion Title A" name="A">This is the content
area for section A
<aura:set attribute="actions">
<lightning:buttonMenu aura:id="menu" alternativeText="Show menu">
<lightning:menuItem value="New" label="Menu Item One" />
</lightning:buttonMenu>
</aura:set>
</lightning:accordionSection>
<lightning:accordionSection label="Accordion Title B" name="B">This is the content
area for section B</lightning:accordionSection>
<lightning:accordionSection label="Accordion Title C" name="C">This is the content
area for section C</lightning:accordionSection>
</lightning:accordion>
</aura:component>
Usage Considerations
The first section in the lightning:accordion is expanded by default. To change the default, use the activeSectionName
attribute.
If two or more sections use the same name and that name is also specified as the activeSectionName, the first section is expanded
by default.
A lightning:accordionSection component is a single section that’s nested in a lightning:accordion component. You can't use this
component on its own. This example creates a basic accordion with one section.
444
Reference lightning:avatar
Attributes
Attribute Name Attribute Type Description Required?
actions Component[] Enables a custom menu implementation. Actions are displayed to the
right of the section title.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
label String The text that displays as the title of the section.
name String The unique section name to use with the activeSectionName attribute
in the lightning:accordion component.
title String Displays tooltip text when the mouse moves over the element.
lightning:avatar
A visual representation of an object.
A lightning:avatar component is an image that represents an object, such as an account or user. By default, the image renders
in medium sizing with a rounded rectangle, which is also known as the square variant.
This component inherits styling from avatars in the Lightning Design System.
Use the class attribute to apply additional styling.
Here is an example.
<aura:component>
<lightning:avatar src="/images/codey.jpg" alternativeText="Codey Bear"/>
</aura:component>
To use an image in your org, upload it as a static resource in the Static Resources setup page. Use the {!$Resource.logo}" syntax
in your src attribute, where logo is the name you provided in the Name field on the setup page.
Handling Invalid Image Paths
The src attribute resolves the relative path to an image, but sometimes the image path doesn't resolve correctly because the app is
offline or the image has been deleted. To handle an invalid image path, you can provide fallback initials using the initials attribute.
This example displays the initials "Sa" if the image path is invalid.
<lightning:avatar src="/bad/image/url.jpg" initials="Sa"
fallbackIconName="standard:account" alternativeText="Salesforce"/>
In the previous example, the fallback icon "standard:account" is displayed if initials are not provided.
445
Reference lightning:badge
Accessibility
Use the alternativeText attribute to describe the avatar, such as a user's initials or name. This description provides the value for
the alt attribute in the img HTML tag.
Attributes
Attribute Name Attribute Type Description Required?
alternativeText String The alternative text used to describe the avatar, which is displayed as Yes
hover text on the image.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
fallbackIconName String The Lightning Design System name of the icon used as a fallback when
the image fails to load. The initials fallback relies on this for its background
color. Names are written in the format 'standard:account' where 'standard'
is the category, and 'account' is the specific icon to be displayed. Only
icons from the standard and custom categories are allowed.
initials String If the record name contains two words, like first and last name, use the
first capitalized letter of each. For records that only have a single word
name, use the first two letters of that word using one capital and one
lower case letter.
size String The size of the avatar. Valid values are x-small, small, medium, and large.
This value defaults to medium.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the shape of the avatar. Valid values are empty, circle,
and square. This value defaults to square.
lightning:badge
Represents a label which holds a small amount of information, such as the number of unread notifications.
A lightning:badge is a label that holds small amounts of information. A badge can be used to display unread notifications, or to
label a block of text. Badges don’t work for navigation because they can't include a hyperlink.
This component inherits styling from badges in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:badge label="Label" />
</aura:component>
446
Reference lightning:breadcrumb
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
lightning:breadcrumb
An item in the hierarchy path of the page the user is on.
A lightning:breadcrumb component displays the path of a page relative to a parent page. Breadcrumbs are nested in a
lightning:breadcrumbs component. Each breadcrumb is actionable and separated by a greater-than sign. The order the
breadcrumbs appear depends on the order they are listed in markup.
This component inherits styling from breadcrumbs in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:breadcrumbs>
<lightning:breadcrumb label="Parent Account" href="path/to/place/1"/>
<lightning:breadcrumb label="Case" href="path/to/place/2"/>
</lightning:breadcrumbs>
</aura:component>
The behavior of a breadcrumb is similar to a link. If a link is not provided via the href attribute, the value defaults to
javascript:void(0);. To provide custom navigation, use an onclick handler. For example, using onclick is useful if
you're navigating using an event like force:navigateToSObject. If you provide a link in the href attribute, calling
event.preventDefault() enables you to bypass the link and use your custom navigation instead.
<aura:component>
<lightning:breadcrumbs>
<lightning:breadcrumb label="Parent Account" href="path/to/place/1" onclick="{!
c.navigateToCustomPage1 }"/>
<lightning:breadcrumb label="Case" href="path/to/place/2" onclick="{!
c.navigateToCustomPage2 }"/>
</lightning:breadcrumbs>
</aura:component>
447
Reference lightning:breadcrumb
/* Client-Side Controller */
({
init: function (cmp, event, helper) {
var myBreadcrumbs = [
{label: 'Account', name: 'objectName' },
{label: 'Record Name', name: 'record' }
];
cmp.set('v.myBreadcrumbs', myBreadcrumbs);
},
navigateTo: function (cmp, event, helper) {
//get the name of the breadcrumb that's clicked
var name = event.getSource().get('v.name');
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
href String The URL of the page that the breadcrumb goes to.
name String The name for the breadcrumb component. This value is optional and
can be used to identify the breadcrumb in a callback.
448
Reference lightning:breadcrumbs
lightning:breadcrumbs
A hierarchy path of the page you're currently visiting within the website or app.
A lightning:breadcrumbs component is an ordered list that displays the path of a page and helps you navigate back to the
parent. Each breadcrumb item is represented by a lightning:breadcrumb component. Breadcrumbs are actionable and separated
by a greater-than sign.
This component inherits styling from breadcrumbs in the Lightning Design System.
For more information, see lightning:breadcrumb.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
lightning:button
Represents a button element.
A lightning:button component represents a button element that executes an action in a controller. Clicking the button triggers
the client-side controller method set for onclick. Buttons can be either a label only, label and icon, body only, or body and icon. Use
lightning:buttonIcon if you need an icon-only button.
Use the variant and class attributes to apply additional styling.
The Lightning Design System utility icon category provides nearly 200 utility icons that can be used in lightning:button along
with label text. Although SLDS provides several categories of icons, only the utility category can be used in this component.
Visit https://lightningdesignsystem.com/icons/#utility to view the utility icons.
This component inherits styling from buttons in the Lightning Design System.
Here's an example that creates a button with the brand variant, which displays a label on the button.
<aura:component>
<lightning:button variant="brand" label="Submit" onclick="{! c.handleClick }" />
</aura:component>
Here's another example that creates a button with the brand variant, which displays a label and icon on the button.
<aura:component>
<lightning:button variant="brand" label="Download" iconName="utility:download"
449
Reference lightning:button
You can retrieve the button that's clicked by using event.getSource(). For example, to retrieve the label on the button, use
event.getSource().get("v.label").
Accessibility
To inform screen readers that a button is disabled, set the disabled attribute to true.
Methods
This component supports the following method.
focus(): Sets the focus on the element.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies whether this button should be displayed in a disabled state.
Disabled buttons can't be clicked. This value defaults to false.
iconName String The Lightning Design System name of the icon. Names are written in the
format 'utility:down' where 'utility' is the category, and 'down' is the
specific icon to be displayed.
iconPosition String Describes the position of the icon with respect to body. Options include
left and right. This value defaults to left.
name String The name for the button element. This value is optional and can be used
to identify the button in a callback.
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
title String Displays tooltip text when the mouse moves over the element.
type String Specifies the type of button. Valid values are button, reset, and submit.
This value defaults to button.
450
Reference lightning:buttonGroup
variant String The variant changes the appearance of the button. Accepted variants
include base, neutral, brand, destructive, inverse, and success. This value
defaults to neutral.
lightning:buttonGroup
Represents a group of buttons.
A lightning:buttonGroup component represents a set of buttons that can be displayed together to create a navigational bar.
The body of the component can contain lightning:button or lightning:buttonMenu. If navigational tabs are needed,
use lightning:tabset instead of lightning:buttonGroup.
This component inherits styling from button groups in the Lightning Design System.
To create buttons, use the lightning:button component as shown in this example.
<aura:component>
<lightning:buttonGroup>
<lightning:button label="Refresh" onclick="{!c.handleClick}"/>
<lightning:button label="Edit" onclick="{!c.handleClick}"/>
<lightning:button label="Save" onclick="{!c.handleClick}"/>
</lightning:buttonGroup>
</aura:component>
The onclick handler in lightning:button calls the handleClick client-side controller, which returns the label of the
button that was clicked.
({
handleClick: function (cmp, event, helper) {
var selectedButtonLabel = event.getSource().get("v.label");
alert("Button label: " + selectedButtonLabel);
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
451
Reference lightning:buttonIcon
lightning:buttonIcon
An icon-only HTML button.
A lightning:buttonIcon component represents an icon-only button element that executes an action in a controller. Clicking
the button triggers the client-side controller method set for onclick.
You can use a combination of the variant, size, class, and iconClass attributes to customize the button and icon styles.
To customize styling on the button container, use the class attribute. For the bare variant, the size class applies to the icon itself.
For non-bare variants, the size class applies to the button. To customize styling on the icon element, use the iconClass attribute.
This example creates an icon-only button with bare variant and custom icon styling.
<!-- Bare variant with custom "dark" CSS class added to icon svg element -->
<lightning:buttonIcon iconName="utility:settings" variant="bare" alternativeText="Settings"
iconClass="dark"/>
The Lightning Design System utility icon category offers nearly 200 utility icons that can be used in lightning:buttonIcon.
Although the Lightning Design System provides several categories of icons, only the utility category can be used in
lightning:buttonIcon.
Visit https://lightningdesignsystem.com/icons/#utility to view the utility icons.
This component inherits styling from button icons in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:buttonIcon iconName="utility:close" variant="bare" onclick="{! c.handleClick
}" alternativeText="Close window." />
</aura:component>
Usage Considerations
When using lightning:buttonIcon in a standalone app, extend force:slds to resolve the icon resources correctly.
<aura:application extends="force:slds">
<lightning:buttonIcon iconName="utility:close" alternativeText="Close"/>
</aura:application>
Accessibility
Use the alternativeText attribute to describe the icon. The description should indicate what happens when you click the button,
for example 'Upload File', not what the icon looks like, 'Paperclip'.
Methods
This component supports the following method.
focus(): Sets focus on the element.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
alternativeText String The alternative text used to describe the icon. This text should describe Yes
what happens when you click the button, for example 'Upload File', not
what the icon looks like, 'Paperclip'.
452
Reference lightning:buttonIconStateful
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies whether this button should be displayed in a disabled state.
Disabled buttons can't be clicked. This value defaults to false.
iconName String The Lightning Design System name of the icon. Names are written in the Yes
format '\utility:down\' where 'utility' is the category, and 'down' is the
specific icon to be displayed. Note: Only utility icons can be used in this
component.
name String The name for the button element. This value is optional and can be used
to identify the button in a callback.
onblur Action The action triggered when the element releases focus.
onclick Action The action that will be run when the button is clicked.
onfocus Action The action triggered when the element receives focus.
size String The size of the buttonIcon. For the bare variant, options include x-small,
small, medium, and large. For non-bare variants, options include xx-small,
x-small, small, and medium. This value defaults to medium.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
title String Displays tooltip text when the mouse moves over the element.
type String Specifies the type of button. Valid values are button, reset, and submit.
This value defaults to button.
value String The value for the button element. This value is optional and can be used
when submitting a form.
variant String The variant changes the appearance of buttonIcon. Accepted variants
include bare, container, border, border-filled, bare-inverse, and
border-inverse. This value defaults to border.
lightning:buttonIconStateful
An icon-only button that retains state. This component requires API version 41.0 and later.
A lightning:buttonIconStateful component represents an icon-only button element that toggles between two states.
For example, you can use this component for capturing a customer's feedback on a blog post (like or dislike). Clicking the button triggers
the client-side controller method set for onclick and changes the state of the icon using the selected attribute.
453
Reference lightning:buttonIconStateful
The Lightning Design System utility icon category offers nearly 200 utility icons that can be used in
lightning:buttonIconStateful. Although the Lightning Design System provides several categories of icons, only the utility
category can be used with this component.
Visit https://lightningdesignsystem.com/icons/#utility to view the utility icons.
This component inherits styling from button icons in the Lightning Design System.
You can use a combination of the variant, size, and class attributes to customize the button and icon styles. To customize
styling on the button container, use the class attribute.
This example creates a like button that toggles between two states. The like button is selected by default. The button's state is stored
in the selected attribute.
<aura:component>
<aura:attribute name="liked" type="Boolean" default="true"/>
<lightning:buttonIconStateful iconName="utility:like" selected="{!v.liked}"
alternativeText="Like" onclick="{! c.handleToggle }"/>
<aura:component>
Selecting the dislike button also toggles the state on the like button and deselects it.
({
handleToggle : function (cmp, event) {
var liked = cmp.get("v.liked");
cmp.set("v.liked", !liked);
}
})
Methods
This component supports the following method.
focus(): Sets focus on the element.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
onfocus Action The action triggered when the element receives focus.
onblur Action The action triggered when the element releases focus.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
name String The name for the button element. This value is optional and can be used
to identify the button in a callback.
454
Reference lightning:buttonMenu
iconName String The Lightning Design System name of the icon. Names are written in the Yes
format 'utility:down' where 'utility' is the category, and 'down' is the
specific icon to be displayed. Note: Only utility icons can be used in this
component.
variant String The variant changes the appearance of buttonIcon. Accepted variants
include border, border-filled, and border-inverse. This value defaults to
border.
size String The size of the buttonIcon. Options include xx-small, x-small, small, and
medium. This value defaults to medium.
disabled Boolean Specifies whether this button should be displayed in a disabled state.
Disabled buttons can't be clicked. This value defaults to false.
alternativeText String The alternative text used to describe the icon. This text should describe Yes
what happens when you click the button, for example 'Upload File', not
what the icon looks like, 'Paperclip'.
onclick Action The action that will be run when the button is clicked.
lightning:buttonMenu
Represents a dropdown menu with a list of actions or functions.
A lightning:buttonMenu represents a button that when clicked displays a dropdown menu of actions or functions that a user
can access.
Use the variant, size, or class attributes to customize the styling.
This component inherits styling from menus in the Lightning Design System.
This example shows a dropdown menu with three items.
<lightning:buttonMenu iconName="utility:settings" alternativeText="Settings" onselect="{!
c.handleMenuSelect }">
<lightning:menuItem label="Font" value="font" />
<lightning:menuItem label="Size" value="size"/>
<lightning:menuItem label="Format" value="format" />
</lightning:buttonMenu>
When onselect is triggered, its event will have a value parameter, which is the value of the selected menu item. Here's an example
of how to read that value.
handleMenuSelect: function(cmp, event, helper) {
var selectedMenuItemValue = event.getParam("value");
}
455
Reference lightning:buttonMenu
You can create menu items that can be checked or unchecked using the checked attribute in the lightning:menuItem
component, toggling it as needed. To enable toggling of a menu item, you must set an initial value on the checked attribute, specifying
either true or false.
The menu closes when you click away from it, and it will also close and will put the focus back on the button when a menu item is
selected.
Generating Menu Items with aura:iteration
This example creates a button menu with several items during initialization.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.createItems}" />
<lightning:buttonMenu alternativeText="Action" onselect="{! c.handleMenuSelect }">
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
456
Reference lightning:buttonStateful
disabled Boolean If true, the menu is disabled. Disabling the menu prevents users from
opening it. This value defaults to false.
iconName String The name of the icon to be used in the format 'utility:down'. This value
defaults to utility:down. If an icon other than utility:down or
utility:chevrondown is used, a utility:down icon is appended to the right
of that icon.
iconSize String The size of the icon. Options include xx-small, x-small, medium, or large.
This value defaults to medium.
menuAlignment String Determines the alignment of the menu relative to the button. Available
options are: left, center, right. This value defaults to left.
name String The name for the button element. This value is optional and can be used
to identify the button in a callback.
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
onselect Action Action fired when a menu item is selected. The 'detail.menuItem' property
of the passed event is the selected menu item.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
value String The value for the button element. This value is optional and can be used
when submitting a form.
variant String The variant changes the look of the button. Accepted variants include
bare, container, border, border-filled, bare-inverse, and border-inverse.
This value defaults to border.
visible Boolean If true, the menu items are displayed. This value defaults to false.
lightning:buttonStateful
A button that toggles between states.
A lightning:buttonStateful component represents a button that toggles between states, similar to a like button on social
media. Stateful buttons can show a different label and icon based on their states.
Use the variant and class attributes to apply additional styling.
The Lightning Design System utility icon category provides nearly 200 utility icons that can be used in lightning:button along
with a text label. Although the Lightning Design System provides several categories of icons, only the utility category can be used with
this component.
Visit https://lightningdesignsystem.com/icons/#utility to view the utility icons.
457
Reference lightning:buttonStateful
This component inherits styling from stateful buttons in the Lightning Design System.
To handle the state change when the button is clicked, use the onclick event handler. This example enables you to toggle the button
between states, displaying the "Follow" label by default, and replacing it with "Following" when the button is selected. Selecting the
button toggles the state to true, and deselecting it toggles the state to false. When the state is true, the button displays "Unfollow" when
you mouse over it or when it receives focus.
<aura:component>
<aura:attribute name="buttonstate" type="Boolean" default="false"/>
<lightning:buttonStateful
labelWhenOff="Follow"
labelWhenOn="Following"
labelWhenHover="Unfollow"
iconNameWhenOff="utility:add"
iconNameWhenOn="utility:check"
iconNameWhenHover="utility:close"
state="{! v.buttonstate }"
onclick="{! c.handleClick }"
/>
</aura:component>
The client-side controller toggles the state via the buttonstate attribute.
({
handleClick : function (cmp, event, helper) {
var buttonstate = cmp.get('v.buttonstate');
cmp.set('v.buttonstate', !buttonstate);
}
})
Accessibility
For accessibility, include the attribute aria-live="assertive" on the button. The aria-live="assertive" attribute
means the value of the <span> inside the button will be spoken whenever it changes.
To inform screen readers that a button is disabled, set the disabled attribute to true.
Methods
This component supports the following method.
focus(): Sets focus on the element.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
iconNameWhenHover String The name of the icon to be used in the format \'utility:close\' when the
state is true and the button receives focus.
458
Reference lightning:card
iconNameWhenOn String The name of the icon to be used in the format \'utility:check\' when the
state is true.
labelWhenHover String The text to be displayed inside the button when state is true and the
button receives focus.
labelWhenOff String The text to be displayed inside the button when state is false. Yes
labelWhenOn String The text to be displayed inside the button when state is true. Yes
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
state Boolean The state of the button, which shows whether the button has been
selected or not. The default state is false.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the appearance of the button. Accepted variants
include brand, destructive, inverse, neutral, success, and text. This value
defaults to neutral.
lightning:card
Cards are used to apply a container around a related grouping of information.
A lightning:card is used to apply a stylized container around a grouping of information. The information could be a single item
or a group of items such as a related list.
Use the variant or class attributes to customize the styling.
A lightning:card contains a title, body, and footer. To style the card body, use the Lightning Design System helper classes.
This component inherits styling from cards in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:card title="Card Header" iconName="standard:account" footer="Card Footer">
<aura:set attribute="actions">
<lightning:button label="New"/>
</aura:set>
<p class="slds-p-horizontal_small">
Card Body
</p>
459
Reference lightning:card
</lightning:card>
</aura:component>
Usage Considerations
The title and footer attributes are of type Object, which means that you can pass in values of String or Component[]
types among some others. The previous example passes in the title and footer attributes as a Component[] type, also known
as a facet. The Component[] type is useful if you need to pass in markup to the title or footer, as shown in this example.
<aura:component>
<aura:attribute name="name" type="String" default="Your Name"/>
<aura:attribute name="myTitleName" type="Aura.Component[]">
<h1>Hello {! v.name }</h1>
</aura:attribute>
<lightning:card footer="Card Footer">
<aura:set attribute="title">
{!v.myTitleName}
</aura:set>
<!-- actions and body markup here -->
</lightning:card>
</aura:component>
To pass in a value of String type, you can include it in the <lightning:card> tag.
<aura:component>
<aura:attribute name="myTitle" type="String" default="My Card Title"/>
<lightning:card title="{!v.myTitle}" footer="Card Footer">
<aura:set attribute="actions">
<lightning:button label="New"/>
</aura:set>
<p class="slds-p-horizontal_small">
Card Body (custom component)
</p>
</lightning:card>
Attributes
Attribute Name Attribute Type Description Required?
actions Component[] Actions are components such as button or buttonIcon. Actions are
displayed in the header.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
iconName String The Lightning Design System name of the icon. Names are written in the
format 'utility:down' where 'utility' is the category, and 'down' is the
specific icon to be displayed. The icon is displayed in the header to the
left of the title.
460
Reference lightning:carousel (Beta)
variant String The variant changes the appearance of the card. Accepted variants include
base or narrow. This value defaults to base.
lightning:carousel (Beta)
A collection of images that are displayed one at a time.
A lightning:carousel component displays a series of images in a single container. Only one image is displayed at a time, and
you can select other images by clicking the carousel indicators. The carousel auto scrolls by default, and auto scrolling can be disabled
by setting disableAutoScroll="true".
This component inherits styling from carousel in the Lightning Design System.
To implement additional styling for this component, use the Lightning Design System helper classes.
This example creates a basic carousel with three images.
<aura:component>
<lightning:carousel>
<lightning:carouselImage
src = "path/to/carousel-01.jpg"
header = "First card"
description = "First card description"
alternativeText = "This is a card"></lightning:carouselImage>
<lightning:carouselImage
src = "path/to/carousel-02.jpg"
header = "Second card"
description = "Second card description"
alternativeText = "This is a card">
</lightning:carouselImage>
<lightning:carouselImage
src = "path/to/carousel-03.jpg"
header = "Third card"
description = "Third card description"
alternativeText = "This is a card">
</lightning:carouselImage>
</lightning:carousel>
</aura:component>
Usage Considerations
The first image in the lightning:carousel is displayed by default. To use an image in your org, upload it as a static resource in
the Static Resources setup page. Use the {!$Resource.image}" syntax in your src attribute, where image is the name you
provided in the Name field on the setup page. If the image path is invalid or the image does not load because the user is offline or
another reason, the description and alternative text are shown in place of the image.
461
Reference lightning:checkboxGroup
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
disableAutoRefresh Boolean Specifies whether the carousel should stop looping from the beginning
after the last item is displayed. The default value is false.
disableAutoScroll Boolean Specifies whether auto scroll is disabled. The default value is false.
scrollDuration Integer The auto scroll duration. The default is 5 seconds, after that the next
image is displayed.
title String Displays tooltip text when the mouse moves over the element.
lightning:checkboxGroup
A checkbox group that enables selection of single or multiple options. This component requires API version 41.0 and later.
A lightning:checkboxGroup component represents a checkbox group that enables selection of single or multiple options.
If the required attribute is set to true, at least one checkbox must be selected. When a user interacts with the checkbox group
and doesn't make a selection, an error message is displayed. You can provide a custom error message using the
messageWhenValueMissing attribute.
If the disabled attribute is set to true, checkbox selections can't be changed.
This component inherits styling from Checkbox in the Lightning Design System.
This example creates a checkbox group with two options and option1 is selected by default. At least one checkbox must be selected
as the required attribute is true.
<aura:component>
<aura:attribute name="options" type="List" default="[
{'label': 'Ross', 'value': 'option1'},
{'label': 'Rachel', 'value': 'option2'},
]"/>
<aura:attribute name="value" type="List" default="option1"/>
<lightning:checkboxGroup
aura:id="mygroup"
name="checkboxGroup"
label="Checkbox Group"
options="{! v.options }"
value="{! v.value }"
onchange="{! c.handleChange }"
required="true" />
</aura:component>
462
Reference lightning:checkboxGroup
You can check which values are selected by using cmp.find("mygroup").get("v.value"). To retrieve the values when a
checkbox is selected or deselected, use the onchange event handler and call event.getParam("value").
({
handleChange: function (cmp, event) {
var changeValue = event.getParam("value");
alert(changeValue);
}
});
Usage Considerations
lightning:checkboxGroup is useful for grouping a set of checkboxes. If you have a single checkbox, use lightning:input
type="checkbox" instead.
Accessibility
The checkbox group is nested in a fieldset element that contains a legend element. The legend contains the label value.
The fieldset element enables grouping of related checkboxes to facilitate tabbing navigation and speech navigation for accessibility
purposes. Similarly, the legend element improves accessibility by enabling a caption to be assigned to the fieldset.
Methods
This component supports the following method.
checkValidity(): Returns the valid property value (Boolean) on the ValidityState object to indicate whether the checkbox group
has any validity errors.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
value String[] The list of selected checkboxes. Each array entry contains the value of a Yes
selected checkbox. The value of each checkbox is set in the options
attribute.
messageWhenValueMissing String Optional message displayed when no checkbox is selected and the
required attribute is set to true.
required Boolean Set to true if at least one checkbox must be selected. This value defaults
to false.
disabled Boolean Set to true if the checkbox group is disabled. Checkbox selections can't
be changed for a disabled checkbox group. This value defaults to false.
463
Reference lightning:clickToDial
onfocus Action The action triggered when the checkbox group receives focus.
lightning:clickToDial
Renders a formatted phone number as click-to-dial enabled or disabled for Open CTI and Voice. This component requires API version
41.0 and later.
A lightning:clickToDial component respects any existing click-to-dial commands for computer-telephony integrations (CTI)
with Salesforce, such as Open CTI and Voice.
To dial phone numbers in the component, you must first enable the phone system. After the phone system is enabled, when a user
clicks on a phone number the component notifies the phone system that the number was clicked. Then, the component passes along
any information that's required by the phone system to make an outbound call.
Here's an example of how you can use a lightning:clickToDial component. The first phone number doesn't have a recordId
or any parameters. The second phone number has a recordId. The third phone number has a recordId and parameters.
<aura:component>
<lightning:clickToDial value="14155555551"/>
<lightning:clickToDial value="14155555552" recordId="5003000000D9duF"/>
<lightning:clickToDial value="14155555553" recordId="5003000000D8cuI"
params="accountSid=xxx, sourceId=xxx, apiVersion=123"/>
</aura:component>
464
Reference lightning:combobox
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
recordId String The Salesforce record Id that's associated with the phone number.
lightning:combobox
A widget that provides an input field that is readonly, accompanied with a dropdown list of selectable options.
lightning:combobox is an input element that enables single selection from a list of options. The result of the selection is displayed
as the value of the input.
This component inherits styling from combobox in the Lightning Design System.
This example creates a list of options during init with a default selection.
<aura:component>
<aura:attribute name="statusOptions" type="List" default="[]"/>
<aura:handler name="init" value="{! this }" action="{! c.loadOptions }"/>
<lightning:combobox aura:id="selectItem" name="status" label="Status"
placeholder="Choose Status"
value="new"
onchange="{!c.handleOptionSelected}"
options="{!v.statusOptions}"/>
</aura:component>
In your client-side controller, define an array of options and assign it to the statusOptions attribute. Each option corresponds to
a list item on the dropdown list.
({
loadOptions: function (component, event, helper) {
var options = [
{ value: "new", label: "New" },
{ value: "in-progress", label: "In Progress" },
{ value: "finished", label: "Finished" }
];
component.set("v.statusOptions", options);
},
handleChange: function (cmp, event) {
// Get the string of the "value" attribute on the selected option
var selectedOptionValue = event.getParam("value");
alert("Option selected with value: '" + selectedOptionValue + "'");
465
Reference lightning:combobox
}
})
Selecting an option triggers the onchange event, which calls the handleChange client-side controller. To check which option
has been clicked, use event.getParam("value"). Calling cmp.find("mycombobox").get("v.value"); returns
the currently selected option.
Usage Considerations
Special characters like " must be escaped. For example, you want to display "New".
var options = [
{ value: "\"new\"", label: "\"New\"" },
{ value: "expired", label: "Expired" }
];
When using single quotes in your value, escape the quote with a double slash instead of a single slash.
Input Validation
Client-side input validation is available for this component. You can make the the selection required by setting required="true".
An error message is automatically displayed when an item is not selected and required="true".
To check the validity states of an input, use the validity attribute, which is based on the ValidityState object. You can access
the validity states in your client-side controller. This validity attribute returns an object with boolean properties. See
lightning:input for more information.
You can override the default message by providing your own value for messageWhenValueMissing.
Accessibility
You must provide a text label for accessibility to make the information available to assistive technology. The label attribute creates an
HTML label element for your input component. To hide a label from view and make it available to assistive technology, use the
label-hidden variant.
Methods
This component supports the following methods.
focus(): Sets focus on the element.
checkValidity(): Returns the valid property value (Boolean) on the ValidityState object to indicate whether the combobox has
any validity errors.
setCustomValidity(message): Sets a custom error message to be displayed when the combobox value is submitted.
• message (String): The string that describes the error. If message is an empty string, the error message is reset.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
variant String The variant changes the appearance of an input field. Accepted variants
include standard and label-hidden. This value defaults to standard.
466
Reference lightning:container
readonly Boolean Specifies that an input field is read-only. This value defaults to false.
required Boolean Specifies that an input field must be filled out before submitting the form.
This value defaults to false.
validity Object Represents the validity states that an element can be in, with respect to
constraint validation.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
onfocus Action The action triggered when the element receives focus.
onblur Action The action triggered when the element releases focus.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
options Object[] A list of options that are available for selection. Each option has the Yes
following attributes: class, selected, label, and value.
placeholder String Text that is displayed before an option is selected, to prompt the user to
select an option. The default is "Select an Option".
dropdownAlignment String Determines the alignment of the drop-down relative to the input.
Available values are left, center, right, bottom-left, bottom-center,
bottom-right. The default is left.
messageWhenValueMissing String Error message to be displayed when the value is missing and input is
required.
lightning:container
Used to contain content that uses a third-party javascript framework such as Angular or React.
The lightning:container component allows you to host content developed with a third-party framework within a Lightning
component. The content is uploaded as a static resource, and hosted in an iFrame. The lightning:container component can
be used for single-page applications only.
This is a simple example of lightning:container, which loads an app that's uploaded as a static resource named myReactApp.
<aura:component access="global" implements="flexipage:availableForAllPageTypes">
<lightning:container src="{!$Resource.myReactApp + '/index.html'}"/>
</aura:component>
467
Reference lightning:container
To pass a value of an attribute to the container via its URL, define the attribute in your component and pass it in using the src attribute.
<aura:component>
<aura:attribute access="global" name="greeting" type="String" required="true"
default="Hello"/>
<div>
<lightning:container src="{!$Resource.myReactApp + '/index.html?greeting=' +
v.greeting}"/>
</div>
</aura:component>
You can also implement communication to and from the framed application, allowing it to interact with Salesforce. Use the message()
function in the Javascript controller to send messages to the application, and specify a method for handling messages with the component’s
onmessage attribute.
This example defines attributes for a message to send from the container to the Lightning component and for a message received.
<aura:component access="global" implements="flexipage:availableForAllPageTypes" >
<aura:attribute name="messageToSend" type="String" default=""/>
<aura:attribute name="messageReceived" type="String" default=""/>
<div>
<lightning:input name="messageToSend" value="{!v.messageToSend}" label="Message
to send to Angular app: "/>
<lightning:button label="Send" onclick="{!c.sendMessage}"/>
<lightning:textarea name="messageReceived" value="{!v.messageReceived}"
label="Message received from Angular app: "/>
<lightning:container aura:id="AngularApp"
src="{!$Resource.SendReceiveMessages + '/index.html'}"
onmessage="{!c.handleMessage}"/>
</div>
</aura:component>
The client-side controller uses the message() function to send a simple JSON payload to an AngularJS app.
({
sendMessage : function(component, event, helper) {
var msg = {
name: "General",
value: component.get("v.messageToSend")
};
component.find("AngularApp").message(msg);
},
handleMessage: function(component, message, helper) {
var payload = message.payload;
var name = payload.name;
if (name === "General") {
var value = payload.value;
component.set("v.messageReceived", value);
}
else if (name === "Foo") {
// A different response
}
},
})
468
Reference lightning:datatable
Because you define the controller-side message handling yourself, you can use it to handle any kind of message payload. You can, for
example, send just a text string or return a structured JSON response.
Usage Considerations
When specifying the src of the container, don’t specify a hostname. Instead, use $Resource with dot notation to reference your
application, uploaded as a static resource.
For more information, see the Lightning Components Developer Guide.
Accessibility
Use the alternativeText attribute to provide assistive text for the lightning:container.
Methods
The component supports the following method.
message(): Sends a user-defined message from the component to the iFrame content.
Attributes
Attribute Name Attribute Type Description Required?
alternativeText String Used for alternative text in accessibility scenarios.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
onerror Action The client-side controller action to run when an error occurs when
sending a message to the contained app.
onmessage Action The client-side controller action to run when a message is received from
the contained content.
src String The resource name, landing page and query params in url format. Yes
Navigation is supported only for the single page identified.
lightning:datatable
A table that displays columns of data, formatted according to type. This component requires API version 41.0 and later.
A lightning:datatable component displays tabular data where each column can be displayed based on the data type. For
example, an email address is displayed as a hyperlink with the mailto: URL scheme by specifying the email type. The default type
is text.
This component inherits styling from data tables in the Lightning Design System.
lightning:datatable is not supported on mobile devices. Inline editing is currently not supported. Supported features include:
• Displaying and formatting of columns with appropriate data types
• Infinite scrolling of rows
• Header-level actions
• Row-level actions
• Resizing of columns
469
Reference lightning:datatable
• Selecting of rows
• Sorting of columns by ascending and descending order
• Text wrapping and clipping
Tables can be populated during initialization using the data, columns, and keyField attributes. This example creates a table
with 6 columns, where the first column displays a checkbox for row selection. The table data is loaded using the init handler. Selecting
the checkbox enables you to select the entire row of data and triggers the onrowselection event handler.
<aura:component>
<aura:attribute name="mydata" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<lightning:datatable data="{! v.mydata }"
columns="{! v.mycolumns }"
keyField="id"
onrowselection="{! c.getSelectedName }"/>
</aura:component>
Here's the client-side controller that creates selectable rows and the columns object to their corresponding column data. The
Confidence column displays percentages with an icon that denotes the increasing or decreasing confidence trend.
({
init: function (cmp, event, helper) {
cmp.set('v.mycolumns', [
{label: 'Opportunity name', fieldName: 'opportunityName', type: 'text'},
{label: 'Confidence', fieldName: 'confidence', type: 'percent',
cellAttributes:
{ iconName: { fieldName: 'trendIcon' }, iconPosition: 'right' }},
{label: 'Amount', fieldName: 'amount', type: 'currency', typeAttributes:
{ currencyCode: 'EUR'}},
{label: 'Contact Email', fieldName: 'contact', type: 'email'},
{label: 'Contact Phone', fieldName: 'phone', type: 'phone'}
]);
cmp.set('v.mydata', [{
id: 'a',
opportunityName: 'Cloudhub',
confidence: 0.2,
amount: 25000,
contact: 'jrogers@cloudhub.com',
phone: '2352235235',
trendIcon: 'utility:down'
},
{
id: 'b',
opportunityName: 'Quip',
confidence: 0.78,
amount: 740000,
contact: 'quipy@quip.com',
phone: '2352235235',
trendIcon: 'utility:up'
}]);
},
getSelectedName: function (cmp, event) {
var selectedRows = event.getParam('selectedRows');
// Display that fieldName of the selected rows
470
Reference lightning:datatable
In the previous example, the first row of data displays a checkbox in the first column, and columns with the following data: Cloudhub,
20%, $25,000.00, jrogers@cloudhub.com, and (235) 223-5235. The last two columns are displayed as hyperlinks to represent an email
address and telephone number.
Retrieving Data Using an Apex Controller
Let's say you want to display data on the Contact object. Create an Apex controller that queries the fields you want to display.
public with sharing class ContactController {
@AuraEnabled
public static List<Contact> getContacts() {
List<Contact> contacts =
[SELECT Id, Name, Phone, Email FROM Contact];
//Add isAccessible() check
return contacts;
}
}
Wire this up to your component via the controller attribute. The markup looks similar to the previous example.
<aura:component controller="ContactController">
<aura:attribute name="mydata" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<lightning:datatable data="{! v.mydata }"
columns="{! v.mycolumns }"
keyField="Id"
hideCheckboxColumn="true"/>
</aura:component>
Initialize the column data by mapping the fieldName property to the API name of the field.
({
init: function (cmp, event, helper) {
cmp.set('v.mycolumns', [
{label: 'Contact Name', fieldName: 'Name', type: 'text'},
{label: 'Phone', fieldName: 'Phone', type: 'phone'},
{label: 'Email', fieldName: 'Email', type: 'email'}
]);
helper.getData(cmp);
}
})
471
Reference lightning:datatable
cmp.set('v.mydata', response.getReturnValue());
} else if (state === "ERROR") {
var errors = response.getError();
console.error(errors);
}
}));
$A.enqueueAction(action);
}
})
fieldName string Required. The name that binds the columns properties to the
associated data. Each columns property must correspond to an
item in the data array.
type string Required. The data type to be used for data formatting. For more
information, see Formatting with Data Types.
initialWidth integer The 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.
typeAttributes object Provides custom formatting with component attributes for the data
type. For example, currencyCode for the currency type. For
more information, see Formatting with Data Types.
sortable boolean Specifies whether sorting by columns is enabled. The default is false.
actions object Appends a dropdown menu of actions to a column. You must pass
in a list of label-name pairs.
iconName string The 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.
472
Reference lightning:datatable
button Displays a button using disabled, iconName, iconPosition, label, name, title, variant
lightning:button
date Displays a date and time based on day, era, hour, hour12, minute, month, second, timeZone,
the locale using timeZoneName, weekday, year
lightning:formattedDateTime
To customize the formatting based on the data type, pass in the attributes for the corresponding base Lightning component. For example,
pass in a custom currencyCode value to override the default currency code.
columns: [
{label: 'Amount', fieldName: 'amount', type: 'currency', typeAttributes: { currencyCode:
'EUR' }}
// other column data
]
When using currency or date and time types, the default user locale is used when no locale formatting is provided.
For more information on attributes, see the corresponding component documentation.
Appending an Icon to Column Data
To append an icon to your data output, use cellAttributes and pass in these attributes.
473
Reference lightning:datatable
Attribute Description
iconName Required. The Lightning Design System name of the icon, for example,
utility:down.
iconLabel The label for the icon to be displayed on the right of the icon.
iconPosition The position of the icon relative to the data. Valid options include left
and right. This value defaults to left.
474
Reference lightning:datatable
The onloadmore event handler retrieves more data when you scroll to the bottom of the table until there are no more data to load.
To display a spinner while data is being loaded, set the isLoading attribute to true.
({
loadMoreData: function (cmp, event, helper) {
//Display a spinner to signal that data is being loaded
event.getSource().set("v.isLoading", true);
//Display "Loading" when more data is being loaded
cmp.set('v.loadMoreStatus', 'Loading');
helper.fetchData(cmp, cmp.get('v.rowsToLoad'))
.then($A.getCallback(function (data) {
if (cmp.get('v.data').length >= cmp.get('v.totalNumberOfRows')) {
cmp.set('v.enableInfiniteLoading', false);
cmp.set('v.loadMoreStatus', 'No more data to load');
} else {
var currentData = cmp.get('v.data');
//Appends new data to the end of the table
var newData = currentData.concat(data);
cmp.set('v.data', newData);
cmp.set('v.loadMoreStatus', '');
}
event.getSource().set("v.isLoading", false);
}));
}
})
While this example uses a fixed number to denote the total number of rows, you can also use the SOQL SELECT syntax with the COUNT()
function to return the number of rows in the object in your Apex controller. Then, set the result on the totalNumberOfRows
attribute during initialization.
SELECT COUNT(Id) FROM Contact
Attribute Description
label Required. The label that's displayed for the action.
name Required. The name of the action, which identifies the selected action.
checked Specifies whether a check mark is shown to the left of the action label. If
true, a check mark is shown to the left of the menu item. If false, a check
mark is not shown but there is space to accommodate one.
disabled Specifies whether the action can be selected. If true, the action item is shown
as disabled. This value defaults to false.
iconName The name of the icon to be displayed to the right of the action item.
475
Reference lightning:datatable
For example, you want to create a filter that displays only rows where the Publishing State column matches either the Published or
Unpublished state.
Bind the header actions to the actions column property, which can be done during initialization.
({
init: function (cmp, event, helper) {
var headerActions = [
{
label: 'All',
checked: true,
name:'all'
},
{
label: 'Published',
checked: false,
name:'show_published'
},
{
label: 'Unpublished',
checked: false,
name:'show_unpublished'
},
];
cmp.set('v.mycolumns', [
// other column data
{
label: 'Publishing State',
fieldName: 'published',
type: 'text',
actions: headerActions
}
]);
},
handleHeaderAction: function (cmp, event, helper) {
// Retrieves the name of the selected filter
var actionName = event.getParam('action').name;
// Retrieves the current column definition
// based on the selected filter
var colDef = event.getParam('columnDefinition');
var columns = cmp.get('v.mycolumns');
var activeFilter = cmp.get('v.activeFilter');
if (actionName !== activeFilter) {
var idx = columns.indexOf(colDef);
476
Reference lightning:datatable
Finally, display the rows to match the selected filter, which is performed by helper.updateBooks(cmp).
({
updateBooks: function (cmp) {
var rows = cmp.get('v.rawData');
var activeFilter = cmp.get('v.activeFilter');
var filteredRows = rows;
if (activeFilter !== 'all') {
filteredRows = rows.filter(function (row) {
return (activeFilter === 'show_published' ||
(activeFilter === 'show_unpublished');
});
}
cmp.set('v.mydata', filteredRows);
}
})
Attribute Description
label Required. The label that's displayed for the action.
name Required. The name of the action, which identifies the selected action.
disabled Specifies whether the action can be selected. If true, the action item is shown
as disabled. This value defaults to false.
iconName The name of the icon to be displayed to the right of the action item.
<lightning:datatable
columns="{! v.mycolumns }"
data="{! v.mydata }"
keyField="id"
onrowaction="{! c.handleRowAction }"/>
477
Reference lightning:datatable
You must provide a list of actions to the columns data, which can be done during initialization. This client-side controller initializes the
actions column and handles the actions on each row, displaying the row details and deleting the row when the action is clicked.
({
init: function (cmp, event, helper) {
var actions = [
{ label: 'Show details', name: 'show_details' },
{ label: 'Delete', name: 'delete' }
];
cmp.set('v.mycolumns', [
// Other column data here
{ type: 'action', typeAttributes: { rowActions: actions } }
]);
},
handleRowAction: function (cmp, event, helper) {
var action = event.getParam('action');
var row = event.getParam('row');
switch (action.name) {
case 'show_details':
alert('Showing Details: ' + JSON.stringify(row));
break;
case 'delete':
var rows = cmp.get('v.mydata');
var rowIndex = rows.indexOf(row);
rows.splice(rowIndex, 1);
cmp.set('v.mydata', rows);
break;
}
})
To delete the record in the database, create an Apex controller with the delete operation.
@AuraEnabled
public static Contact deleteContact(Contact contact) {
delete contact;
return contact;
}
The code in the case 'delete' block can be moved to a helper function and replaced with:
helper.deleteRow(cmp, row);
Your helper looks like this. It calls the deleteContact Apex controller and passes in the row of data to be deleted. If the delete is
successful, the row of data in the component is removed from view.
({
deleteRow: function(cmp, row) {
var action = cmp.get("c.deleteContact");
action.setParams({
"contact":row
});
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var rows = cmp.get('v.mydata');
var rowIndex = rows.indexOf(row);
478
Reference lightning:datatable
rows.splice(rowIndex, 1);
cmp.set('v.mydata', rows);
}
else if (state === "ERROR") {
// handle error
}
});
$A.enqueueAction(action);
}
})
You can also update a row of data by using the Apex controller with the upsert operation. Alternatively, you can display the record
edit page by firing the force:editRecord event. To associate the record edit page to the contacts, pass in "recordId":
row.Id.
Creating Dynamic Row-Level Actions
Dynamic actions are created based on the content of each row. When you click the dropdown menu, an asynchronous call is made to
determine which actions to display for the particular row. The logic that determines which action to display can be created on initialization.
In this example, the action and its label is evaluated when the dropdown menu is activated. Assume that we have an active column
that displays the status of a contact (Active or Inactive), which determines which action to display (Deactivate or Activate).
({
init: function (cmp, event, helper) {
var actions = helper.getRowActions.bind(this, cmp);
cmp.set('v.mycolumns', [
// Other column data here
{ label: 'State', fieldName: 'active', type: 'text' },
{ type: 'action', typeAttributes: { rowActions: actions } }
]);
// Fetch or set your data
},
handleRowAction: function (cmp, event, helper) {
var action = event.getParam('action');
var row = event.getParam('row');
switch (action.name) {
case 'activate':
helper.activateContact(cmp, row)
break;
case 'deactivate':
helper.deactivateContact(cmp, row)
break;
}
}
})
The helper evaluates which label (Activate or Deactivate) to display and updates the active column with the right value.
({
getRowActions: function (cmp, row, doneCallback) {
var actions = [];
if (row['isActive']) {
actions.push({
'label': 'Deactivate',
'iconName': 'utility:block_visitor',
'name': 'deactivate'
479
Reference lightning:datatable
});
} else {
actions.push({
'label': 'Activate',
'iconName': 'utility:adduser',
'name': 'activate'
});
}
// simulate a trip to the server
setTimeout($A.getCallback(function () {
doneCallback(actions);
}), 200);
},
activateContact: function (cmp, row) {
var rows = cmp.get('v.data');
var rowIndex = rows.indexOf(row);
rows[rowIndex]['isActive'] = true;
rows[rowIndex]['active'] = 'Active';
cmp.set('v.data', rows);
},
deactivateContact: function (cmp, row) {
var rows = cmp.get('v.data');
var rowIndex = rows.indexOf(row);
rows[rowIndex]['isActive'] = false;
rows[rowIndex]['active'] = 'Inactive';
cmp.set('v.data', rows);
}
})
The previous example illustrates how to create and handle dynamic actions on the client-side only. You can make server calls and persist
your record data changes via an Apex controller.
Resizing Tables and Columns
The width and height of the datatable is determined by the container element. A scroller is appended to the table body if there are more
rows to display. For example, you can restrict the height to 300px by applying CSS styling to the container element.
<div style="height: 300px;">
<!-- lightning:datatable goes here -->
</div>
By default, columns are resizable. Users can click and drag the width to a minimum of 50px and a maximum of 1000px, unless the default
values are changed. Columns can be resized by default. You can disable column resizing by setting resizeColumnDisabled to
true. To change the minimum and maximum width column, use the minColumnWidth and maxColumnWidth attributes.
Selecting Rows Programmatically
The selectedRows attribute enables programmatic selection of rows, which is useful when you want to preselect rows.
<aura:component>
<!-- Attributes and init handler here -->
<lightning:datatable
columns="{! v.columns }"
data="{! v.data }"
keyField="id"
selectedRows="{! v.selectedRows }" />
480
Reference lightning:datatable
If maxRowSelection is set to a value less than the number of selected rows, only the specified number of rows will be selected.
For example, if you set maxRowSelection to 2 and pass in ['a', 'b', 'c'] to selectedRows, only rows a and b will
be selected.
Sorting Data By Column
To enable sorting of row data by a column label, set sortable to true for the column on which you want to enable sorting. Set
sortedBy to match the fieldName property on the column. Clicking a column header sorts rows by ascending order unless the
defaultSortDirection is changed, and clicking it subsequently reverses the order. Handle the onsort event handler to
update the table with the new column index and sort direction.
Here's an example of the client-side controller that's called by the onsort event handler.
({
// Client-side controller called by the onsort event handler
updateColumnSorting: function (cmp, event, helper) {
var fieldName = event.getParam('fieldName');
var sortDirection = event.getParam('sortDirection');
// assign the latest attribute with the sorted column fieldName and sorted direction
cmp.set("v.sortedBy", fieldName);
cmp.set("v.sortedDirection", sortDirection);
helper.sortData(cmp, fieldName, sortDirection);
}
})
481
Reference lightning:datatable
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
columns List Array of the columns object that's used to define the data types. Required
properties include 'label', 'dataKey', and 'type'. The default type is 'text'.
482
Reference lightning:datatable
defaultSortDirection String Specifies the default sorting direction on an unsorted column. Valid
options include 'asc' and 'desc'. The default is 'asc' for sorting in ascending
order.
hideCheckboxColumn Boolean Hides or displays the checkbox column for row selection. To hide the
checkbox column, set hideCheckboxColumn to true. The default is false.
isLoading Boolean Specifies whether more data is being loaded and displays a spinner if so.
The default is false.
keyField String Required for better performance. Associates each row with a unique ID. Yes
loadMoreOffset Integer Determines when to trigger infinite loading based on how many pixels
the table's scroll position is from the bottom of the table. The default is
20.
maxColumnWidth Integer The maximum width for all columns. The default is 1000px.
maxRowSelection Integer The maximum number of rows that can be selected. Checkboxes are
used for selection by default, and radio buttons are used when
maxRowSelection is 1.
minColumnWidth Integer The minimum width for all columns. The default is 50px.
onheaderaction Action The action triggered when a header action is clicked. By default, it also
closes the header actions menu.
onloadmore Action The action triggered when infinite loading loads more data.
onresize Action The action triggered when the table renders columns the first time and
every time its resized an specific column.
onrowaction Action The action triggered when a row action is clicked. By default, it also closes
the row actions menu.
resizeColumnDisabled Boolean Specifies whether column resizing is disabled. The default is false.
resizeStep Integer The width to resize the column when user press left or right arrow. The
default is 10px.
rowNumberOffset Integer Determines where to start counting the row number. The default is 0.
selectedRows List Enables programmatic row selection with a list of keyField values.
showRowNumberColumn Boolean Shows or hides the row number column. Set to true to show the row
number column. The default is false.
483
Reference lightning:dualListbox
sortedDirection String Specifies the sorting direction. Sort the data using the onsort event
handler. Valid options include 'asc' and 'desc'.
title String Displays tooltip text when the mouse moves over the element.
lightning:dualListbox
A widget that provides an input listbox, accompanied with a listbox of selectable options. Order of selected options is saved. This
component requires API version 41.0 and later.
A lightning:dualListbox component represents two side-by-side list boxes. Select one or more options in the list on the left.
Move selected options to the list on the right. The order of the selected options is maintained and you can reorder options.
This component inherits styling from Dueling Picklist in the Lightning Design System.
Here's an example that creates a simple dual list box with 8 options. Options 7, 2 and 3 are selected under the "Second Category" list
box. Options 2 and 7 are required options.
<aura:component>
<aura:attribute name="listOptions" type="List" default="[]"/>
<aura:attribute name="defaultOptions" type="List" default="[]"/>
<aura:attribute name="requiredOptions" type="List" default="[]"/>
<aura:handler name="init" value="{! this }" action="{! c.initialize }"/>
<lightning:dualListbox aura:id="selectOptions" name="Select Options" label= "Select
Options"
sourceLabel="Available Options"
selectedLabel="Selected Options"
options="{! v.listOptions }"
value="{! v.defaultOptions }"
requiredOptions="{! v.requiredOptions }"
onchange="{! c.handleChange }"/>
</aura:component>
Here's the client-side controller that loads the options and handles value changes.
484
Reference lightning:dualListbox
To specify the number of options users can select, use the min and max attributes. For example, if you set min to 3 and max to 8,
users must select at least 3 options and at most 8 options.
Usage Considerations
To retrieve the selected values, use the onchange handler.
({
onChange: function (cmp, event) {
// Retrieve an array of the selected options
var selectedOptionValue = event.getParam("value");
}
})
The onchange handler is triggered when you click the left and right buttons to move options from one list to another or when you
change the order of options in the selected options list.
Accessibility
Use the following keyboard shortcuts to work with dual list boxes.
• Click - Select a single option.
• Cmd+Click - Select multiple options or deselect selected options.
• Shift+Click - Select all options between the current and last clicked option.
When focus is on options:
• Up Arrow - Move selection to previous option.
• Down Arrow - Move selection to next option.
• Cmd/Ctrl+Up Arrow - Move focus to previous option.
• Cmd/Ctrl+Down Arrow - Move focus to next option.
• Ctrl+Space - Toggle selection of focused option.
• Cmd/Ctrl+Right Arrow - Move selected options to right list box.
• Cmd/Ctrl+Left Arrow - Move selected options to left list box.
• Tab - Move focus to next element.
When focus is on a button:
• Enter - Perform the operation associated with that button.
Methods
This component supports the following methods.
485
Reference lightning:dualListbox
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
variant String The variant changes the appearance of an input field. Accepted variants
include standard and label-hidden. This value defaults to standard.
disabled Boolean Specifies that an input element should be disabled. This value defaults
to false.
readonly Boolean Specifies that an input field is read-only. This value defaults to false.
required Boolean Specifies that an input field must be filled out before submitting the form.
This value defaults to false.
validity Object Represents the validity states that an element can be in, with respect to
constraint validation.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
onfocus Action The action triggered when the element receives focus.
onblur Action The action triggered when the element releases focus.
options Object[] A list of options that are available for selection. Each option has the Yes
following attributes: label and value.
requiredOptions List A list of required options that cannot be removed from selected options
list box. This list is populated with values from options attribute.
486
Reference lightning:dynamicIcon
min Integer Minimum number of options required in the selected options list box.
max Integer Maximum number of options required in the selected options list box.
lightning:dynamicIcon
Represents various animated icons with different states. This component requires API version 41.0 and later.
A lightning:dynamicIcon component visually displays an event that's in progress, such as a graph that's loading.
This component inherits styling from dynamic icons in the Lightning Design System.
Here’s an example of an ellie icon with alternative text.
<aura:component>
<lightning:dynamicIcon type="ellie" alternativeText="Your calculation is running."/>
</aura:component>
Usage Considerations
The following options are available.
• Use the type="ellie" attribute to show a pulsing blue circle, which pulses and stops after one animation cycle. This icon is
great for field calculations or a process that’s running in the background.
• Use the type="eq" attribute to show an animated graph with three bars that rise and fall randomly. This icon is great for a graph
that’s refreshing.
• Use the type="score" attribute to show a green filled circle or a red unfilled circle. This icon is great for showing positive and
negative indicators.
• Use the type="strength" attribute to show three animated horizontal circles that are colored green or red. This icon is great
for Einstein calculations or indicating password strengths.
• Use the type="trend" attribute to show animated arrows that point up, down, or straight. This icon is great for showing
movement of a value from one range to another, like a forecast score.
• Use the type="waffle" attribute to show a square made up of a 3x3 grid of circles. This icon animates on hover. This icon is
great for app-related items, like the App Launcher in Lightning Experience.
Accessibility
Optionally, you can use the alternativeText attribute to describe the dynamicIcon.
Sometimes a dynamicIcon is decorative and doesn’t need a description. However, on smaller screens and windows the
dynamicIcon can also be informational. In this case, include alternativeText. If you don’t include alternativeText,
check smaller screens and windows to ensure that the dynamicIcon is only decorative on all formats.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
487
Reference lightning:fileCard
title String Displays tooltip text when the mouse moves over the element.
type String The Lightning Design System name of the dynamicIcon. Valid values are: Yes
ellie, eq, score, strength, trend, and waffle.
option String The option attribute changes the appearance of the dynamicIcon. The
options available depend on the type attribute. For eq: play (default) or
stop For score: positive (default) or negative For strength: -3, -2, -1, 0
(default), 1, 2, 3 For trend: neutral (default), up, or down
alternativeText String The alternative text used to describe the dynamicIcon. This text should
describe what’s happening. For example, 'Graph is refreshing',
not what the icon looks like, 'Graph'.
lightning:fileCard
Displays a preview of an uploaded file available in Salesforce CRM Content or Salesforce Files.
A lightning:fileCard component displays a preview of a file. On desktops, clicking the file preview opens the SVG file preview
player, enabling you to preview images, documents, and other files in the browser. The file preview player provides quick access to file
actions, such as upload, delete, download, and share. On mobile devices, clicking the file preview downloads the file. If a title is available,
it's displayed below the file preview in the caption area. The file type determines the icon used on the file preview and caption area.
This component inherits styling from files in the Lightning Design System.
Here's an example of a file preview. The fileId value must be a valid 15 character ContentDocument ID.
<aura:component>
<lightning:fileCard fileId="069XXXXXXXXXXXX"/>
</aura:component>
Usage Considerations
Opening the file preview player is supported in Lightning Experience, the Salesforce mobile web, and Lightning communities.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
488
Reference lightning:fileUpload
lightning:fileUpload
A file uploader for uploading and attaching files to records.
A lightning:fileUpload component provides an easy and integrated way for users to upload multiple files. The file uploader
includes drag-and-drop functionality and filtering by file types.
This component inherits styling from file selector in the Lightning Design System.
File uploads are always associated to a record, hence the recordId attribute is required. Uploaded files are available in Files Home
under the Owned by Me filter and on the record's Attachments related list on the record detail page. Although all file formats supported
by Salesforce are allowed, you can restrict the file formats using the accept attribute.
This example creates a file uploader that allows multiple PDF and PNG files to be uploaded. Change the recordId value to your own.
<aura:component>
<aura:attribute name="myRecordId" type="String" description="Record to which the files
should be attached" />
<lightning:fileUpload label="Attach receipt"
name="fileUploader"
multiple="true"
accept=".pdf, .png"
recordId="{!v.myRecordId}"
onuploadfinished="{!c.handleUploadFinished}" />
</aura:component>
You must handle the onuploadfinished event, which is fired when the upload is finished.
({
handleUploadFinished: function (cmp, event) {
// Get the list of uploaded files
var uploadedFiles = event.getParam("files");
alert("Files uploaded : " + uploadedFiles.length);
}
})
event.getParam("files") returns a list of uploaded files with the properties name and documentId.
• name: The file name in the format filename.extension, for example, account.jpg.
• documentId: The ContentDocument Id in the format 069XXXXXXXXXXXX.
File Upload Limits
By default, you can upload up to 10 files simultaneously unless Salesforce has changed that limit. The org limit for the number of files
simultaneously uploaded is a maximum of 25 files and a minimum of one file. The maximum file size you can upload is 2 GB. In
Communities, the file size limits and types allowed follow the settings determined by community file moderation.
Usage Considerations
This component isn’t supported in Lightning Out or standalone apps, and displays as a disabled input. Also, if the Don't allow
HTML uploads as attachments or document records security setting is enabled for your organization, the file
uploader can’t be used to upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg.
For more information, see Upload and Share Files in Salesforce Help.
489
Reference lightning:flexipageRegionInfo
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
label String The text label for the file uploader. Yes
recordId String The record Id of the record that the uploaded file is associated to. Yes
multiple Boolean Specifies whether a user can upload more than one file simultanesouly.
This value defaults to false.
accept List Comma-separated list of file extensions that can be uploaded in the
format .ext, such as .pdf, .jpg, or .png
onuploadfinished Action The action triggered when files have finished uploading.
lightning:flexipageRegionInfo
Provides Lightning page region information to the component that contains it.
The lightning:flexipageRegionInfo component provides Lightning page region information to the component that
contains it. It passes the width of the region that the component is dropped into in the Lightning App Builder. For more information,
see Make Your Lightning Page Components Width Aware With lightning:flexipageRegionInfo.
<aura:component implements="flexipage:availableForAllPageTypes">
<aura:attribute name="width" type="String" description=" width of parent region"/>
<lightning:flexipageRegionInfo width="{!v.width}"/>
<div id="MyCustomComponent" class="{! v.width}">
<!-- Your custom component here -->
</div>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
width String The width of the region that the component resides in.
490
Reference lightning:flow
lightning:flow
Represents a flow interview in Lightning runtime. This component requires API version 41.0 and later.
A lightning:flow component represents a flow interview in Lightning runtime.
Specify which flow to render with the name attribute. If it’s appropriate for your flow, initialize the flow’s input variables with the
inputVariables attribute.
This example renders the Survey Customers flow (from the Create a Satisfaction Survey Trailhead project).
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.init}"/>
<lightning:flow aura:id="flowData"/>
</aura:component>
Usage Considerations
The referenced flow must be active.
The onstatuschange action returns these parameters.
helpText String The help text for the current screen. Available in API version 42.0 and
later.
guid String The interview’s GUID. Available in API version 42.0 and later.
outputVariables Object[] The current values for the flow’s output variables.
status String The current status of the interview. Valid statuses for a flow interview
are:
• STARTED: the interview successfully started.
• PAUSED: the interview was successfully paused.
• FINISHED: the interview for a flow with screens finished.
• FINISHED_SCREEN: the interview for a flow without screens
finished, and the component displayed a default screen with this
message: “Your flow finished”
491
Reference lightning:formattedAddress
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
onstatuschange Action The action triggered when the interview’s status changes or a new screen
is displayed.
lightning:formattedAddress
Displays a formatted address that provides a link to the given location on Google Maps. This component requires API version 42.0 and
later.
A lightning:formattedAddress component displays formatted addresses in a given format and order. The locale set in the
app's user preferences determines how addresses are formatted and the order they are presented. A valid address that includes the
street, city, country, province, and postal code must be used.
This example displays an address.
<aura:component>
<lightning:formattedAddress
street="1 Market St."
492
Reference lightning:formattedDateTime (Beta)
city="San Francisco"
country="US"
province="CA"
postalCode="94105"
/>
</aura:component>
The output looks like this. By default, the address is displayed as a link, which when clicked takes you to the given location on Google
Maps.
1 Market St.
San Francisco, CA 94105
US
If the latitude and longitude are provided, the address is displayed as the link label, and the link directs you to the given location provided
by the latitude and longitude on Google Maps.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies whether the address is clickable. This value defaults to false.
latitude Decimal The latitude of the location if known. Latitude values must be within -90
and 90.
longitude Decimal The longitude of the location if known. Longitude values must be within
-180 and 180.
title String Displays tooltip text when the mouse moves over the element.
lightning:formattedDateTime (Beta)
Displays formatted date and time.
A lightning:formattedDateTime component displays formatted date and time. This component uses the Intl.DateTimeFormat
JavaScript object to format date values. The locale set in the app's user preferences determines the formatting. The following input
values are supported.
493
Reference lightning:formattedDateTime (Beta)
• Date object
• ISO8601 formatted string
• Timestamp
An ISO8601 formatted string matches one of the following patterns.
• YYYY
• YYYY-MM
• YYYY-MM-DD
• YYYY-MM-DDThh:mmTZD
• YYYY-MM-DDThh:mm:ssTZD
• YYYY-MM-DDThh:mm:ss.sTZD
Here are some examples based on a locale of en-US.
Displays: 8/2/2016
<aura:component>
<lightning:formattedDateTime value="1470174029742" />
</aura:component>
Usage Considerations
This component provides fallback behavior in Apple Safari 10 and below. The following formatting options have exceptions when using
the fallback behavior in older browsers.
• era is not supported.
• timeZoneName appends GMT for short format, GMT-h:mm or GMT+h:mm for long format.
• timeZone supports UTC. If another timezone value is used, lightning:formattedDateTime uses the browser timezone.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
494
Reference lightning:formattedEmail
hour12 Boolean Determines whether time is displayed as 12-hour. If false, time displays
as 24-hour. The default setting is determined by the user's locale.
timeZone String The time zone to use. Implementations can include any time zone listed
in the IANA time zone database. The default is the runtime's default time
zone. Use this attribute only if you want to override the default time zone.
timeZoneName String Allowed values are short or long. For example, the Pacific Time zone
would display as 'PST' if you select 'short', or 'Pacific Standard Time' if you
select 'long.'
title String Displays tooltip text when the mouse moves over the element.
value Object The value to be formatted, which can be a Date object, timestamp, or Yes
an ISO8601 formatted string.
lightning:formattedEmail
Displays an email as a hyperlink with the mailto: URL scheme. This component requires API version 41.0 and later.
A lightning:formattedEmail component displays a read-only representation of an email address as a hyperlink using the
mailto: URL scheme. Clicking on the email address opens the default mail application for the desktop or mobile device.
This example displays an email address with an email icon. The email address is displayed as the default label.
<aura:component>
<lightning:formattedEmail value="hello@myemail.com" />
</aura:component>
Multiple email addresses are supported. The label "Send a group email" is displayed as a hyperlink in this example.
<aura:component>
<lightning:formattedEmail value="hello@email1.com,hello@email2.com" label="Send a group
email" />
</aura:component>
495
Reference lightning:formattedLocation
This example creates an email address with values for cc, subject, and email body. The label is displayed as a hyperlink.
<aura:component>
<lightning:formattedEmail value="hello@myemail.com?cc=cc@myemail.com&subject=My%20subject
&body=The%20email%20body"
label="Send us your feedback" />
</aura:component>
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
value String The email address that's displayed if a label is not provided. Yes
lightning:formattedLocation
Displays a geolocation in Decimal degrees (DD) using the format [latitude, longitude]. This component requires API version 41.0 and
later.
A lightning:formattedLocation component displays a read-only representation of a latitude and longitude value. Latitude
and longitude are geographic coordinates specified in decimal degrees. If one of the values are invalid or outside the allowed range,
this component doesn't display anything.
Here are a few examples of latitudes: -30, 45, 37.12345678, -10.0. Values such as 90.5 or -90.5 are not valid latitudes. Here are a few
examples of longitudes: -100, -120.9762, 115.84. Values such as 180.5 or -180.5 are not valid longitudes.
This example displays a geolocation with a latitude of 37.7938460 and a longitude of -122.3948370.
<aura:component>
<lightning:formattedLocation latitude="37.7938460" longitude="-122.3948370"/>
</aura:component>
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
latitude Decimal The latitude value of the geolocation. Latitude values must be within -90 Yes
and 90.
496
Reference lightning:formattedName
lightning:formattedName
Displays a formatted name that can include a salutation and suffix. This component requires API version 42.0 and later.
A lightning:formattedName component displays formatted names in a given format and order. The locale set in the app's
user preferences determines how names are formatted and the order they are presented.
This examples displays "Mr. John Middleton Doe The 3rd Jo" based on the default English United States locale with the long format.
<aura:component>
<lightning:formattedName
aura:id="myname"
firstName="John"
middleName="Middleton"
lastName="Doe"
informalName="Jo"
suffix="The 3rd"
salutation="Mr."
/>
</aura:component>
long Displays the name including Mr. John Middleton Doe The 3rd Jo
(default) salutation, first name, middle name,
last name, suffix, informal name.
For more information on supported locales, see Supported Locales in the Salesforce Help.
To create a form that takes in user input for names, you can use the lightning:inputName component, which displays a name
compound field that supports user input for salutation, suffix, and so on.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
497
Reference lightning:formattedNumber (Beta)
format String The format for which to display the name. Valid values include short,
medium, and long. This value defaults to long.
salutation String The value for the salutation, such as Dr. or Mrs.
title String Displays tooltip text when the mouse moves over the element.
lightning:formattedNumber (Beta)
Displays formatted numbers for decimals, currency, and percentages.
A lightning:formattedNumber component displays formatted numbers for decimals, currency, and percentages. This
component uses the Intl.NumberFormat JavaScript object to format numerical values. The locale set in the app's user preferences
determines how numbers are formatted.
The component has several attributes that specify how number formatting is handled in your app. Among these attributes are
minimumSignificantDigits and maximumSignificantDigits. Significant digits refer the accuracy of a number. For
example, 1000 has one significant digit, but 1000.0 has five significant digits. Additionally, the number of decimal places can be customized
using maximumFractionDigits.
Decimal numbers default to 3 decimal places. This example returns 1234.568.
<aura:component>
<lightning:formattedNumber value="1234.5678" />
</aura:component>
Currencies default to 2 decimal places. In this example, the formatted number displays as $5,000.00.
<aura:component>
<lightning:formattedNumber value="5000" style="currency" currencyCode="USD" />
</aura:component>
Percentages default to 0 decimal places. In this example, the formatted number displays as 50%.
<aura:component>
<lightning:formattedNumber value="0.5" style="percent" />
</aura:component>
Usage Considerations
This component provides the following fallback behavior in Apple Safari 10 and below.
498
Reference lightning:formattedPhone
• If style is set to currency, providing a currencyCode value that’s different from the locale displays the currency code
instead of the symbol. The following example displays EUR12.34 in fallback mode and €12.34 otherwise.
<lightning:formattedNumber value="12.34" style="currency"
currencyCode="EUR"/>
• currencyDisplayAs supports symbol only. The following example displays $12.34 in fallback mode only if currencyCode
matches the user’s locale currency and USD12.34 otherwise.
<lightning:formattedNumber value="12.34" style="currency"
currencyCode="USD" currencyDisplayAs="symbol"/>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
currencyCode String Only used if style='currency', this attribute determines which currency
is displayed. Possible values are the ISO 4217 currency codes, such as
'USD' for the US dollar.
currencyDisplayAs String Determines how currency is displayed. Possible values are symbol, code,
and name. This value defaults to symbol.
maximumFractionDigits Integer The maximum number of fraction digits that are allowed.
maximumSignificantDigits Integer The maximum number of significant digits that are allowed. Possible
values are from 1 to 21.
minimumFractionDigits Integer The minimum number of fraction digits that are required.
minimumIntegerDigits Integer The minimum number of integer digits that are required. Possible values
are from 1 to 21.
minimumSignificantDigits Integer The minimum number of significant digits that are required. Possible
values are from 1 to 21.
style String The number formatting style to use. Possible values are decimal, currency,
and percent. This value defaults to decimal.
title String Displays tooltip text when the mouse moves over the element.
lightning:formattedPhone
Displays a phone number as a hyperlink with the tel: URL scheme. This component requires API version 41.0 and later.
499
Reference lightning:formattedRichText
A lightning:formattedPhone component displays a read-only representation of a phone number as a hyperlink using the
tel: URL scheme. Clicking the phone number opens the default VOIP call application on a desktop. On mobile devices, clicking the
phone number calls the number.
Providing a phone number with 10 or 11 digits that starts with 1 displays the number in the format (999) 999-9999. Including a "+" sign
before the number displays the number in the format +19999999999.
Here are two ways to display (425) 333-4444 as a hyperlink.
<aura:component>
<p><lightning:formattedPhone value="4253334444"></lightning:formattedPhone></p>
<p><lightning:formattedPhone value="14253334444"></lightning:formattedPhone></p>
</aura:component>
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
onclick Action The action triggered when the phone number is clicked.
lightning:formattedRichText
Displays rich text that's formatted with whitelisted tags and attributes. Other tags and attributes are removed and only their text content
is displayed. This component requires API version 41.0 and later.
A lightning:formattedRichText component is a read-only representation of rich text. Rich text refers to text that's formatted
by HTML tags, such as <b> for bold text or <u> for underlined text. You can pass in rich text to this component using the
lightning:inputRichText component or programmatically by setting a value in the client-side controller.
This example creates a rich text editor that's wired up to a lightning:formattedRichText component. The rich text content
is set during initialization.
<aura:component>
<aura:handler name="init" value="{! this }" action="{! c.init }" />
<aura:attribute name="richtext" type="String"/>
<!-- Rich text editor and formatted output -->
<lightning:inputRichText value="{!v.richtext}"/>
<lightning:formattedRichText value="{!v.richtext}" />
</aura:component>
500
Reference lightning:formattedRichText
To use double quotes in your value definitions, escape them using the \ character.
var rte = "<h1 style=\"color:blue;\">This is a blue heading</h1>";
cmp.set("v.richtext", rte);
To pass in HTML tags in your component markup, escape the tags like this.
<lightning:formattedRichText value="<h1>TEST</h1>" />
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
501
Reference lightning:formattedText
lightning:formattedText
Displays text, replaces newlines with line breaks, and linkifies if requested. This component requires API version 41.0 and later.
A lightning:formattedText component displays a read-only representation of text, wrapping URLs and email addresses in
anchor tags (also known as "linkify"). It also converts the \r or \n characters into <br /> tags.
To display URLs and email addresses in a block of text in anchor tags, set linkify="true". If not set, URLs and email addresses
display as plain text. Setting linkify="true" wraps URLs and email addresses in anchor tags with format="html"
scope="external" type="new-window:HTML". URLs and email addresses are appended by http:// and mailto://
respectively.
<aura:component>
<lightning:formattedText linkify="true" value="I like salesforce.com and
trailhead.salesforce.com." />
</aura:component>
Usage Considerations
lightning:formattedText supports the following protocols: http, https, ftp and mailto.
If you're working with hyperlinks and need to specify the target value, use lightning:formattedURL instead. If you're
working with email addresses only, use lightning:formattedEmail.
For rich text that uses tags beyond anchor tags, use lightning:formattedRichText instead.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
linkify Boolean Specifies whether the text should be converted to a link. If set to true,
URLs and email addresses are displayed in anchor tags.
lightning:formattedTime
Displays a formatted time in user's locale format. This component requires API version 42.0 and later.
502
Reference lightning:formattedUrl
A lightning:formattedTime component displays a read-only representation of time in the user's locale format. A valid ISO8601
formatted time string must be used.
An ISO8601 formatted time string matches one of the following patterns.
• HH:mm
• HH:mm:ss
• HH:mm:ss.SSS
• HH:mmZ
• HH:mm:ssZ
• HH:mm:ss.SSSZ
HH is the number of hours that have passed since midnight, and mm is the number of minutes that have passed since the start of the
hour, and ss is the number of seconds since the start of the minute. To indicate that a time is measured in Universal Time (UTC), append
a Z to a time.
The following example returns 10:12:30 PM.
<aura:component>
<lightning:formattedTime value="22:12:30.999Z" />
</aura:component>
Salesforce uses the format HH:mm:ss.SSSZ for time fields. The time field is a timestamp without the date included. Time values in Salesforce
are not localized or associated with a time zone.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
lightning:formattedUrl
Displays a URL as a hyperlink. This component requires API version 41.0 and later.
A lightning:formattedUrl component displays a read-only representation of a URL as a hyperlink with an href attribute.
The link can be a relative or absolute URL. Absolute URLs use protocols such as http://, https://, and ftp://. This component
renders an anchor link with the absolute URL as the href value and the label as the displayed text. If no label is provided, the
absolute url is used as the displayed text. Clicking the URL takes you to the URL in the same window as it was clicked.
An absolute URL displays using the http:// protocol by default.
<aura:component>
<lightning:formattedUrl value="www.salesforce.com" />
</aura:component>
503
Reference lightning:helptext
A relative URL navigates to a path within the current site you're on.
<aura:component>
<!-- Resolves to http://current-domain/my/path -->
<lightning:formattedUrl value="/my/path" />
</aura:component>
Usage Considerations
Use the target attribute to change where the link should open. If you don't provide a target, the hyperlink renders without the href
attribute. Supported target values are:
• _blank: Opens the link in a new window or tab.
• _self: Opens the link in the same frame as it was clicked. This is the default behavior.
• _parent: Opens the link in the parent frame. If there's no parent, this is similar to _self.
• _top: Opens the link into the top-level browsing context. If there's no parent, this is similar to _self.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
target String Specifies where to open the link. Options include _blank, _parent, _self,
and _top.
tooltip String The text to display when the mouse hovers over the link.
lightning:helptext
An icon with a text popover.
A lightning:helptext component displays an icon with a popover containing a small amount of text describing an element
on screen. The popover is displayed when you hover or focus on the icon that's attached to it. This component is similar to a tooltip and
is useful to display field-level help text, for example. HTML markup is not supported in the tooltip content.
This component inherits styling from tooltips in the Lightning Design System.
504
Reference lightning:icon
By default, the tooltip uses the utility:info icon. The Lightning Design System utility icon category offers nearly 200 utility icons
that can be used in lightning:helptext. Although the Lightning Design System provides several categories of icons, only the
utility category can be used in lightning:buttonIcon.
Visit https://lightningdesignsystem.com/icons/#utility to view the utility icons.
This example creates an icon with a tooltip.
<aura:component>
<lightning:helptext
content="Your email address will be your login name" />
</aura:component>
The popover is anchored on the lower left of the icon and shown above the icon if space is available. It automatically adjusts its position
according to the viewport.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
iconName String The Lightning Design System name of the icon used as the visible
element. Names are written in the format 'utility:info' where 'utility' is the
category, and 'info' is the specific icon to be displayed. The default value
is 'utility:info'.
lightning:icon
Represents a visual element that provides context and enhances usability.
A lightning:icon is a visual element that provides context and enhances usability. Icons can be used inside the body of another
component or on their own.
Visit https://lightningdesignsystem.com/icons to view the available icons.
Here is an example.
<aura:component>
<lightning:icon iconName="action:approval" size="large" alternativeText="Indicates
approval"/>
</aura:component>
Use the variant, size, or class attributes to customize the styling. The variant attribute changes the appearance of a utility
icon. For example, the error variant adds a red fill to the error utility icon.
<lightning:icon iconName="utility:error" variant="error"/>
505
Reference lightning:input (Beta)
If you want to make additional changes to the color or styling of an icon, use the class attribute.
Usage Considerations
When using lightning:icon in a standalone app, extend force:slds to resolve the icon resources correctly.
<aura:application extends="force:slds">
<lightning:icon iconName="utility:error" variant="error"/>
</aura:application>
Accessibility
Use the alternativeText attribute to describe the icon. The description should indicate what happens when you click the button,
for example 'Upload File', not what the icon looks like, 'Paperclip'.
Sometimes an icon is decorative and does not need a description. But icons can switch between being decorative or informational based
on the screen size. If you choose not to include an alternativeText description, check smaller screens and windows to ensure
that the icon is decorative on all formats.
Attributes
Attribute Name Attribute Type Description Required?
alternativeText String The alternative text used to describe the icon. This text should describe
what happens when you click the button, for example 'Upload File', not
what the icon looks like, 'Paperclip'.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
iconName String The Lightning Design System name of the icon. Names are written in the Yes
format 'utility:down' where 'utility' is the category, and 'down' is the
specific icon to be displayed.
size String The size of the icon. Options include xx-small, x-small, small, medium, or
large. This value defaults to medium.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the appearance of a utility icon. Accepted variants
include inverse, warning and error. Use the inverse variant to implement
a white fill in utility icons on dark backgrounds.
lightning:input (Beta)
Represents interactive controls that accept user input depending on the type attribute.
A lightning:input component creates an HTML input element. This component supports HTML5 input types, including
checkbox, date and datetime, email, file, password, search, tel, url, number, radio, toggle. The default
is text.
506
Reference lightning:input (Beta)
You can define a client-side controller action for input events like onblur, onfocus, and onchange. For example, to handle a
change event on the component when the value of the component is changed, use the onchange attribute.
This component inherits styling from input in the Lightning Design System.
Checkbox
Checkboxes let you select one or more options. lightning:input type="checkbox" is useful for creating single checkboxes.
If you are working with a group of checkboxes, use lightning:checkboxGroup instead.
<lightning:input type="checkbox" label="Red" name="red" checked="true"/>
<lightning:input type="checkbox" label="Blue" name="blue" />
Checkbox-button
Checkbox buttons let you select one or more options with an alternative visual design.
<lightning:input type="checkbox" label="Add pepperoni" name="addPepperoni" checked="true"
value="pepperoni" />
<lightning:input type="checkbox-button" label="Add salami" name="addSalami" value="salami"
/>
Color
A color picker enables you to specify a color using a color picker or by entering the color into a text field. The color picker doesn't currently
support the Lightning Design System styling.
<lightning:input type="color" label="Color" name="color" value="#EEEEEE"/>
Date
An input field for entering a date. The date picker doesn't currently support the Lightning Design System styling. The date format is
automatically validated during the onblur event.
<lightning:input type="date" label="Birthday" name="date" />
Datetime
An input field for entering a date and time. The date picker doesn't currently support the Lightning Design System styling. The date and
time format is automatically validated during the onblur event.
<lightning:input type="datetime-local" label="Birthday" name="datetime" />
Email
An input field for entering an email address. The email pattern is automatically validated during the onblur event.
<lightning:input type="email" label="Email" name="email" value="abc@domain.com" />
File
An input field for uploading files using a Upload Files button or a drag-and-drop zone. To retrieve the list of selected files, use
event.getSource().get("v.files");.
Files uploaded using type="file" are subject to a 1 MB size limit, or about 4MB if you chunk the files. You must wire up your
component to an Apex controller that handles file uploads. Alternatively, use the lightning:fileUpload component for an
integrated way to upload files to records.
Month
507
Reference lightning:input (Beta)
An input field for entering a month and year. Date pickers don't currently inherit the Lightning Design System styling. The month and
year format is automatically validated during the onblur event.
<lightning:input type="month" label="Birthday" name="month" />
Number
An input field for entering a number. When working with numerical input, you can use attributes like max, min, and step.
<lightning:input type="number" name="number" label="Number" value="12345"/>
To format numerical input as a percentage or currency, set formatter to percent or currency respectively.
<lightning:input type="number" name="ItemPrice"
label="Price" value="12345" formatter="currency"/>
Fields for percentage and currency input default to a step increment of 0.01.
<lightning:input type="number" name="decimal" label="Enter a decimal value" step="0.001"/>
<lightning:input type="number" name="percentVal" label="Enter a percentage value"
formatter="percent" step="0.01" />
<lightning:input type="number" name="currencyVal" label="Enter a dollar amount"
formatter="currency" step="0.01" />
To enter a percentage value as is, use formatter="percent-fixed". For example, entering "10" results in "10%" on blur.
Password
An input field for entering a password. Characters you enter are masked.
<lightning:input type="password" label="Password" name="password" />
Radio
Radio buttons let you select only one of a given number of options. lightning:input type="radio" is useful for creating
single radio buttons. If you are working with a set of radio buttons, use lightning:radioGroup instead.
<lightning:input type="radio" label="Red" name="red" value="red" checked="true" />
<lightning:input type="radio" label="Blue" name="blue" value="blue" />
Range
A slider control for entering a number. When working with numerical input, you can use attributes like max, min, and step.
<lightning:input type="range" label="Number" name="number" min="0" max="10" />
Search
An input field for entering a search string. This field displays the Lightning Design System search utility icon.
<lightning:input type="search" label="Search" name="search" />
Tel
An input field for entering a telephone number. Use the pattern attribute to define a pattern for field validation.
<lightning:input type="tel" label="Telephone" name="tel" value="343-343-3434"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"/>
Text
508
Reference lightning:input (Beta)
An input field for entering text. This is the default input type.
<lightning:input label="Name" name="myname" />
Time
An input field for entering time. The time format is automatically validated during the onblur event.
<lightning:input type="time" label="Time" name="time" />
Toggle
A checkbox toggle for selecting one of two given values.
<lightning:input type="toggle" label="Toggle value" name="togglevalue" checked="true" />
URL
An input field for entering a URL. This URL pattern is automatically validated during the onblur event.
<lightning:input type="url" label="Website" name="website" />
Week
An input field for entering a week and year. Date pickers don't currently inherit the Lightning Design System styling. The week and year
format is automatically validated during the onblur event.
<lightning:input type="week" label="Week" name="week" />
Input Validation
Client-side input validation is available for this component. For example, an error message is displayed when a URL or email address is
expected for an input type of url or email.
You can define additional field requirements. For example, to set a maximum length, use the maxlength attribute.
<lightning:input name="quantity" value="1234567890" label="Quantity" maxlength="10" />
To check the validity states of an input, use the validity attribute, which is based on the ValidityState Web API. To determine
if a field is valid, you can access the validity states in your client-side controller. Let's say you have the following input field.
<lightning:input name="input" aura:id="myinput" label="Enter some text" onblur="{!
c.handleBlur }" />
The valid property returns true because all constraint validations are met, and in this case there are none.
handleBlur: function (cmp, event) {
var validity = cmp.find("myinput").get("v.validity");
console.log(validity.valid); //returns true
}
For example, you have the following form with several fields and a button. To display error messages on invalid fields, use the
showHelpMessageIfInvalid() method.
<aura:component>
<lightning:input aura:id="field" label="First name" placeholder="First name"
required="true" />
<lightning:input aura:id="field" label="Last name" placeholder="Last name"
required="true" />
<lightning:button aura:id="submit" type="submit" label="Submit" onclick="{! c.onClick
}" />
</aura:component>
509
Reference lightning:input (Beta)
This validity attribute returns an object with the following boolean properties.
• badInput: Indicates that the value is invalid
• patternMismatch: Indicates that the value doesn't match the specified pattern
• rangeOverflow: Indicates that the value is greater than the specified max attribute
• rangeUnderflow: Indicates that the value is less than the specified min attribute
• stepMismatch: Indicates that the value doesn't match the specified step attribute
• tooLong: Indicates that the value exceeds the specified maxlength attribute
• typeMismatch: Indicates that the value doesn't match the required syntax for an email or url input type
• valid: Indicates that the value is valid
• valueMissing: Indicates that an empty value is provided when required attribute is set to true
Error Messages
When an input validation fails, the following messages are displayed by default.
• badInput: Enter a valid value.
• patternMismatch: Your entry does not match the allowed pattern.
• rangeOverflow: The number is too high.
• rangeUnderflow: The number is too low.
• stepMismatch: Your entry isn't a valid increment.
• tooLong: Your entry is too long.
• typeMismatch: You have entered an invalid format.
• valueMissing: Complete this field.
You can override the default messages by providing your own values for these attributes: messageWhenBadInput,
messageWhenPatternMismatch, messageWhenTypeMismatch, messageWhenValueMissing,
messageWhenRangeOverflow, messageWhenRangeUnderflow, messageWhenStepMismatch,
messageWhenTooLong.
For example, you want to display a custom error message when the input is less than five characters.
<lightning:input name="firstname" label="First Name" minlength="5"
messageWhenBadInput="Your entry must be at least 5 characters." />
Usage Considerations
510
Reference lightning:input (Beta)
maxlength limits the number of characters you can enter. The messageWhenTooLong error message isn't triggered because
you can't type more than the number of characters allowed. However, you can use the messageWhenPatternMismatch and
pattern to achieve the same behavior.
Accessibility
You must provide a text label for accessibility to make the information available to assistive technology. The label attribute creates
an HTML label element for your input component. To hide a label from view and make it available to assistive technology, use the
label-hidden variant.
Methods
This component supports the following methods.
focus(): Sets focus on the element.
showHelpMessageIfInvalid(): Shows the help message if the form control is in an invalid state.
Attributes
Attribute Name Attribute Type Description Required?
accept String Specifies the types of files that the server accepts. This attribute can be
used only when type='file'.
511
Reference lightning:input (Beta)
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
checked Boolean Specifies whether the checkbox is checked. This value defaults to false.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies that an input element should be disabled. This value defaults
to false.
files Object A FileList that contains selected files. This attribute can be used only when
type='file'.
formatter String String value with the formatter to be used. Valid values include percent,
percent-fixed, and currency.
isLoading Boolean Specifies whether the spinner is displayed to indicate that data is loading.
This value defaults to false.
max Decimal Expected higher bound for the value in Floating-Point number
messageToggleActive String Text shown for the active state of a toggle. The default is "Active".
messageToggleInactive String Text shown for then inactive state of a toggle. The default is "Inactive".
messageWhenTooLong String Error message to be displayed when the value is too long.
min Decimal Expected lower bound for the value in Floating-Point number
multiple Boolean Specifies that a user can enter more than one value. This attribute can
be used only when type='file' or type='email'.
onblur Action The action triggered when the element releases focus.
512
Reference lightning:inputAddress
onfocus Action The action triggered when the element receives focus.
pattern String Specifies the regular expression that the input's value is checked against.
This attribute is supported for text, date, search, url, tel, email, and
password types.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
readonly Boolean Specifies that an input field is read-only. This value defaults to false.
required Boolean Specifies that an input field must be filled out before submitting the form.
This value defaults to false.
step Object Granularity of the value in Positive Floating Point. Use 'any' when
granularity is not a concern.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
title String Displays tooltip text when the mouse moves over the element.
type String The type of the input. This value defaults to text.
validity Object Represents the validity states that an element can be in, with respect to
constraint validation.
variant String The variant changes the appearance of an input field. Accepted variants
include standard and label-hidden. This value defaults to standard.
lightning:inputAddress
Represents an address compound field. This component requires API version 42.0 and later.
A lightning:inputAddress component is an address compound field represented by HTML input elements of type text.
The country and province fields can be an input field or a dropdown menu. An input field is displayed if countryOptions and
provinceOptions are not provided.
This example creates an address compound field with a field for the street, city, province, postal code, and country.
<aura:component>
<div style="max-width: 400px;">
<lightning:inputAddress
aura:id="myaddress"
addressLabel="Address"
streetLabel="Street"
cityLabel="City"
countryLabel="Country"
provinceLabel="State"
postalCodeLabel="PostalCode"
513
Reference lightning:inputAddress
To create a dropdown menu for the country and province, pass in an array of label-value pairs to countryOptions and
provinceOptions. The country and province values are used as the default values on the dropdown menus.
<aura:component>
<aura:attribute name="provinceOptions" type="List" default="[
{'label': 'California', 'value': 'CA'},
{'label': 'Texas', 'value': 'TX'},
{'label': 'Washington', 'value': 'WA'},
]"/>
<aura:attribute name="countryOptions" type="List" default="[
{'label': 'United States', 'value': 'US'},
{'label': 'Japan', 'value': 'JP'},
{'label': 'China', 'value': 'CN'},
]"/>
<div style="max-width: 400px;">
<lightning:inputAddress
aura:id="myaddress"
addressLabel="Address"
streetLabel="Street"
cityLabel="City"
countryLabel="Country"
provinceLabel="Province/State"
postalCodeLabel="PostalCode"
street="1 Market St."
city="San Francisco"
country="US"
countryOptions="{! v.countryOptions }"
provinceOptions="{! v.provinceOptions }"
postalCode="94105"
required="true"
/>
</div>
</aura:component>
Alternatively, you can enable state and country picklists in your org, and access the values through an Apex controller. For more information,
see Let Users Select State and Country from Picklists in Salesforce Help.
Usage Considerations
When you set required="true", a red asterisk is displayed on every address field to indicate that they are required. An error
message is displayed below a field if a user interacted with it and left it blank. The required attribute is not enforced and you must
validate it before submitting a form that contains an address compound field.
514
Reference lightning:inputAddress
Let's say you have a lightning:button component that calls the handleClick controller action. You can display the error
message when a user clicks the button without providing a value on a field.
({
handleClick: function (cmp, event) {
var address = cmp.find("myaddress");
var isValid = address.checkValidity();
if(isValid) {
alert("Creating new address");
}
else {
address.showHelpMessageIfInvalid();
}
}
})
Attributes
Attribute Name Attribute Type Description Required?
addressLabel String The label of the address compound field.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
country String The country field of the address. If countryOptions is provided, this country
value is selected by default.
countryOptions List The array of label-value pairs for the country. Displays a dropdown menu
of options.
disabled Boolean Specifies whether the address fields are disabled. This value defaults to
false.
onblur Action The action triggered when the input releases focus.
onfocus Action The action triggered when the input receives focus.
postalCodeLabel String The label of the postal code field of the address.
province String The province field of the address. If provinceOptions is provided, this
province value is selected by default.
515
Reference lightning:inputField
readonly Boolean Specifies whether the address fields are read-only. This value defaults to
false.
required Boolean Specifies whether the address fields are required. This value defaults to
false.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the appearance of the compound field. Accepted
variants include standard and label-hidden. This value defaults to
standard.
lightning:inputField
Represents an editable input for a field on a Salesforce object. This component requires API version 42.0 and later.
A lightning:inputField component displays an editable field based on the field type. For example, if fieldName references
a date value, then a date field with a date picker is rendered. If fieldName references a picklist, then a dropdown menu displays
values based on your record types.
This component inherits styling from form layout in the Lightning Design System.
To create a record edit layout, use this component with lightning:recordEditForm and pass in a record ID and object API
name. To create a record create layout, use this component with lightning:recordEditForm and pass in the object API name
of the record you're creating. You don't need additional Apex controllers or Lightning Data Service as data refresh happens automatically.
To support error handling, include the lightning:messages component. To support record edit and create, include a
lightning:button with type="submit". You must provide a record type ID using the recordTypeId attribute on
lightning:recordEditForm if you have multiple record types on an object and you don't have a default record type.
Here's an example that displays a record edit layout and a record view layout for a contact record. The record view is automatically
updated when you make edits and press the Update record button.
<aura:component>
<div class="slds-p-bottom_large slds-p-left_large" style="width:500px">
<lightning:recordEditForm aura:id="recordViewForm"
recordId="003R00000000000000"
recordTypeId="012R00000000000000"
objectApiName="Contact">
<lightning:messages />
<lightning:inputField fieldName="FirstName" />
<lightning:inputField fieldName="LastName" />
<lightning:inputField fieldName="Birthdate" />
<lightning:inputField fieldName="Phone" />
<!--Picklist-->
<lightning:inputField fieldName="Level__c" />
<lightning:button aura:id="submit" type="submit" label="Update record"
516
Reference lightning:inputField
class="slds-m-top_medium" />
</lightning:recordEditForm>
</div>
<!-- Record Display -->
<div class="slds-p-bottom_large slds-p-left_large" style="width:500px">
<lightning:recordViewForm recordId="003R00000000000000" objectApiName="Contact">
<div class="slds-box">
<lightning:outputField fieldName="Name" />
<lightning:outputField fieldName="Birthdate" />
<lightning:outputField fieldName="Phone" />
<lightning:outputField fieldName="Level__c" />
</div>
</lightning:recordViewForm>
</div>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
value String The field value, which overrides the existing value.
517
Reference lightning:inputLocation
lightning:inputLocation
Represents a geolocation compound field that accepts a latitude and longitude value. This component requires API version 41.0 and
later.
A lightning:inputLocation component represents a geolocation compound field that accepts user input for a latitude and
longitude value. Latitude and longitude are geographic coordinates specified in decimal degrees. The geolocation compound field
allows you to identify locations by their latitude and longitude. The latitude field accepts values within -90 and 90, and the longitude
field accepts values within -180 and 180. An error message is displayed when you enter a value outside of the accepted range.
Here are a few examples of latitudes: -30, 45, 37.12345678, -10.0. Values such as 90.5 or -90.5 are not valid latitudes. Here are a few
examples of longitudes: -100, -120.9762, 115.84. Values such as 180.5 or -180.5 are not valid longitudes.
This example displays a geolocation compound field with a latitude of 37.7938460 and a longitude of -122.3948370.
<aura:component>
<lightning:inputLocation label="My Coordinates" latitude="37.7938460"
longitude="-122.3948370"/>
</aura:component>
Methods
This component supports the following methods.
focus(): Sets focus on the element.
blur(): Removes focus from the element.
checkValidity(): Returns the valid property value (Boolean) on the ValidityState object to indicate whether the combobox has
any validity errors.
showHelpMessageIfInvalid(): Shows the help message if the compound field is in an invalid state.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
latitude String The latitude value. Latitude values must be within -90 and 90.
longitude String The longitude value. Longitude values must be within -180 and 180.
required Boolean Specifies whether the compound field must be filled out. An error
message is displayed if a user interacts with the field and does not provide
a value. This value defaults to false.
518
Reference lightning:inputName
readonly Boolean Specifies whether the compound field is read-only. This value defaults
to false.
variant String The variant changes the appearance of the compound field. Accepted
variants include standard and label-hidden. This value defaults to
standard.
onblur Action The action triggered when the input releases focus.
onfocus Action The action triggered when the input receives focus.
lightning:inputName
Represents a name compound field. This component requires API version 42.0 and later.
A lightning:inputName component is a name compound field represented by HTML input elements of type text. The
Salutation field is a dropdown menu that accepts an array of label-value pairs.
This example creates a name compound field with a field for first name, middle name, last name, informal name, suffix. The Salutation
dropdown menu displays "Mr." by default. The fieldsToDisplay attribute determines which fields are rendered.
<aura:component>
<aura:attribute name="salutationOptions" type="List" default="[
{'label': 'None', 'value': 'None'},
{'label': 'Mr.', 'value': 'Mr.'},
{'label': 'Ms.', 'value': 'Ms.'},
{'label': 'Mrs.', 'value': 'Mrs.'},
{'label': 'Dr.', 'value': 'Dr.'},
{'label': 'Prof.', 'value': 'Prof.'},
]"/>
<aura:attribute name="fields" type="List" default="['firstName', 'lastName']"/>
<div class="slds-size_1-of-2">
<lightning:inputName
aura:id="myname"
label="Contact Name"
firstName="John"
middleName="Middleton"
lastName="Doe"
informalName="Jo"
suffix="The 3rd"
salutation="Mr."
options="{!v.salutationOptions}"
fieldsToDisplay="{!v.fields}"
/>
</div>
</aura:component>
519
Reference lightning:inputName
Usage Considerations
When you set required="true", a red asterisk is displayed on the Last Name field to indicate that it's required. An error message
is displayed below the Last Name field if a user interacted with it and left it blank. The required attribute is not enforced and you
must validate it before submitting a form that contains a name compound field.
Let's say you have a lightning:button component that calls the handleClick controller action. You can display the error
message when a user clicks the button without providing a value for the Last Name field.
({
handleClick: function (cmp, event) {
var name = cmp.find("myname");
var isValid = name.checkValidity();
if(isValid) {
alert("Creating new contact for " + name.get("v.lastName"));
}
else {
name.showHelpMessageIfInvalid();
}
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies whether the compound field should be disabled. Disabled fields
are grayed out and not clickable. This value defaults to false.
fieldsToDisplay List List of fields to be displayed on the component. This value defaults to
['firstName', 'salutation', 'lastName']. Other field values include
middleName, informalName, suffix.
lastName String Displays the Last Name field. This field is always displayed if you set
required to true.
onblur Action The action triggered when the input releases focus.
onfocus Action The action triggered when the input receives focus.
520
Reference lightning:inputRichText (Beta)
readonly Boolean Specifies whether the compound field is read-only. This value defaults
to false.
required Boolean Specifies whether the compound field must be filled out. A red asterisk
is displayed on the Last Name field. An error message is displayed if a
user interacts with the Last Name field and does not provide a value. This
value defaults to false.
salutation String Displays the Salutation field as a dropdown menu. An array of label-value
pairs must be provided using the options attribute.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the appearance of the compound field. Accepted
variants include standard and label-hidden. This value defaults to
standard.
lightning:inputRichText (Beta)
A WYSIWYG editor with a customizable toolbar for entering rich text.
A lightning:inputRichText component creates a rich text editor based on the Quill JS library, enabling you to add, edit,
format, and delete rich text. You can create multiple rich text editors with different toolbar configurations. Pasting rich content into the
editor is supported if the feature is available in the toolbar. For example, you can paste bold text if the bold button is available in the
toolbar. An overflow menu is provided if more toolbar buttons are available than can fit the width of the toolbar.
This component inherits styling from rich text editor in the Lightning Design System.
This example creates a rich text editor and sets its content during initialization.
<aura:component>
<aura:attribute name="myVal" type="String" />
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<lightning:inputRichText value="{!v.myVal}" />
</aura:component>
521
Reference lightning:inputRichText (Beta)
text block with Left Align Text, Center Align Text, and Right Align Text buttons. The Remove Formatting button is also available,
and it always stands alone at the end of the toolbar.
You can disable buttons by category using the disabledCategories attribute. The categories are:
1. FORMAT_FONT: Format font family and size menus
2. FORMAT_TEXT: Format text buttons
3. FORMAT_BODY: Format body buttons
4. ALIGN_TEXT: Align text buttons
5. REMOVE_FORMATTING: Remove formatting buttons
The font menu provides the following font selection: Arial, Courier, Garamond, Salesforce Sans, Tahoma, Times New Roman, and Verdana.
The font selection defaults to Salesforce Sans with a size of 12px. Supported font sizes are: 8, 9, 10, 11, 12, 14, 16, 18, 20, 22, 24, 26, 28,
36, 48, and 72. When you copy and paste text in the editor, the font is preserved only if the font is available in the font menu.
Input Validation
lightning:inputRichText doesn't provide built-in validation but you can wire up your own validation logic. Set the valid
attribute to false to change the border color of the rich text editor to red. This example checks whether the rich text content is empty
or undefined.
<aura:component>
<aura:attribute name="myVal" type="String" />
<aura:attribute name="errorMessage" type="String" default="You haven't composed anything
yet."/>
<aura:attribute name="validity" type="Boolean" default="true"/>
<lightning:inputRichText value="{!v.myVal}" placeholder="Type something interesting"
messageWhenBadInput="{!v.errorMessage}" valid="{!v.validity}"/>
<lightning:button name="validate" label="Validate" onclick="{!c.validate}"/>
</aura:component>
The client-side controller toggles the validity of the rich text editor, and displays the error message when it's invalid.
({
validate: function(cmp) {
if(!cmp.get("v.myVal")){
cmp.set("v.validity", false);
}
else{
cmp.set("v.validity", true);
}
}
})
522
Reference lightning:inputRichText (Beta)
text content is preserved. The supported HTML tags are: a, b, col, colgroup, em (converted to i), h1, h2, h3, h4, h5, h6, i,
img, li, ol, p, q, s, strike (converted to s), strong, table, tbody, td, tfoot, th, thead, tr, u, ul, strike.
Pasting text enclosed in div and span tags convert those tags to p tags. Let’s say you paste or set some text in the editor that looks
like this.
The sky is <span style="color:blue;font-weight:bold">blue</span>.
<div style="color:#0000FF;font-weight:bold">This is some text in a div element.</div>
Notice that the font-weight:bold formatting is preserved and converted to a b tag since it corresponds to the Bold toolbar
button. Color formatting in the markup is removed.
Usage Considerations
Although the toolbar buttons for creating tables and inserting images and links are not available, creating them programmatically or
copy and pasting these elements preserves the formatting in the editor. However, resizing of images is not supported.
When using lightning:inputRichText in a standalone app, extend force:slds to display the editor styling correctly.
Methods
This component supports the following method.
focus(): Sets focus on the element.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
ariaLabel String Label describing the rich text editor to assistive technologies.
ariaLabelledby String An element ID that provides a label for the rich text editor.
ariaDescribedby String A space-separated list of element IDs that provides descriptive labels for
the rich text editor.
disabled Boolean Specifies whether the editor is disabled. This value defaults to false.
disabledCategories List A comma-separated list of button categories to remove from the toolbar.
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
523
Reference lightning:layout
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
valid Boolean Specifies whether the editor content is valid. If invalid, the slds-has-error
class is added. This value defaults to true.
variant String The variant changes the appearance of the toolbar. Accepted variants
include bottom-toolbar.
lightning:layout
Represents a responsive grid system for arranging containers on a page.
A lightning:layout is a flexible grid system for arranging containers within a page or inside another container. The default layout
is mobile-first and can be easily configured to work on different devices.
The layout can be customized by setting the following attribute values.
horizontalAlign
Spread layout items out horizontally based on the following values.
• center: Appends the slds-grid_align-center class to the grid. This attribute orders the layout items into a horizontal line
without any spacing, and places the group into the center of the container.
• space: Appends the slds-grid_align-space class to the grid. The layout items are spaced horizontally across the container,
starting and ending with a space.
• spread: Appends the slds-grid_align-spread class to the grid. The layout items are spaced horizontally across the container,
starting and ending with a layout item.
• end: Appends the slds-grid_align-end class to the grid. The layout items are grouped together and aligned horizontally
on the right side of the container.
verticalAlign
Spread layout items out vertically based on the following values.
• start: Appends the slds-grid_vertical-align-start class to the grid. The layout items are aligned at the top of the
container.
• center: Appends the slds-grid_vertical-align-center class to the grid. The layout items are aligned in the center
of the container.
• end: Appends the slds-grid_vertical-align-end class to the grid. The layout items are aligned at the bottom of the
container.
• stretch: Appends the slds-grid_vertical-stretch class to the grid. The layout items extend vertically to fill the container.
pullToBoundary
Pull layout items to the layout boundaries based on the following values. If padding is used on layout items, this attribute pulls the
elements on either side of the container to the boundary. Choose the size that corresponds to the padding on your layoutItems. For
instance, if lightning:layoutItem="horizontalSmall", choose pullToBoundary="small".
• small: Appends the slds-grid_pull-padded class to the grid.
524
Reference lightning:layout
Attributes
Attribute Name Attribute Type Description Required?
body Component[] Body of the layout component.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
horizontalAlign String Determines how to spread the layout items horizontally. The alignment
options are center, space, spread, and end.
multipleRows Boolean Determines whether to wrap the child items when they exceed the layout
width. If true, the items wrap to the following line. This value defaults to
false.
pullToBoundary String Pulls layout items to the layout boundaries and corresponds to the
padding size on the layout item. Possible values are small, medium, or
large.
verticalAlign String Determines how to spread the layout items vertically. The alignment
options are start, center, end, and stretch.
525
Reference lightning:layoutItem
lightning:layoutItem
The basic element of lightning:layout.
A lightning:layoutItem is the basic element within lightning:layout. You can arrange one or more layout items
inside lightning:layout. The attributes of lightning:layoutItem enable you to configure the size of the layout item,
and change how the layout is configured on different device sizes.
The layout system is mobile-first. If the size and smallDeviceSize attributes are both specified, the size attribute is applied
to small mobile phones, and the smallDeviceSize is applied to smart phones. The sizing attributes are additive and apply to
devices that size and larger. For example, if mediumDeviceSize=10 and largeDeviceSize isn’t set, then
mediumDeviceSize will apply to tablets, as well as desktop and larger devices.
If the smallDeviceSize, mediumDeviceSize, or largeDeviceSize attributes are specified, the size attribute is
required.
Here is an example.
<aura:component>
<div>
<lightning:layout>
<lightning:layoutItem padding="around-small">
<div>1</div>
</lightning:layoutItem>
<lightning:layoutItem padding="around-small">
<div>2</div>
</lightning:layoutItem>
<lightning:layoutItem padding="around-small">
<div>3</div>
</lightning:layoutItem>
<lightning:layoutItem padding="around-small">
<div>4</div>
</lightning:layoutItem>
</lightning:layout>
</div>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
flexibility Object Make the item fluid so that it absorbs any extra space in its container or
shrinks when there is less space. Allowed values are: auto (columns grow
or shrink equally as space allows), shrink (columns shrink equally as space
decreases), no-shrink (columns don't shrink as space reduces), grow
(columns grow equally as space increases), no-grow (columns don't grow
as space increases), no-flex (columns don't grow or shrink as space
526
Reference lightning:listView
largeDeviceSize Integer If the viewport is divided into 12 parts, this attribute indicates the relative
space the container occupies on device-types larger than desktop. It is
expressed as an integer from 1 through 12.
mediumDeviceSize Integer If the viewport is divided into 12 parts, this attribute indicates the relative
space the container occupies on device-types larger than tablet. It is
expressed as an integer from 1 through 12.
padding String Sets padding to either the right and left sides of a container, or all sides
of a container. Allowed values are horizontal-small, horizontal-medium,
horizontal-large, around-small, around-medium, around-large.
size Integer If the viewport is divided into 12 parts, size indicates the relative space
the container occupies. Size is expressed as an integer from 1 through
12. This applies for all device-types.
smallDeviceSize Integer If the viewport is divided into 12 parts, this attribute indicates the relative
space the container occupies on device-types larger than mobile. It is
expressed as an integer from 1 through 12.
lightning:listView
Displays a List View of the specified object. This component requires API 42.0 and later.
A lightning:listView component represents a list view of records that you own or have read or write access to, and records
shared with you. They also include records owned by or shared with users in roles below you in the role hierarchy. You can see only the
fields that are visible according to your page layout and field-level security settings.
To create a list view, specify which object to render with the objectApiName attribute and which list view to use with the listName
attribute. The list view doesn't require additional Apex controllers or Lightning Data Service to display record data.
This example displays a list view of Accounts with five rows. Each time "Load More" is clicked, five more rows are loaded and appended.
The action bar isn't shown at the top of the component and the per-row actions are also hidden. However, inline edit of individual cells
is available.
<lightning:listView aura:id="listViewAccounts"
objectApiName="Account"
listName="My_Accounts"
rows="5"
showActionBar="false"
enableInlineEdit="true"
showRowLevelActions="false"
/>
Usage Considerations
Links outside of Lightning Experience and Communities appear as hyperlinks but don't navigate to the link target. This is a known
limitation that will be addressed in a future release.
527
Reference lightning:listView
528
Reference lightning:menuItem
• SkillRequirement
• SocialPost
• Tenant
• TimeSheet
• TimeSheetEntry
• WorkType
• WorkOrder
• WorkOrderLineItem
Inline edit, row level actions, and the action bar are supported in Lightning Experience, the Salesforce app, and communities only.
If attempting to use these features outside of this context, they are automatically disabled and a warning displays.
On a desktop, this component renders a full list view. On all other form factors, such as a tablet or mobile devices, the component renders
a mobile-friendly alternative.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
enableInlineEdit Boolean Specifies whether the inline edit of cells is enabled. This value defaults
to false.
objectApiName String The API name of the object to be displayed in this List View Yes
rows Integer Specifies the number of rows to initially load and additional rows after
each subsequent 'Load More' click. The default and maximum number
of rows value is 50.
showActionBar Boolean Specifies whether the action bar displays. This value defaults to false.
showRowLevelActions Boolean Specifies whether row level actions are displayed (as a dropdown menu
in the last column of the row). This value defaults to false.
lightning:menuItem
Represents a list item in a menu.
A lightning:menuItem is a menu item within the lightning:buttonMenu dropdown component. It can hold state such
as checked or unchecked, and can contain icons.
Use the class attribute to customize the styling.
This component inherits styling from menus in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:buttonMenu alternativeText="Toggle menu">
529
Reference lightning:menuItem
To implement a multi-select menu, use the checked attribute. The following client-side controller example handles selection via the
onselect event on the lightning:buttonMenu component. Selecting a menu item applies the selected state to that item.
({
handleSelect : function (cmp, event) {
var menuItem = event.getSource();
// Toggle check mark on the menu item
menuItem.set("v.checked", !menuItem.get("v.checked"));
}
})
Methods
This component supports the following method.
focus(): Sets the focus on the element.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
checked Boolean If not specified, the menu item is not checkable. If true, the a check mark
is shown to the left of the menu item. If false, a check mark is not shown
but there is space to accommodate one.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean If true the menu item is not actionable and is shown as disabled.
iconName String If provided an icon with the provided name is shown to the right of the
menu item.
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
530
Reference lightning:omniToolkitAPI (Beta)
lightning:omniToolkitAPI (Beta)
This component provides access to the API for the Omni-channel toolkit.
The lightning:omniToolkitAPI component (beta) enables a component in the utility bar for Omni-Channel to use methods like returning
a list of open work items for an agent. Omni-Channel routes work to agents in the console.
This example includes a button to accept a work item that’s assigned to an agent in the Omni-Channel utility.
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
<lightning:omniToolkitAPI aura:id="omniToolkit" />
<lightning:button label="Accept" onClick="{! c.acceptWork }" />
</aura:component>
({
acceptWork: function(cmp, evt, hlp) {
var omniAPI = cmp.find("omniToolkit");
omniAPI.getAgentWorks({
callback: function(result) {
var works = JSON.parse(result.works);
var work = works[0];
omniAPI.acceptAgentWork({
workId: work.workId,
callback: function(result2) {
if (result2.success) {
console.log("Accepted work successfully");
} else {
console.log("Accept work failed");
}
}
});
}
});
}
})
Usage Considerations
All the methods are asynchronous, so they return the response in an object in a callback method.
Methods
This component supports the following methods.
acceptAgentWork({workId, callback}): Accepts a work item that’s assigned to an agent.
• workId (string): The ID of the work item the agent accepts.
• callback (function): Optional. Function called when an agent accepts the work item associated with the workId.
531
Reference lightning:outputField
closeAgentWork({workId, callback}): Changes the status of a work item to Closed and removes it from the list of work
items.
• workId (string): The ID of the work item that’s closed.
• callback (function): Optional. Function called when the work item associated with the workId is closed.
declineAgentWork({workId, declineReason, callback}): Declines a work item that’s assigned to an agent.
• workId (string): The ID of the work item that the agent declines.
• declineReason (string): Optional. The provided reason for why the agent declined the work request.
• callback (function): Optional. Function called when an agent declines the work item associated with the workId.
getAgentWorks({callback}): Returns a list of work items that are currently assigned to an agent and open in the agent’s
workspace.
• callback (function): Optional. Function called when the list of an agent’s work items is retrieved.
getAgentWorkload({callback}): Retrieves an agent’s currently-assigned workload. Use this method for rerouting work to
available agents.
• callback (function): Optional. Function called when the agent’s configured capacity and work retrieved.
getServicePresenceStatusChannels({callback}): Retrieves the service channels that are associated with an
Omni-Channel user’s current presence status.
• callback (function): Optional. Function called when the channels associated with a presence status are retrieved.
getServivePresenceStatusId({callback}): Retrieves an agent’s current presence status.
• callback (function): Optional. Function called when the agent’s presence status is retrieved.
login({statusId, callback}): Logs an agent into Omni-Channel with a specific presence status.
• statusId (string): The ID of the presence status.
• callback (function): Optional. Function called when the agent is logged in with the presence status associated with statusId.
logout({callback}): Logs an agent out of Omni-Channel.
• callback (function): Optional. Function called when the agent is logged out of Omni-Channel.
setServicePresenceStatus({statusId, callback}): Sets an agent’s presence status to a status with a particular ID.
We log the user into presence if that user isn’t already logged in. This removes the need for you to make additional calls.
• statusId (string): The ID of the presence status you want to set the agent to.
• callback (function): Optional. Function called when the agent’s status is changed to the presence status associated with statusId.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
lightning:outputField
Represents a read-only display of a label, help text, and value for a field on a Salesforce object. This component requires API version 41.0
and later.
532
Reference lightning:outputField
A lightning:outputField component displays the field value in the correct format based on the field type. You must provide
the record ID in the wrapper lightning:recordFormView component, and specify the field name on
lightning:outputField. For example, if fieldName references a date and time value, then the default output value contains
the date and time in the user's locale. If fieldName references an email address, phone number, or URL, then a clickable link is
displayed.
This component inherits styling from input (readonly state) in the Lightning Design System.
To create a record detail layout, wrap the fields with lightning:recordViewForm and provide the record ID. You don't need
additional Apex controllers or Lightning Data Service as data refresh happens automatically.
<aura:component>
<!-- Replace the record ID with your own -->
<lightning:recordViewForm recordId="001XXXXXXXXXXXXXXX" objectApiName="Contact">
<div class="slds-box slds-theme_default">
<lightning:outputField fieldName="Name" />
<lightning:outputField fieldName="Phone"/>
<lightning:outputField fieldName="Email" />
<lightning:outputField fieldName="Birthdate" />
<lightning:outputField fieldName="LeadSource" />
</div>
</lightning:recordViewForm>
</aura:component>
The user's locale settings determine the display formats for numbers, percentages, and date and time. Locales are currently not supported
for currency. Besides field values, lightning:outputField displays the localized labels and help text for the fields based on
their metadata, which are defined by your Salesforce admin. Additionally, no output label or value is rendered if you reference an invalid
field.
Usage Considerations
The following fields are supported.
• Auto Number: Displays a string that represents the unique number of the record.
• Checkbox: Displays a disabled checkbox that's either selected or not.
• Currency: Displays the formatted currency based on the user's locale. Locales are currently not supported for currency.
• Date: Displays the formatted date based on the user's locale.
• Date/Time: Displays the formatted date and time based on the user's locale.
• Email: Displays the email address prepended with the mailto: URL scheme.
• Formula: Displays the result of the formula based on its data type.
• Geolocation: Displays latitude and longitude in decimal degrees format: 90.0000, 180.0000.
• Lookup: Displays a relationship between two records, for example, the account ID associated to a contact record. Lookups render
as text only. Linking and hover overlays on lookup values are not supported.
• Number: Displays the integer or double.
• Percent: Displays the percentage number.
• Phone: Displays the phone number prepended with the tel: URL scheme.
• Picklist and multi-select picklist: Displays picklist values separated by a semi-colon.
• Text: Displays text up to 255 characters.
• Text (Encrypted): Displays the encrypted text.
• Text Area: Displays multi-line text up to 255 characters.
• Text Area (Long): Displays multi-line text up to 131,072 characters.
533
Reference lightning:path (Beta)
• Text Area (Rich): Displays rich text such as bold or underline text, lists, and images. Unsupported tags and attributes are removed
and only their text content is displayed. For more information on supported tags, see Rich Text Editor in Salesforce Help.
• URL: Displays a link that opens in the same browser window when it's clicked.
For supported objects, see the User Interface API Developer Guide.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
variant String Changes the appearance of the output. Accepted variants include
standard and label-hidden. This value defaults to standard.
lightning:path (Beta)
Displays a path driven by a picklist field and Path Setup metadata. This component requires API 41.0 and later.
A lightning:path component displays the progress of a process, which is based on the picklist field that's specified by Path
Settings in Setup. The path is rendered as a horizontal bar with a chevron for each picklist item. The key fields and guidance for success
are displayed below the path.
This example changes the path variant depending on which stage is clicked.
<aura:component
implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId"
>
<aura:attribute name="variant" type="String" default="non-linear"/>
<aura:attribute name="hideUpdateButton" type="Boolean" default="false"/>
<lightning:path aura:id="path" recordId="{!v.recordId}"
variant="{!v.variant}"
hideUpdateButton="{!v.hideUpdateButton}"
onselect="{!c.handleSelect}"
/>
</aura:component>
The client-side controller displays a toast with the step name that's clicked.
({
handleSelect : function (component, event, helper) {
var stepName = event.getParam("detail").value;
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Success!",
"message": "Toast from " + stepName
});
toastEvent.fire();
534
Reference lightning:picklistPath (Beta)
}
})
Usage Considerations
If an invalid attribute value is used, an error is displayed in place of the component.
Implementing the force:hasRecordId interfaces provides the record Id of the record that's currently viewed to the component.
To make your component available in Lightning App Builder, implement the flexipage:availableForAllPageTypes
interface, which enables admins to drag-and-drop the component onto a Lightning page easily.
To use a path component in the Salesforce app, display it in a custom tab.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
variant String Changes the appearance of the path. Choose between linear and
non-linear formats. In linear paths, completed steps show a checkmark.
In non-linear paths, completed steps show the step name. We show
linear paths by default.
hideUpdateButton Boolean Specified whether the Mark Complete button is displayed next to the
path. If true, the button is not displayed. The Mark Complete button is
displayed by default.
onselect Action The action triggered when a step on the path is clicked.
lightning:picklistPath (Beta)
Displays a path based on a specified picklist field. This component requires API 41.0 and later.
A lightning:picklistPath component displays the progress of a process, which is based on the picklist field specified by the
picklistFieldApiName attribute. The path is rendered as a horizontal bar with one chevron for each picklist item. Paths created
by this component do not have key fields or guidance and do not display the Mark Complete button.
This example creates a path for contact records that's based on the record ID and the LeadSource picklist field.
<aura:component
implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId"
>
<lightning:picklistPath aura:id="picklistPath" recordId="{!v.recordId}"
variant="non-linear"
picklistFieldApiName="LeadSource"
onselect="{!c.handleSelect}">
</lightning:picklistPath>
</aura:component>
535
Reference lightning:pill
Clicking a step in the path displays a toast with the step name that's clicked.
({
handleSelect : function (component, event, helper) {
var stepName = event.getParam("detail").value;
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Success!",
"message": "Toast from " + stepName
});
toastEvent.fire();
}
})
Usage Considerations
To create a path based on forecast categories, use the ForecastCategoryName field.
If an invalid attribute value is used, an error is displayed in place of the component.
Implementing the force:hasRecordId interfaces provides the record Id of the record that's currently viewed to the component.
To make your component available in Lightning App Builder, implement the flexipage:availableForAllPageTypes
interface, which enables admins to drag-and-drop the component onto a Lightning page easily.
To use a path component in the Salesforce app, display it in a custom tab.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
onselect Action The action triggered when a step on the path is clicked.
picklistFieldApiName String The API name of the field from which the path is derived. For example,
StageName for Opportunity.
variant String Changes the appearance of the path. Valid variants are linear and
non-linear. In linear paths, steps prior to the current step are displayed
with a checkmark to indicate completion. In non-linear paths, step names
are displayed instead. By default, the path displays as a linear path.
lightning:pill
A pill represents an existing item in a database, as opposed to user-generated freeform text.
A lightning:pill component represents an item, such as an account name or case number, and the text label is wrapped by a
rounded border. By default, pills are rendered with a remove button. They are useful for displaying read-only text that can be added and
removed on demand, for example, a list of email addresses or a list of keywords.
This component inherits styling from pills in the Lightning Design System.
Use the class attribute to apply additional styling.
536
Reference lightning:pill
Pills have two clickable elements: the text label and the remove button. Both elements trigger the onclick handler. If you provide
an href value, clicking the text label triggers the onclick handler and then takes you to the provided path. Clicking the remove
button on the pill triggers the onremove handler and then the onclick handler. These event handlers are optional.
To prevent the onclick handler from running, call event.preventDefault() in the onremove handler.
<aura:component>
<lightning:pill label="hello pill" onremove="{! c.handleRemoveOnly }" onclick="{!
c.handleClick }"/>
</aura:component>
({
handleRemoveOnly: function (cmp, event) {
event.preventDefault();
alert('Remove button was clicked!');
},
handleClick: function (cmp, event) {
// this won't run when you click the remove button
alert('The pill was clicked!');
}
})
Inserting an Image
A pill can contain an image, such as an icon or avatar, which represents the type of object. To insert an image in the pill, use the media
attribute.
<aura:component>
<lightning:pill label="Pill Label" href="/path/to/some/where">
<aura:set attribute="media">
<lightning:icon iconName="standard:account" alternativeText="Account"/>
</aura:set>
</lightning:pill>
</aura:component>
Usage Considerations
A pill can display an error state when the containing text doesn't match a pre-defined collection of items, such as when an email address
is invalid or a case number doesn't exist. Use the hasError attribute to denote a pill that contains an error. Setting hasError to
true inserts a warning icon in the pill and change the border to red. Providing your own image in this context has no effect on the pill.
Accessibility
Use the alternativeText attribute to describe the avatar, such as a user's initials or name. This description provides the value for
the alt attribute in the img HTML tag.
537
Reference lightning:pillContainer
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
hasError Boolean Specifies whether the pill has errors. The default is false.
href String The URL of the page that the link goes to.
label String The text label that displays in the pill. Yes
media Component[] The icon or figure that's displayed next to the textual information.
name String The name for the pill. This value is optional and can be used to identify
the pill in a callback.
title String Displays tooltip text when the mouse moves over the element.
lightning:pillContainer
A list of pills grouped in a container. This component requires API version 42.0 and later.
A lightning:pillContainer component represents a list of pills that contains a label with or without an avatar or icon. By
default, pills are rendered with a remove button but you must provide the onitemremove event handler. They are useful for displaying
read-only text that can be added and removed on demand, for example, a list of email addresses or a list of keywords.
This component displays pills using lightning:pill, which supports utility icons from the Lightning Design System. Visit
https://lightningdesignsystem.com/icons/#utility to view the utility icons.
lightning:pillContainer inherits styling from pills in the Lightning Design System.
This example creates three pills: a text-only pill, a pill with an avatar, and a pill with an icon.
<aura:component>
<aura:attribute name="items" type="List" default="[
{
label: 'My Pill',
name: 'mypill'
},
{
type: 'avatar',
label: 'Avatar Pill',
name: 'avatarpill',
src: '/my/path/avatar.jpg',
fallbackIconName: 'standard:user',
variant: 'circle',
alternativeText: 'User avatar',
538
Reference lightning:pillContainer
},
{
type: 'icon',
label: 'Icon Pill',
name: 'iconpill',
iconName: 'standard:account',
alternativeText: 'Account',
},
]"/>
<lightning:pillContainer items="{!v.items}" />
</aura:component>
A text-only pill supports the following attributes. These attributes can also be used to create a pill with an avatar or icon.
• label: Required. The text label that displays in the pill.
• name: The name for the pill. This value is optional and can be used to identify the pill in a callback.
• href: The URL of the page the link goes to.
To create a pill with an avatar, use the following attributes.
• type: The media type. Use avatar.
• src: Required. The URL of the avatar.
• fallbackIconName: The Lightning Design System name of the icon used as a fallback when the image fails to load. The initials fallback
relies on this for its background color. Names are written in the format 'standard:account' where 'standard' is the category, and
'account' is the specific icon to be displayed. Only icons from the standard and custom categories are allowed.
• variant: Changes the shape of the avatar. Valid values are empty, circle, and square. This value defaults to square.
• alternativeText: The alternative text used to describe the avatar, which is displayed as hover text on the image.
To create a pill with an icon, use the following attributes.
• type: The media type. Use icon.
• iconName: Required. The Lightning Design System name of the icon. Names are written in the format '\utility:down\' where 'utility'
is the category, and 'down' is the specific icon to be displayed. Only utility icons can be used in this component.
• alternativeText: The alternative text used to describe the icon. This text should describe what happens when you click the button,
for example 'Upload File', not what the icon looks like, 'Paperclip'.
Removing Pills
Clicking the remove button triggers the onitemremove handler.
<lightning:pillContainer items="{!v.items}" onitemremove="{!c.handleItemRemove}"/>
You can retrieve the name of the pill that's clicked in the event handler and remove the pill from view.
({
handleRemove: function (cmp, event) {
var name = event.getParam("item").name;
alert(name + ' pill was removed!');
// Remove the pill from view
var items = cmp.get('v.items');
var item = event.getParam("index");
items.splice(item, 1);
cmp.set('v.items', items);
}
})
539
Reference lightning:progressBar
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
lightning:progressBar
Displays a horizontal progress bar from left to right to indicate the progress of an operation. This component requires API version 41.0
and later.
A lightning:progressBar component displays the progress of an operation from left to right, such as for a file download or
upload.
This component inherits styling from progress bars in the Lightning Design System.
This example loads the progress bar on rendering and rerendering of the component.
<aura:component>
<aura:handler name="render" value="{!this}" action="{!c.onRender}"/>
<aura:attribute name="progress" type="Integer" default="0"/>
<lightning:progressBar value="{!v.progress}"/>
</aura:component>
Here’s the client-side controller that changes the value of the progress bar. Specifying progress === 100 ?
clearInterval(interval) : progress + 10 increases the progress value by 10% and stops the animation when the
progress reaches 100%. The progress bar is updated every 200 milliseconds.
({
onRender: function (cmp) {
var interval = setInterval($A.getCallback(function () {
var progress = cmp.get('v.progress');
cmp.set('v.progress', progress === 100 ? clearInterval(interval) : progress +
10);
}), 200);
}
})
540
Reference lightning:progressIndicator
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant of the progress bar. Valid values are base and circular.
size String The size of the progress bar. Valid values are x-small, small, medium, and
large. The default value is medium.
lightning:progressIndicator
Provides a visual indication on the progress of a particular process. This component is available in version 41.0 and later.
A lightning:progressIndicator component displays a horizontal list of steps in a process, indicating the number of steps
in a given process, the current step, as well as prior steps completed. For example, Sales Path uses a progress indicator to guide sales
reps through the stages of the sales process.
You can create progress indicators with different visual styling by specifying the type attribute. Set type="base" to create a
component that inherits styling from progress indicators in the Lightning Design System. Set type="path" to create a component
that inherits styling from path in the Lightning Design System.
If the type is not specified, the default type (base) is used. To create steps, use one or more lightning:progressStep component
along with label and value attributes. To specify the current step, the currentStep attribute must match one of the value
attributes on a lightning:progressStep component.
<aura:component>
<lightning:progressIndicator currentStep="step2">
<lightning:progressStep label="Step One" value="step1"/>
<lightning:progressStep label="Step Two" value="step2"/>
<lightning:progressStep label="Step Three" value="step3"/>
</lightning:progressIndicator>
</aura:component>
In the previous example, the label is displayed in a tooltip when you hover over the step. If the progress indicator type is path, the
label is displayed on hover if the step is completed or on the step itself if it's a current or incomplete step.
This example creates a path showing the current step at "Step Two". "Step One" is marked completed and "Step Three" is not yet
completed.
<aura:component>
<lightning:progressIndicator type="path" currentStep="step2">
<lightning:progressStep label="Step One" value="step1"/>
<lightning:progressStep label="Step Two" value="step2"/>
<lightning:progressStep label="Step Three" value="step3"/>
541
Reference lightning:radioGroup
</lightning:progressIndicator>
</aura:component>
Accessibility
Each progress step is decorated with assistive text, which is also the label of that step. For the base type, you can use the Tab key to
navigate from one step to the next. Press Shift+Tab to go to the previous step. For the path type, press Tab to activate the current step
and use the Up and Down Arrow key or the Left and Right arrow key to navigate from one step to another.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
currentStep String The current step, which must match the value attribute of one of
progressStep components. If a step is not provided, the value of the first
progressStep component is used.
hasError Boolean Indicates whether the current step is in error state and displays a warning
icon on the step indicator. Applies to the base type only. This value
defaults to false.
type String Changes the visual pattern of the indicator. Valid values are base and
path. This value defaults to base.
variant String Changes the appearance of the progress indicator for the base type only.
Valid values are base or shaded. The shaded variant adds a light gray
border to the step indicators. This value defaults to base.
lightning:radioGroup
A radio button group that can have a single option selected. This component requires API version 41.0 and later.
A lightning:radioGroup component represents a radio button group that can have a single option selected.
If the required attribute is true, at least one radio button must be selected. When a user interacts with the radio group and doesn't make
a selection, an error message is displayed.
If the disabled attribute is true, radio button selections can't be changed.
This component inherits styling from Radio Button in the Lightning Design System. Set type="button" to create a component
that inherits styling from Radio Button Group in the Lightning Design System.
This example creates a radio group with two options and option1 is selected by default. One radio button must be selected as the
required attribute is true.
<aura:component>
542
Reference lightning:radioGroup
You can check which values are selected by using cmp.find("mygroup").get("v.value"). To retrieve the values when
the selection is changed, use the onchange event handler and call event.getParam("value").
({
handleChange: function (cmp, event) {
var changeValue = event.getParam("value");
alert(changeValue);
}
});
Accessibility
The radio group is nested in a fieldset element that contains a legend element. The legend contains the label value. The
fieldset element enables grouping of related radio buttons to facilitate tabbing navigation and speech navigation for accessibility
purposes. Similarly, the legend element improves accessibility by enabling a caption to be assigned to the fieldset.
Methods
This component supports the following method.
checkValidity(): Returns the valid property value (Boolean) on the ValidityState object to indicate whether the radio group has
any validity errors.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
variant String The variant changes the appearance of an input field. Accepted variants
include standard and label-hidden. This value defaults to standard.
disabled Boolean Specifies that an input element should be disabled. This value defaults
to false.
543
Reference lightning:recordEditForm
required Boolean Specifies that an input field must be filled out before submitting the form.
This value defaults to false.
validity Object Represents the validity states that an element can be in, with respect to
constraint validation.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
onfocus Action The action triggered when the element receives focus.
onblur Action The action triggered when the element releases focus.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
options List Array of label-value pairs for each radio button. Yes
type String The style of the radio group. Options are radio or button. The default is
radio.
messageWhenValueMissing String Optional message displayed when no radio button is selected and the
required attribute is set to true.
lightning:recordEditForm
Represents a record edit layout that displays one or more fields, provided by lightning:outputField. This component requires API version
41.0 and later.
A lightning:recordEditForm component is a wrapper component that accepts a record ID and is used to display one or
more fields and labels associated with that record using lightning:inputField. lightning:recordEditForm requires
a record ID to display the fields on the record. It doesn't require additional Apex controllers or Lightning Data Service to display record
data. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.
lightning:recordEditForm and lightning:inputField support the following features.
• Display a record edit layout for editing a specified record
• Display a record create layout for creating a new record
If a lightning:button component with type="submit" is provided for the record edit layout and it's clicked, the component
automatically performs error handling and saves any changes in the input fields. Similarly, if the button is provided for the record create
layout and it's clicked, error handling is automatically performed and a new record is created with the input data you provide. You must
include lightning:messages to support error handling and displaying of error messages. Additionally, this component provides
basic input validation. For example, entering an invalid email format for the Email field results in an error message when you try to submit
544
Reference lightning:recordEditForm
the change. Similarly, a required field like the Last Name field displays an error message when you try to submit the change and the field
is blank.
Editing a Record
To enable record editing, pass in the ID of the record and the corresponding object API name to be edited. Specify the fields you want
to include in the record edit layout using lightning:inputField.
<aura:component>
<lightning:recordEditForm recordId="003XXXXXXXXXXXXXXX" objectApiName="Contact">
<lightning:messages />
<lightning:inputField fieldName="FirstName" />
<lightning:inputField fieldName="LastName" />
<lightning:inputField fieldName="Email" />
<lightning:button class="slds-m-top_small" variant="brand" type="submit"
name="update" label="Update" />
</lightning:recordEditForm>
</aura:component>
Creating a Record
To enable record creation, pass in the object API name for the record to be created. Specify the fields you want to include in the record
create layout.
<aura:component>
<lightning:recordEditForm aura:id="recordEditForm"
objectApiName="Contact">
<lightning:messages />
<lightning:inputField fieldName="Name" />
<lightning:button class="slds-m-top_small" type="submit" label="Create new" />
</lightning:recordEditForm>
</aura:component>
545
Reference lightning:recordEditForm
Usage Considerations
The lookup type is supported in Lightning Experience only. When used in the mobile app, the lookup type is rendered as an input text
field. The geolocation compound field is not supported. Read-only fields are displayed as input fields that are disabled. When
usinglightning:inputField, rich text fields can't be used for image uploads.
For supported objects, see the User Interface API Developer Guide.
Events
The onerror action returns the following parameter.
546
Reference lightning:recordViewForm
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
onerror Action The action triggered when there is an error on form submission.
onload Action The action triggered when the form data is loaded.
recordTypeId String The ID of the record type, which is required if you created multiple record
types but don't have a default.
lightning:recordViewForm
Represents a record view that displays one or more fields, provided by lightning:outputField. This component requires API version 41.0
and later.
A lightning:recordViewForm component is a wrapper component that accepts a record ID and is used to display one or
more fields and labels associated with that record using lightning:outputField. lightning:recordViewForm requires
a record ID to display the fields on the record. It doesn't require additional Apex controllers or Lightning Data Service to display record
data. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.
To display the fields on a record, specify the fields using lightning:outputField.
<aura:component>
<lightning:recordViewForm recordId="001XXXXXXXXXXXXXXX" objectApiName="My_Contact__c">
<div class="slds-box">
<lightning:outputField fieldName="Name" />
<lightning:outputField fieldName="Email__c" />
</div>
</lightning:recordViewForm>
</aura:component>
547
Reference lightning:relativeDateTime
<div class="slds-grid">
<div class="slds-col slds-size_1-of-2">
<!-- Your lightning:outputField components here -->
</div>
<div class="slds-col slds-size_1-of-2">
<!-- More lightning:outputField components here -->
</div>
</div>
</lightning:recordViewForm>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
lightning:relativeDateTime
Displays the relative time difference between the source date-time and the provided date-time.
When you provide a timestamp or JavaScript Date object, lightning:relativeDateTime displays a string that describes the
relative time between the current time and the provided time.
The unit of time that's used corresponds to how much time has passed since the provided time, for example, "a few seconds ago" or "5
minutes ago". A given time in the future returns the relative time, for example, "in 7 months" or "in 5 years".
This example returns the relative time between the current time and a given time in the past and future. The time differences are set by
the init handler.
<aura:component>
<aura:handler name="init" value="{! this }" action="{! c.init }" />
<aura:attribute name="past" type="Object"/>
<aura:attribute name="future" type="Object"/>
<p><lightning:relativeDateTime value="{! v.past }"/></p>
<p><lightning:relativeDateTime value="{! v.future }"/></p>
</aura:component>
The client-side controller is called during component initialization. The past and future attributes return:
548
Reference lightning:select
• 2 hours ago
• in 2 days
({
init: function (cmp) {
cmp.set('v.past', Date.now()-(2\*60\*60\*1000));
cmp.set('v.future', Date.now()+(2\*24\*60\*60\*1000));
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
lightning:select
Represents a select input.
A lightning:select component creates an HTML select element. This component uses HTML option elements to create
options in the dropdown list, enabling you to select a single option from the list. Multiple selection is currently not supported.
This component inherits styling from select in the Lightning Design System.
549
Reference lightning:select
You can define a client-side controller action to handle various input events on the dropdown list. For example, to handle a change
event on the component, use the onchange attribute. Retrieve the selected value using
cmp.find("selectItem").get("v.value").
<aura:component>
<lightning:select name="selectItem" label="Select an item" onchange="{!c.doSomething}">
</aura:iteration>
</lightning:select>
</aura:component>
In your client-side controller, define an array of options and assign this array to the items attribute.
({
loadOptions: function (component, event, helper) {
var opts = [
{ value: "Red", label: "Red" },
{ value: "Green", label: "Green" },
{ value: "Blue", label: "Blue" }
];
component.set("v.options", opts);
550
Reference lightning:select
}
})
In cases where you're providing a new array of options on the component, you might encounter a race condition in which the value on
the component does not reflect the new selected value. For example, the component returns a previously selected value when you run
component.find("mySelect").get("v.value") even after you select a new option because you are getting the value
before the options finish rendering. You can avoid this race condition by binding the value and selected attributes in the
lightning:select component as illustrated in the previous example. Also, bind the selected attribute in the new option
value and explicitly set the selected value on the component as shown in the next example, which ensures that the value on the
component corresponds to the new selected option.
updateSelect: function(component, event, helper){
var opts = [
{ value: "Cyan", label: "Cyan" },
{ value: "Yellow", label: "Yellow" },
{ value: "Magenta", label: "Magenta", selected: true }];
component.set('v.options', opts);
//set the new selected value on the component
component.set('v.selectedValue', 'Magenta');
//return the selected value
component.find("mySelect").get("v.value");
}
Input Validation
Client-side input validation is available for this component. You can make the dropdown menu a required field by setting
required="true". An error message is automatically displayed when an item is not selected and required="true".
To check the validity states of an input, use the validity attribute, which is based on the ValidityState object. You can access
the validity states in your client-side controller. This validity attribute returns an object with boolean properties. See
lightning:input for more information.
You can override the default message by providing your own value for messageWhenValueMissing.
Usage Considerations
The readonly attribute is inherited from an interface that is used for many input components. However, the readonly attribute
is not valid for lightning:select. Use the disable attribute instead to make a select component unchangeable.
The onchange event is triggered only when a user selects a value on the dropdown list with a mouse click, which is expected behavior
of the HTML select element. Programmatic changes to the value attribute don't trigger this event, even though that change
propagates to the select element. To handle this event, provide a change handler for value.
<aura:handler name="change" value="{!v.value}" action="{!c.handleChange}"/>
This example creates a dropdown list and a button that when clicked changes the selected option.
<aura:component>
<aura:attribute name="status" type="String" default="open"/>
<aura:handler name="change" value="{!v.status}" action="{!c.handleChange}"/>
<lightning:select aura:id="select" name="select" label="Opportunity Status"
value="{!v.status}">
<option value="">choose one...</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
<option value="closedwon">Closed Won</option>
</lightning:select>
551
Reference lightning:select
The client-side controller updates the selected option by changing the v.status value, which triggers the change handler.
({
changeSelect: function (cmp, event, helper) {
//Press button to change the selected option
cmp.find("select").set("v.value", "closed");
},
handleChange: function (cmp, event, helper) {
//Do something with the change handler
alert(event.getParam('value'));
}
})
Accessibility
You must provide a text label for accessibility to make the information available to assistive technology. The label attribute creates an
HTML label element for your input component. To hide a label from view and make it available to assistive technology, use the
label-hidden variant.
Methods
This component supports the following methods.
focus(): Sets focus on the element.
showHelpMessageIfInvalid(): Shows the help message if the form control is in an invalid state.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies that an input element should be disabled. This value defaults
to false.
label String Text that describes the desired select input. Yes
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
readonly Boolean Specifies that an input field is read-only. This value defaults to false.
552
Reference lightning:slider
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
title String Displays tooltip text when the mouse moves over the element.
validity Object Represents the validity states that an element can be in, with respect to
constraint validation.
value String The value of the select, also used as the default value to select the right
option during init. If no value is provided, the first option will be selected.
variant String The variant changes the appearance of an input field. Accepted variants
include standard and label-hidden. This value defaults to standard.
lightning:slider
An input range slider for specifying a value between two specified numbers. This component requires API version 41.0 and later.
A lightning:slider component is a horizontal or vertical slider for specifying a value between two specified numbers. For
example, this slider can be used to capture user input about order quantity or when you want to use an input field of type="range".
To orient the slider vertically, set type="vertical". Older browsers that don't support the slider fall back and treat it as
type="text".
This component inherits styling from slider in the Lightning Design System.
Here's an example of a slider with a step increment of 10.
<aura:component>
<aura:attribute name="myval" default="10" type="Integer"/>
<lightning:slider step="10" value="{!v.myval}" onchange="{! c.handleRangeChange }"/>
</aura:component>
The client-side controller handles the value change and updates it with the latest value.
({
handleRangeChange: function (cmp, event) {
var detail = cmp.set("v.value", event.getParam("value"));
}
})
Usage Considerations
By default, the min and max values are 0 and 100, but you can specify your own values. Additionally, if you specify your own step
increment value, you can drag the slider based on the step increment only. If you set the value lower than the min value, then the
value is set to the min value. Similarly, setting the value higher than the max value results in the value being set to the max value.
For precise numerical values, we recommend using the lightning:input component of type="number" instead.
Methods
This component supports the following methods.
blur(): Removes keyboard focus on the input element.
553
Reference lightning:slider
checkValidity(): Returns the valid property value (Boolean) on the ValidityState object to indicate whether the input field value
has any validity errors.
focus(): Sets focus on the input element.
setCustomValidity(message): Sets a custom error message to be displayed when a condition is met.
• message (String): The string that describes the error. If message is an empty string, the error message is reset.
showHelpMessageIfInvalid(): Displays error messages on the slider. The slider value is invalid if it fails at least one constraint
validation and returns false when checkValidity() is called.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
value Integer The numerical value of the input range. This value defaults to 0.
onchange String The action triggered when the slider value changes. You must pass any
newly selected value back to the slider component to bind the new value
to the slider.
min Integer The min value of the input range. This value defaults to 0.
max Integer The max value of the input range. This value defaults to 100.
step String The step increment value of the input range. Example steps include 0.1,
1, or 10. This value defaults to 1.
size String The size value of the input range. This value default to empty, which is
the base. Supports x-small, small, medium, and large.
type String The type of the input range position. This value defaults to horizontal.
label String The text label for the input range. Provide your own label to describe the
slider. Otherwise, no label is displayed.
disabled Boolean The disabled value of the input range. This value default to false.
variant String The variant changes the appearance of the slider. Accepted variants
include standard and label-hidden. This value defaults to standard.
messageWhenBadInput String Error message to be displayed when a bad input is detected. Use with
setCustomValidity.
messageWhenPatternMismatch String Error message to be displayed when a pattern mismatch is detected. Use
with setCustomValidity.
messageWhenTypeMismatch String Error message to be displayed when a type mismatch is detected. Use
with setCustomValidity.
554
Reference lightning:spinner
messageWhenRangeOverflow String Error message to be displayed when a range overflow is detected. Use
with setCustomValidity.
messageWhenRangeUnderflow String Error message to be displayed when a range underflow is detected. Use
with setCustomValidity.
messageWhenStepMismatch String Error message to be displayed when a step mismatch is detected. Use
with setCustomValidity.
messageWhenTooLong String Error message to be displayed when the value is too long. Use with
setCustomValidity.
onblur Action The action triggered when the slider releases focus.
onfocus Action The action triggered when the slider receives focus.
lightning:spinner
Displays an animated spinner.
A lightning:spinner displays an animated spinner image to indicate that a feature is loading. This component can be used
when retrieving data or anytime an operation doesn't immediately complete.
The variant attribute changes the appearance of the spinner. If you set variant="brand", the spinner matches the Lightning
Design System brand color. Setting variant="inverse" displays a white spinner. The default spinner color is dark blue.
This component inherits styling from spinners in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:spinner variant="brand" size="large"/>
</aura:component>
lightning:spinner is intended to be used conditionally. You can use aura:if or the Lightning Design System utility classes
to show or hide the spinner.
<aura:component>
<lightning:button label="Toggle" variant="brand" onclick="{!c.toggle}"/>
<div class="exampleHolder">
<lightning:spinner aura:id="mySpinner" />
</div>
</aura:component>
555
Reference lightning:tab (Beta)
}
})
Attributes
Attribute Name Attribute Type Description Required?
alternativeText String The alternative text used to describe the reason for the wait and need
for a spinner.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
size String The size of the spinner. Accepted sizes are small, medium, and large. This
value defaults to medium.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the appearance of the spinner. Accepted variants
are base, brand, and inverse. This value defaults to base.
lightning:tab (Beta)
A single tab that is nested in a lightning:tabset component.
A lightning:tab keeps related content in a single container. The tab content displays when a user clicks the tab. lightning:tab
is intended to be used with lightning:tabset.
This component inherits styling from tabs in the Lightning Design System.
The label attribute can contain text or more complex markup. In the following example, aura:set is used to specify a label that
includes a lightning:icon.
<aura:component>
<lightning:tabset>
<lightning:tab>
<aura:set attribute="label">
Item One
<lightning:icon iconName="utility:connected_apps" />
</aura:set>
</lightning:tab>
</lightning:tabset>
</aura:component>
Usage Considerations
This component creates its body during runtime. You won’t be able to reference the component during initialization. You can set your
content using value binding with component attributes instead. See lightning:tabset for more information.
Methods
This component supports the following method.
556
Reference lightning:tabset (Beta)
Attributes
Attribute Name Attribute Type Description Required?
body ComponentDefRef[] The body of the tab.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
class String A CSS class for the outer element, in addition to the component's base
classes.
title String The title displays when you hover over the tab. The title should describe
the content of the tab for screen readers.
id String The optional ID is used during tabset's onSelect event to determine which
tab was clicked.
onblur Action The action triggered when the element releases focus.
onfocus Action The action triggered when the element receives focus.
onactive Action The action triggered when this tab becomes active.
lightning:tabset (Beta)
Represents a list of tabs.
A lightning:tabset displays a tabbed container with multiple content areas, only one of which is visible at a time. Tabs are
displayed horizontally inline with content shown below it. A tabset can hold multiple lightning:tab components as part of its body. The
first tab is activated by default, but you can change the default tab by setting the selectedTabId attribute on the target tab.
Use the variant attribute to change the appearance of a tabset. The variant attribute can be set to default, scoped, or vertical.
The default variant underlines the active tab. The scoped tabset styling displays a closed container with a defined border around the
active tab. The vertical tabset displays a scoped tabset with the tabs displayed vertically instead of horizontally.
This component inherits styling from tabs in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:tabset>
<lightning:tab label="Item One">
Sample Content One
</lightning:tab>
<lightning:tab label="Item Two">
Sample Content Two
</lightning:tab>
</lightning:tabset>
557
Reference lightning:tabset (Beta)
</aura:component>
You can lazy load content in a tab by using the onactive attribute to inject the tab body programmatically. Here's an example with
two tabs, which loads content when they're active.
<lightning:tabset variant="scoped">
<lightning:tab onactive="{! c.handleActive }" label="Accounts" id="accounts" />
<lightning:tab onactive="{! c.handleActive }" label="Cases" id="cases" />
</lightning:tabset>
In your client-side controller, pass in the component and event to the helper.
({
handleActive: function (cmp, event, helper) {
helper.lazyLoadTabs(cmp, event);
}
})
Your client-side helper identifies the tab that's selected and adds your content using $A.createComponent().
({
lazyLoadTabs: function (cmp, event) {
var tab = event.getSource();
switch (tab.get('v.id')) {
case 'accounts' :
this.injectComponent('c:myAccountComponent', tab);
break;
case 'cases' :
this.injectComponent('c:myCaseComponent', tab);
break;
}
},
injectComponent: function (name, target) {
$A.createComponent(name, {
}, function (contentComponent, status, error) {
if (status === "SUCCESS") {
target.set('v.body', contentComponent);
} else {
throw new Error(error);
}
});
}
})
<aura:component>
<aura:attribute name="moretabs" type="Aura.Component[]"/>
<lightning:tabset variant="scoped">
<lightning:tab label="Item One">
Some content here
</lightning:tab>
{!v.moretabs}
558
Reference lightning:tabset (Beta)
</lightning:tabset>
<!-- Click button to create a new tab -->
<lightning:button label="Add tab" onclick="{!c.addTab}"/>
The client-side controller adds the onactive event handler and creates the tab content when the new tab is clicked.
({
addTab: function(component, event) {
$A.createComponent("lightning:tab", {
"label": "New Tab",
"id": "new",
"onactive": component.getReference("c.addContent")
}, function (newTab, status, error) {
if (status === "SUCCESS") {
var body = component.get("v.moretabs");
component.set("v.moretabs", newTab);
} else {
throw new Error(error);
}
});
},
addContent : function(component, event) {
var tab = event.getSource();
switch (tab.get('v.id')){
case 'new':
// Display a badge in the tab content.
// You can replace lightning:badge with a custom component.
$A.createComponent("lightning:badge", {
"label": "NEW"
}, function (newContent, status, error) {
if (status === "SUCCESS") {
tab.set('v.body', newContent);
} else {
throw new Error(error);
}
});
break;
}
}
})
Alternatively, you can conditionally display a tab using aura:if. This example creates the tab on initialization but hides it until the
desired condition is met. You can display the hidden tab using cmp.set('v.displayTab',
!cmp.get('v.displayTab'));.
<aura:component>
<aura:attribute name="displayTab" type="Boolean" default="false" />
<lightning:tabset>
<aura:if isTrue="{! v.displayTab }">
<lightning:tab label="My Hidden Tab">
Your content here
</lightning:tab>
</aura:if>
<!-- Your other lightning:tab components here -->
559
Reference lightning:tabset (Beta)
</lightning:tabset>
</aura:component>
After updating the tab ID to the new value, display the corresponding tab by updating the value on selectedTabId.
({
handleClick: function(cmp) {
cmp.set("v.tabId", "3");
},
handleChange: function(cmp) {
//Display content on the Item Three tab
var selected = cmp.get("v.tabId");
cmp.find("tabs").set("v.selectedTabId", selected);
}
})
Usage Considerations
When you load more tabs than can fit the width of the view port, the tabset provides navigation buttons for the overflow tabs.
This component creates its body during runtime. You won’t be able to reference the component during initialization. You can set your
content using value binding with component attributes instead.
For example, you can't create a lightning:select component in a tabset by loading the list of options dynamically during
initialization using the init handler. However, you can create the list of options by binding the component attribute to the values. By
default, the option's value attribute is given the same value as the option passed to it unless you explicitly assign a value to it.
<aura:component>
<aura:attribute name="opts" type="List" default="['red', 'blue', 'green']" />
<lightning:tabset>
<lightning:tab label="View Options">
<lightning:select name="colors" label="Select a color:">
<aura:iteration items="{!v.opts}" var="option">
<option>{! option }</option>
</iteration>
560
Reference lightning:textarea
</lightning:select>
</lightning:tab>
</lightning:tabset>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body ComponentDefRef[] The body of the component. This could be one or more lightning:tab
components.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
variant String The variant changes the appearance of the tabset. Accepted variants are
default, scoped, and vertical.
selectedTabId String Allows you to set a specific tab to open by default. If this attribute is not
used, the first tab opens by default.
onselect Action The action that will run when the tab is clicked.
lightning:textarea
Represents a multiline text input.
A lightning:textarea component creates an HTML textarea element for entering multi-line text input. A text area holds
an unlimited number of characters.
This component inherits styling from textarea in the Lightning Design System.
The rows and cols HTML attributes are not supported. To apply a custom height and width for the text area, use the class
attribute. To set the input for the text area, set its value using the value attribute. Setting this value overwrites any initial value that's
provided.
The following example creates a text area with a maximum length of 300 characters.
<lightning:textarea name="myTextArea" value="initial value"
label="What are you thinking about?" maxlength="300" />
You can define a client-side controller action to handle input events like onblur, onfocus, and onchange. For example, to handle
a change event on the component, use the onchange attribute.
<lightning:textarea name="myTextArea" value="initial value"
label="What are you thinking about?" onchange="{!c.countLength}" />
Input Validation
Client-side input validation is available for this component. Set a maximum length using the maxlength attribute or a minimum
length using the minlength attribute. You can make the text area a required field by setting required="true". An error
message is automatically displayed in the following cases:
• A required field is empty when required is set to true.
561
Reference lightning:textarea
• The input value contains fewer characters than that specified by the minlength attribute.
• The input value contains more characters than that specified by the maxlength attribute.
To check the validity states of an input, use the validity attribute, which is based on the ValidityState object. You can access
the validity states in your client-side controller. This validity attribute returns an object with boolean properties. See
lightning:input for more information.
You can override the default message by providing your own values for messageWhenValueMissing, messageWhenBadInput,
or messageWhenTooLong.
For example,
<lightning:textarea name="myText" required="true" label="Your Name"
messageWhenValueMissing="This field is required."/>
Accessibility
You must provide a text label for accessibility to make the information available to assistive technology. The label attribute creates an
HTML label element for your input component. To hide a label from view and make it available to assistive technology, use the
label-hidden variant.
Methods
This component supports the following methods.
focus(): Sets the focus on the element.
blur(): Removes focus from the textarea element.
showHelpMessageIfInvalid(): Shows the help message if the form control is in an invalid state.
Attributes
Attribute Name Attribute Type Description Required?
accesskey String Specifies a shortcut key to activate or focus an element.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
disabled Boolean Specifies that an input element should be disabled. This value defaults
to false.
label String Text that describes the desired textarea input. Yes
messageWhenTooLong String Error message to be displayed when the value is too long.
562
Reference lightning:tile
onfocus Action The action triggered when the element receives focus.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
readonly Boolean Specifies that an input field is read-only. This value defaults to false.
required Boolean Specifies that an input field must be filled out before submitting the form.
This value defaults to false.
tabindex Integer Specifies the tab order of an element (when the tab button is used for
navigating).
title String Displays tooltip text when the mouse moves over the element.
validity Object Represents the validity states that an element can be in, with respect to
constraint validation.
value String The value of the textarea, also used as the default value during init.
variant String The variant changes the appearance of an input field. Accepted variants
include standard and label-hidden. This value defaults to standard.
lightning:tile
A grouping of related information associated with a record.
A lightning:tile component groups related information associated with a record. The information can be actionable and paired
with a figure, such as a lightning:icon or lightning:avatar component.
Use the class attributes to customize the styling. For example, providing the slds-tile_board class creates the board
variant. To style the tile body, use the Lightning Design System helper classes.
This component inherits styling from tiles in the Lightning Design System.
Here is an example.
<aura:component>
<lightning:tile label="Lightning component team" href="/path/to/somewhere">
<p class="slds-truncate" title="7 Members">7 Members</p>
</lightning:tile>
</aura:component>
To insert an icon or avatar, pass it into the media attribute. You can create a tile with an icon using definition lists. This example aligns
an icon and some text using helper classes like slds-dl_horizontal.
<aura:component>
<lightning:tile label="Salesforce UX" href="/path/to/somewhere">
<aura:set attribute="media">
<lightning:icon iconName="standard:groups"/>
</aura:set>
563
Reference lightning:tile
<dl class="slds-dl_horizontal">
<dt class="slds-dl_horizontal__label">
<p class="slds-truncate" title="Company">Company:</p>
</dt>
<dd class="slds-dl_horizontal__detail slds-tile__meta">
<p class="slds-truncate" title="Salesforce">Salesforce</p>
</dd>
<dt class="slds-dl_horizontal__label">
<p class="slds-truncate" title="Email">Email:</p>
</dt>
<dd class="slds-dl_horizontal__detail slds-tile__meta">
<p class="slds-truncate"
title="salesforce-ux@salesforce.com">salesforce-ux@salesforce.com</p>
</dd>
</dl>
</lightning:tile>
</aura:component>
You can also create a list of tiles with avatars using an unordered list, as shown in this example.
<aura:component>
<ul class="slds-has-dividers_bottom-space">
<li class="slds-item">
<lightning:tile label="Astro" href="/path/to/somewhere">
<aura:set attribute="media">
<lightning:avatar src="/path/to/img" alternativeText="Astro"/>
</aura:set>
<ul class="slds-list_horizontal slds-has-dividers_right">
<li class="slds-item">Trailblazer, Salesforce</li>
<li class="slds-item">Trailhead Explorer</li>
</ul>
</lightning:tile>
</li>
<!-- More list items here -->
</ul>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component’s base
classes.
title String Displays tooltip text when the mouse moves over the element.
href String The URL of the page that the link goes to.
label String The text label that displays in the tile and hover text. Yes
media Component[] The icon or figure that's displayed next to the textual information.
564
Reference lightning:tree
lightning:tree
Displays a nested tree. This component requires API version 41.0 and later.
A lightning:tree component displays visualization of a structural hierarchy, such as a sitemap for a website or a role hierarchy
in an organization. Items are displayed as hyperlinks and items in the hierarchy can be nested. Items with nested items are also known
as branches.
This component inherits styling from trees in the Lightning Design System.
To create a tree, pass in an array of key-value pairs to the items attribute.
name string The unique name for the item for the onselect event handler to
return the tree item that was clicked.
565
Reference lightning:tree
"name": "4",
"expanded": true,
"items" : []
}]
}]
}, {
"label": "Eastern Sales Director",
"name": "5",
"expanded": false,
"items": [{
"label": "Easter Sales Manager",
"name": "6",
"expanded": true,
"items" :[{
"label": "NY Sales Rep",
"name": "7",
"expanded": true,
"items" : []
}, {
"label": "MA Sales Rep",
"name": "8",
"expanded": true,
"items" : []
}]
}]
}];
cmp.set('v.items', items);
}
})
To retrieve the selected item Id, use the onselect attribute and bind it to your event handler, which is shown by handleSelect()
in the next example. The select event is also fired when you select an item with an href value.
({
handleSelect: function (cmp, event, helper) {
//return name of selected tree item
var myName = event.getParam('name');
alert("You selected: " + myName);
}
})
You can add or remove items in a tree. Let's say you have a tree that looks like this.
var items = [{
label: "Go to Record 1",
href: "#record1",
items: []
},{
label: "Go to Record 2",
href: "#record2",
items: []
}, {
label: "Go to Record 3",
href: "#record3",
566
Reference lightning:treeGrid
items: []
}];
When providing an href value to an item, the onselect event handler is triggered before navigating to the hyperlink.
Accessibility
You can use the keyboard to navigate the tree. Tab into the tree and use the Up and Down Arrow key to focus on tree items. To collapse
an expanded branch, press the Left Arrow key. To expand a branch, press the Right Arrow key. Pressing the Enter key or Space Bar is
similar to an onclick event, and performs the default action on the item.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
items Object An array of key-value pairs that describe the tree. Keys include label,
name, disabled, expanded, and items.
lightning:treeGrid
Displays a hierarchical view of data in a table. This component requires API version 42.0 and later.
A lightning:treeGrid component displays hierarchical data in a table. Its appearance resembles lightning:datatable,
with the exception that each row can be expanded to reveal a nested group of items. Rows that contain nested data display a chevron
567
Reference lightning:treeGrid
icon to denote that they can be expanded or collapsed. Each column can be displayed based on the data type. For example, a phone
number is displayed as a hyperlink with the tel: URL scheme by specifying the phone type. The default type is text.
This component inherits styling from trees in the Lightning Design System.
Inline editing and sorting of columns are not supported. Supported features include:
• Displaying and formatting of columns with appropriate data types
• Header-level actions
• Infinite scrolling of rows
• Row-level actions
• Resizing of columns
• Selecting of rows
• Text wrapping and clipping
Initialize your data using the data, columns, and keyField attributes via the init handler. This example creates a table with
5 columns, where the first column displays a checkbox for row selection. Selecting the checkbox enables you to select the entire row of
data and triggers the onrowselection event handler. The expandedRows attribute is optional, which expands nested items
on a row when provided.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.init}" />
<aura:attribute name="gridColumns" type="List" />
<aura:attribute name="gridData" type="Object" />
<aura:attribute name="gridExpandedRows" type="Object" />
<lightning:treeGrid
columns="{! v.gridColumns }"
data="{! v.gridData }"
expandedRows="{! v.gridExpandedRows }"
keyField="name"
aura:id="mytree"
/>
</aura:component>
The client-side controller creates selectable rows with or without nested data. The Account Owner column displays labels with an
associated URL.
({
init: function (cmp) {
var columns = [
{
type: 'text',
fieldName: 'accountName',
label: 'Account Name'
},
{
type: 'number',
fieldName: 'employees',
label: 'Employees'
},
{
type: 'phone',
fieldName: 'phone',
label: 'Phone Number'
},
568
Reference lightning:treeGrid
{
type: 'url',
fieldName: 'accountOwner',
label: 'Account Owner',
typeAttributes: {
label: { fieldName: 'accountOwnerName' }
}
}
];
cmp.set('v.gridColumns', columns);
var nestedData = [
{
"name": "123555",
"accountName": "Rewis Inc",
"employees": 3100,
"phone": "837-555-1212",
"accountOwner": "http://sfdc.co/jane-doe",
"accountOwnerName": "Jane Doe"
},
{
"name": "123556",
"accountName": "Acme Corporation",
"employees": 10000,
"phone": "837-555-1212",
"accountOwner": "http://sfdc.co/john-doe",
"accountOwnerName": "John Doe",
"_children": [
{
"name": "123556-A",
"accountName": "Acme Corporation (Bay Area)",
"employees": 3000,
"phone": "837-555-1212",
"accountOwner": "http://sfdc.co/john-doe",
"accountOwnerName": "John Doe",
"_children": [
{
"name": "123556-A-A",
"accountName": "Acme Corporation (Oakland)",
"employees": 745,
"phone": "837-555-1212",
"accountOwner": "http://sfdc.co/john-doe",
"accountOwnerName": "John Doe"
},
{
"name": "123556-A-B",
"accountName": "Acme Corporation (San Francisco)",
"employees": 578,
"phone": "837-555-1212",
"accountOwner": "http://sfdc.co/jane-doe",
"accountOwnerName": "Jane Doe"
}
]
}
]
569
Reference lightning:treeGrid
},
];
cmp.set('v.gridData', nestedData);
var expandedRows = ["123556"];
cmp.set('v.gridExpandedRows', expandedRows);
}
})
To retrieve which rows are currently expanded, use the getCurrentExpandedRows() method.
({
getExpandedRows: function(cmp, event, helper) {
cmp.set('v.currentExpandedRows', "");
var treeGridCmp = cmp.find('mytree');
cmp.set('v.currentExpandedRows', treeGridCmp.getCurrentExpandedRows().toString());
}
})
Additionally, you can toggle nested items using expandAll() and collapseAll(). For example, you want to expand all nested
items.
({
expandAllRows: function(cmp, event) {
var tree = cmp.find('mytree');
tree.expandAll();
}
})
return accountcontacts;
}
}
Wire this up to your component via the controller attribute. Make sure keyField is set to Id since this is the unique identifier for
accounts.
<aura:componentcontroller="AccountController">
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="gridColumns" type="List" />
<aura:attribute name="gridData" type="Object" />
<lightning:treeGrid columns="{! v.gridColumns }"
data="{! v.gridData }"
keyField="Id"
aura:id="mytree"
570
Reference lightning:treeGrid
/>
</aura:component>
The client-side controller defines the columns and calls a helper function to load the accounts and contact data.
({
doInit: function (cmp, event, helper) {
cmp.set('v.gridColumns', [
{label: 'Account Name', fieldName: 'Name', type: 'text'},
{label: 'Phone', fieldName: 'Phone', type: 'phone'},
]);
helper.getAcctContacts(cmp);
}
})
The helper function calls the Apex controller to query record data and set the response data on the gridData attribute.
({
getAcctContacts : function (cmp) {
var action = cmp.get("c.getAccountContacts");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
var data = response.getReturnValue();
//Change "Contacts" key to "_children"
for(var i=0; i<data.length;i++) {
data[i]._children = data[i]['Contacts'];
delete data[i].Contacts;
}
cmp.set('v.gridData', data);
}
// error handling when state is "INCOMPLETE" or "ERROR"
});
$A.enqueueAction(action);
}
})
The table displays two columns, Account Name and Phone. Accounts with contacts are displayed with a chevron to denote that they
can be expanded to reveal those contacts.
Working with Column Data
Use the following column properties to customize your data.
fieldName string Required. The name that binds the columns properties to the
associated data. Each columns property must correspond to an
item in the data array.
type string Required. The data type to be used for data formatting. For more
information, see Formatting with Data Types.
571
Reference lightning:treeGrid
typeAttributes object Provides custom formatting with component attributes for the data
type. For example, currencyCode for the currency type. For
more information, see Formatting with Data Types.
actions object Appends a dropdown menu of actions to a column. You must pass
in a list of label-name pairs.
iconName string The 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.
572
Reference lightning:treeGrid
button Displays a button using disabled, iconName, iconPosition, label, name, title, variant
lightning:button
To customize the formatting based on the data type, pass in the attributes for the corresponding base Lightning component. For example,
pass in a custom currencyCode value to override the default currency code.
var columns = [
{label: 'Amount', fieldName: 'amount', type: 'currency', typeAttributes: { currencyCode:
'EUR' }}
// other column data
]
When using currency or date and time types, the default user locale is used when no locale formatting is provided. For more information
on attributes, see the corresponding component documentation.
Creating Header-Level and Row-Level Actions
573
Reference lightning:treeGrid
Header-level actions refer to tasks you can perform on a column of data, while row-level actions refer to tasks you can perform on a row
of data, such as updating or deleting the row. Creating actions in lightning:treeGrid is similar to creating actions in
lightning:datatable. For more information, see the lightning:datatable documentation.
Asynchronous Loading of Nested Items
If you have a large number of nested items that would delay the loading of your data, consider loading your nested items asynchronously.
The nested items are displayed only when you expand the particular row. To do so, initialize your data without nested items.
var mydata = [
{
"name": "123556-A",
"accountName": "Acme Corporation (Bay Area)",
:
:
"_children": []
}, //more data
];
Handle asynchronous loading of nested items when a row is expanded using the ontoggle action. Find the name of the row being
expanded and check if data for the nested items is already available before retrieving and displaying the nested items.
({
handleRowToggle: function(cmp, event, helper) {
var rowName = event.getParam('name');
var hasChildrenContent = event.getParam('hasChildrenContent');
if (!hasChildrenContent) {
// Retrieve and display the nested items
// by passing in the original data, row name, and data for the nested items
}
}
})
574
Reference lightning:treeGrid
hasChildrenContent Boolean Specifies whether any data is available for the nested items of this
row.
575
Reference lightning:utilityBarAPI
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
columns List Array of the columns object that's used to define the data types. Required
properties include 'label', 'dataKey', and 'type'. The default type is 'text'.
expandedRows List The array of unique row IDs that are expanded.
hideCheckboxColumn Boolean Hides or displays the checkbox column for row selection. To hide the
checkbox column, set hideCheckboxColumn to true. The default is false.
isLoading Boolean Specifies whether more data is being loaded and displays a spinner if so.
The default is false.
keyField String Required for better performance. Associates each row with a unique ID. Yes
maxColumnWidth Integer The maximum width for all columns. The default is 1000px.
minColumnWidth Integer The minimum width for all columns. The default is 50px.
onresize Action The action triggered when the table renders columns the first time and
every time its resized an specific column.
onrowaction Action The action triggered when an operation its clicked. By default its to closes
the actions menu.
ontoggle Action The action triggered when a row is toggled (expanded or collapsed).
ontoggleall Action The action triggered when all rows are toggled (expanded or collapsed).
resizeColumnDisabled Boolean Specifies whether column resizing is disabled. The default is false.
rowNumberOffset Integer Determines where to start counting the row number. The default is 0.
selectedRows List The array of unique row IDs that are selected.
showRowNumberColumn Boolean Hides or displays the row number column. To show the row number
column, set showRowNumberColumn to true. The default is false.
title String Displays tooltip text when the mouse moves over the element.
lightning:utilityBarAPI
The public API for the Utility Bar.
576
Reference lightning:utilityBarAPI
This component allows you to access methods for programmatically controlling a utility within the utility bar of a Lightning app. The
utility bar is a footer that gives users quick access to frequently used tools and components. Each utility is a single-column Lightning
page that includes a standard or custom Lightning component.
To access the methods, create an instance of the lightning:utilityBarAPI component inside of your utility and assign an
aura:id attribute to it.
<lightning:utilityBarAPI aura:id="utilitybar"/>
This example sets the icon of a utility to the SLDS “insert tag field” icon when the button is clicked.
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
<lightning:utilityBarAPI aura:id="utilitybar" />
<lightning:button label="Set Utility Icon" onclick="{! c.setUtilityIcon }" />
</aura:component>
Methods
This component supports the following methods. Most methods take only one argument, a JSON array of parameters. The utilityId
parameter is only optional if within a utility itself. For more information on these methods, see the Console Developer Guide.
getEnclosingUtilityId()
Returns a Promise. Success resolves to the enclosing utilityId or false if not within a utility. The Promise will be rejected on error.
getUtilityInfo({utilityId})
• utilityId (string): Optional. The ID of the utility for which to get info.
Returns a Promise. Success resolves to a utilityInfo object. The Promise will be rejected on error.
getAllUtilityInfo()
Returns a Promise. Success resolves to an array of utilityInfo objects. The Promise will be rejected on error.
minimizeUtility({utilityId})
• utilityId (string): Optional. The ID of the utility for which to minimize.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
openUtility({utilityId})
• utilityId (string): Optional. The ID of the utility for which to open.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setPanelHeaderIcon({icon, utilityId})
• icon (string): An SLDS utility icon key. This is displayed in the utility panel. See a full list of utility icon keys on the SLDS reference
site.
• utilityId (string): Optional. The ID of the utility for which to set the panel header icon on.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setPanelHeaderLabel({label, utilityId})
577
Reference lightning:utilityBarAPI
• label (string): The label of the utility displayed in the panel header.
• utilityId (string): Optional. The ID of the utility for which to set the panel header label on.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setPanelHeight({heightPX, utilityId})
• heightPX (integer): The height of the utility panel in pixels.
• utilityId (string): Optional. The ID of the utility for which to set the panel height on.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setPanelWidth({widthPX, utilityId})
• widthPX (integer): The width of the utility panel in pixels.
• utilityId (string): Optional. The ID of the utility for which to set the panel width on.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setUtilityHighlighted({highlighted, utilityId})
• highlighted (boolean): Whether the utility is highlighted. Makes a utility more prominent by giving it a different background
color.
• utilityId (string): Optional. The ID of the utility for which to set highlighted.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setUtilityIcon({icon, utilityId})
• icon (string): An SLDS utility icon key. This is displayed in the utility bar. See a full list of utility icon keys on the SLDS reference site.
• utilityId (string): Optional. The ID of the utility for which to set the icon on.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
setUtilityLabel({label, utilityId})
• label (string): The label of the utility. This is displayed in the utility bar.
• utilityId (string): Optional. The ID of the utility for which to set the label on.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
toggleModalMode({enableModalMode, utilityId})
• enableModalMode (boolean): Whether to enable the utility's modal mode. While in modal mode, an overlay is shown over the
whole app that blocks usage while the utility panel is still visible.
• utilityId (string): Optional. The ID of the utility for which to toggle modal mode.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
578
Reference lightning:verticalNavigation
lightning:verticalNavigation
Represents a vertical list of links that either take the user to another page or parts of the page the user is in. This component requires
API version 41.0 and later.
A lightning:verticalNavigation component represents a list of links that's only one level deep, with support for overflow
sections that collapse and expand. The overflow section must be created using lightning:verticalNavigationOverflow
and does not adjust automatically based on the view port.
This component inherits styling from vertical navigation in the Lightning Design System.
lightning:verticalNavigation is used together with these sub-components.
• lightning:verticalNavigationSection
• lightning:verticalNavigationItem
• lightning:verticalNavigationOverflow
• lightning:verticalNavigationItemBadge
• lightning:verticalNavigationItemIcon
This example creates a basic vertical navigation menu.
<aura:component>
<lightning:verticalNavigation>
<lightning:verticalNavigationSection label="Reports">
<lightning:verticalNavigationItem label="Recent" name="recent" />
<lightning:verticalNavigationItem label="Created by Me" name="created" />
579
Reference lightning:verticalNavigation
To create a navigation menu via JavaScript, pass in a map of key-value pairs that define the sub-components. Here's an example that
creates a navigation menu during component initialization.
<aura:component>
<aura:attribute name="navigationData" type="Object" description="The list of sections
and their items." />
<aura:handler name="init" value="{! this }" action="{! c.init }" />
<lightning:verticalNavigation>
<aura:iteration items="{! v.navigationData }" var="section">
<lightning:verticalNavigationSection label="{! section.label }">
<aura:iteration items="{! section.items }" var="item">
<aura:if isTrue="{! !empty(item.icon) }">
<lightning:verticalNavigationItemIcon
label="{! item.label }"
name="{! item.name }"
iconName="{! item.icon }" />
<aura:set attribute="else">
<lightning:verticalNavigationItem
label="{! item.label }"
name="{! item.name }" />
</aura:set>
</aura:if>
</aura:iteration>
</lightning:verticalNavigationSection>
</aura:iteration>
</lightning:verticalNavigation>
</aura:component>
The client-side controller creates two sections with two navigation items each.
({
init: function (component) {
var sections = [
{
label: "Reports",
items: [
{
label: "Created by Me",
name: "default_created"
},
{
label: "Public Reports",
name: "default_public"
}
]
},
{
label: "Dashboards",
items: [
{
label: "Favorites",
name: "default_favorites",
icon: "utility:favorite"
},
{
580
Reference lightning:verticalNavigation
Usage Considerations
If you want a navigation menu that's more than one level deep, consider using lightning:tree instead.
The navigation menu takes up the full width of the screen. You can specify a width using CSS.
.THIS {
width: 320px;
}
Accessibility
Use the Tab and Shift+Tab keys to navigate up and down the menu. To expand or collapse an overflow section, press the Enter key or
Space Bar.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
compact Boolean Specify true to reduce spacing between navigation items. This value
defaults to false.
onbeforeselect Action Action fired before an item is selected. The event params include the
`name` of the selected item. To prevent the onselect handler from
running, call event.preventDefault() in the onbeforeselect handler.
onselect Action Action fired when an item is selected. The event params include the
`name` of the selected item.
shaded Boolean Specify true when the vertical navigation is sitting on top of a shaded
background. This value defaults to false.
title String Displays tooltip text when the mouse moves over the element.
581
Reference lightning:verticalNavigationItem
lightning:verticalNavigationItem
A text-only link within lightning:verticalNavigationSection or lightning:verticalNavigationOverflow. This component requires API version
41.0 and later.
A lightning:verticalNavigationItem component is a navigation item within lightning:verticalNavigation.
For more information, see lightning:verticalNavigation.
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
label String The text displayed for the navigation item. Yes
href String The URL of the page that the navigation item goes to.
lightning:verticalNavigationItemBadge
A link and badge within a lightning:verticalNavigationSection or lightning:verticalNavigationOverflow. This component requires API
version 41.0 and later.
A lightning:verticalNavigationItemBadge component is a navigation item that displays a numerical badge to the
right of the item label.
Here's an example that creates a navigation menu with an item containing a badge.
<aura:component>
<lightning:verticalNavigation selectedItem="recent">
<lightning:verticalNavigationSection label="Reports">
<lightning:verticalNavigationItemBadge label="Recent" name="recent"
badgeCount="3" />
<lightning:verticalNavigationItem label="Created by Me" name="usercreated" />
582
Reference lightning:verticalNavigationItemIcon
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
label String The text displayed for this navigation item. Yes
href String The URL of the page that the navigation item goes to.
badgeCount Integer The number to show inside the badge. If this value is zero the badge will
be hidden.
assistiveText String Assistive text describing the number in the badge. This is used to enhance
accessibility and is not displayed to the user.
lightning:verticalNavigationItemIcon
A link and icon within a lightning:verticalNavigationSection or lightning:verticalNavigationOverflow. This component requires API version
41.0 and later.
A lightning:verticalNavigationItemIcon component is a navigation item that displays an icon to the left of the item
label.
Here's an example that creates a navigation menu with icons on the navigation items.
<aura:component>
<lightning:verticalNavigation>
<lightning:verticalNavigationSection label="Reports">
<lightning:verticalNavigationItemIcon
label="Recent"
name="recent"
iconName="utility:clock" />
<lightning:verticalNavigationItemIcon
label="Created by Me"
name="created"
iconName="utility:user" />
<lightning:verticalNavigationItem
label="All Reports"
name="all"
iconName="utility:open_folder" />
</lightning:verticalNavigationSection>
</lightning:verticalNavigation>
</aura:component>
Icons from the Lightning Design System are supported. Visit https://lightningdesignsystem.com/icons to view available icons.
583
Reference lightning:verticalNavigationOverflow
Attributes
Attribute Name Attribute type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS class for the outer element, in addition to the component's base
classes.
title String Displays tooltip text when the mouse moves over the element.
label String The text displayed for this navigation item. Yes
href String The URL of the page that the navigation item goes to.
iconName String The Lightning Design System name of the icon. Names are written in the
format 'utility:down' where 'utility' is the category, and 'down' is the
specific icon to be displayed.
lightning:verticalNavigationOverflow
Represents an overflow of items from a preceding lightning:verticalNavigationSection, with the ability to toggle visibility. This component
requires API 41.0 and later.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
lightning:verticalNavigationSection
Represents a section within a lightning:verticalNavigation. This component requires API version 41.0 and later.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
584
Reference lightning:workspaceAPI
lightning:workspaceAPI
This is the Public API for accessing/manipulating workspaces (Tabs and Subtabs)
This component allows you to access methods for programmatically controlling workspace tabs and subtabs in a Lightning console
app. In Lightning console apps, records open as workspace tabs and their related records open as subtabs.
To access the methods, create an instance of the lightning:workspaceAPI component and assign an aura:id attribute to
it.
<lightning:workspaceAPI aura:id="workspace"/>
This example opens a new tab displaying the record with the given relative URL in the url attribute when the button is clicked.
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
<lightning:workspaceAPI aura:id="workspace" />
<lightning:button label="Open Tab" onclick="{! c.openTab }" />
</aura:component>
Methods
This component supports the following methods. Most methods take only one argument, a JSON array of parameters. For more information
on these methods, see the Console Developer Guide.
closeTab({tabId})
• tabId (string): ID of the workspace tab or subtab to close.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
focusTab({tabId})
• tabId (string): The ID of the workspace tab or subtab on which to focus.
Returns a Promise. Success resolves to true. The Promise will be rejected on error.
getAllTabInfo()
Returns a Promise. Success resolves to an array of tabInfo objects. The Promise will be rejected on error.
getFocusedTabInfo()
Returns a Promise. Success resolves to a tabInfo object. The Promise will be rejected on error.
getTabInfo({tabId})
• tabId (string): ID of the tab for which to retrieve the information.
Returns a Promise. Success resolves to a tabInfo object. The Promise will be rejected on error.
getTabURL({tabId})
• tabId (string): ID of the tab for which to retrieve the URL.
585
Reference lightning:workspaceAPI
Returns a Promise. Success resolves to the tab URL. The Promise will be rejected on error.
isSubtab({tabId})
• tabId (string): ID of the tab.
Returns a Promise. Success resolves to true if the tab is a subtab, false otherwise. The Promise will be rejected on error.
isConsoleNavigation()
Returns a Promise. Success resolves to true if console navigation is present, false otherwise. The Promise will be rejected on error.
getEnclosingTabId()
Returns a Promise. Success resolves to the enclosing tabId or false if not within a tab. The Promise will be rejected on error.
openSubtab({parentTabId, url, recordId, focus})
• parentTabId (string): ID of the workspace tab within which the new subtab should open.
• url (string): Optional. The URL representing the content of the new subtab. URLs can be either relative or absolute.
• recordId (string): Optional. A record ID representing the content of the new subtab.
• focus (boolean): Optional. Specifies whether the new subtab has focus.
Returns a Promise. Success resolves to the tabId of the subtab. The Promise will be rejected on error.
openTab({url, recordId, focus})
• url (string): Optional. The URL representing the content of the new tab. URLs can be either relative or absolute.
• recordId (string): Optional. A record ID representing the content of the new tab.
• focus (boolean): Optional. Specifies whether the new tab has focus.
• overrideNavRules (boolean): Optional. Specifies whether to override nav rules when opening the new tab.
Returns a Promise. Success resolves to the tabId of the workspace. The Promise will be rejected on error.
setTabIcon({tabId, icon, iconAlt})
• tabId (string): The ID of the tab for which to set the icon.
• icon (string): An SLDS icon key. See a full list of icon keys on the SLDS reference site.
• iconAlt (string): Optional. Alternative text for the icon.
Returns a Promise. Success resolves to a tabInfo object of the modified tab. The Promise will be rejected on error.
setTabLabel({tabId, label})
• tabId (string): The ID of the tab for which to set the label.
• label (string): The label of the workspace tab or subtab.
Returns a Promise. Success resolves to a tabInfo object of the modified tab. The Promise will be rejected on error.
setTabHighlighted({tabId, highlighted})
• tabId (string): The ID of the tab for which to highlight.
• highlighted (boolean): Specifies whether the new tab should be highlighted.
Returns a Promise. Success resolves to a tabInfo object of the modified tab. The Promise will be rejected on error.
586
Reference ltng:require
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
ltng:require
Loads scripts and stylesheets while maintaining dependency order. The styles are loaded in the order that they are listed. The styles only
load once if they are specified in multiple <ltng:require> tags in the same component or across different components.
ltng:require enables you to load external CSS and JavaScript libraries after you upload them as static resources.
<aura:component>
<ltng:require
styles="{!$Resource.SLDSv1 + '/assets/styles/lightning-design-system-ltng.css'}"
scripts="{!$Resource.jsLibraries + '/jsLibOne.js'}"
afterScriptsLoaded="{!c.scriptsLoaded}" />
</aura:component>
Due to a quirk in the way $Resource is parsed in expressions, use the join operator to include multiple $Resource references in a single
attribute. For example, if you have more than one JavaScript library to include into a component the scripts attribute should be something
like the following.
scripts="{!join(',',
$Resource.jsLibraries + '/jsLibOne.js',
$Resource.jsLibraries + '/jsLibTwo.js')}"
The comma-separated lists of resources are loaded in the order that they are entered in the scripts and styles attributes. The
afterScriptsLoaded action in the client-side controller is called after the scripts are loaded. To ensure encapsulation and
reusability, add the <ltng:require> tag to every .cmp or .app resource that uses the CSS or JavaScript library.
The resources only load once if they are specified in multiple <ltng:require> tags in the same component or across different
components.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
scripts String[] The set of scripts in dependency order that will be loaded.
styles String[] The set of style sheets in dependency order that will be loaded.
587
Reference ui:actionMenuItem
Events
Event Name Event Type Description
afterScriptsLoaded COMPONENT Fired when ltng:require has loaded all scripts listed in ltng:require.scripts
ui:actionMenuItem
A menu item that triggers an action. This component is nested in a ui:menu component.
A ui:actionMenuItem component represents a menu list item that triggers an action when clicked. Use aura:iteration
to iterate over a list of values and display the menu items. A ui:menuTriggerLink component displays and hides your menu
items.
<aura:attribute name="status" type="String[]" default="Open, Closed, Closed Won, Any"/>
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Opportunity Status"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<aura:iteration items="{!v.status}" var="s">
<ui:actionMenuItem label="{!s}" click="{!c.doSomething}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
hideMenuAfterSelected Boolean Set to true to hide menu after the menu item is selected.
selected Boolean The status of the menu item. True means this menu item is selected;
False is not selected.
type String The concrete type of the menu item. Accepted values are 'action',
'checkbox', 'radio', 'separator' or any namespaced component descriptor,
e.g. ns:xxxxmenuItem.
588
Reference ui:button
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
ui:button
Represents a button element.
A ui:button component represents a button element that executes an action defined by a controller. To apply Lightning Design
System styling, we recommend that you use lightning:button instead of ui:button.
Clicking the button triggers the client-side controller method set for the press event. The button can be created in several ways.
A text-only button has only the label attribute set on it.
<ui:button label="Find"/>
An image-only button uses both the label and labelClass attributes with CSS.
<!-- Component markup -->
<ui:button label="Find" labelClass="assistiveText" class="img" />
589
Reference ui:button
The assistiveText class hides the label from view but makes it available to assistive technologies. To create a button with both
image and text, use the label attribute and add styles for the button.
<!-- Component markup -->
<ui:button label="Find" />
The previous markup for a button with text and image results in the following HTML.
<button class="button uiButton--default uiButton" accesskey type="button">
<span class="label bBody truncate" dir="ltr">Find</span>
</button>
This example shows a button that displays the input value you enter. To apply Lightning Design System styling, we recommend that
you use lightning:button instead of ui:button.
<aura:component access="global">
<ui:inputText aura:id="name" label="Enter Name:" placeholder="Your Name" />
<ui:button aura:id="button" buttonTitle="Click to see what you put into the field"
class="button" label="Click me" press="{!c.getInput}"/>
<ui:outputText aura:id="outName" value="" class="text"/>
</aura:component>
({
getInput : function(cmp, evt) {
var myName = cmp.find("name").get("v.value");
var myText = cmp.find("outName");
var greet = "Hi, " + myName;
myText.set("v.value", greet);
}
})
Attributes
Attribute Name Attribute Type Description Required?
accesskey String The keyboard access key that puts the button in focus. When the button
is in focus, pressing Enter clicks the button.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
buttonTitle String The text displayed in a tooltip when the mouse pointer hovers over the
button.
buttonType String Specifies the type of button. Possible values: reset, submit, or button.
This value defaults to button.
class String A CSS style to be attached to the button. This style is added in addition
to base styles output by the component.
590
Reference ui:checkboxMenuItem
label String The text displayed on the button. Corresponds to the value attribute of
the rendered HTML input element.
labelClass String A CSS style to be attached to the label. This style is added in addition to
base styles output by the component.
Events
Event Name Event Type Description
press COMPONENT The event fired when the button is clicked.
ui:checkboxMenuItem
A menu item with a checkbox that supports multiple selection and can be used to invoke an action. This component is nested in a
ui:menu component.
A ui:checkboxMenuItem component represents a menu list item that enables multiple selection. Use aura:iteration to
iterate over a list of values and display the menu items. A ui:menuTriggerLink component displays and hides your menu items.
<aura:attribute name="status" type="String[]" default="Open, Closed, Closed Won, Any"/>
<ui:menu>
<ui:menuTriggerLink aura:id="checkboxMenuLabel" label="Multiple selection"/>
<ui:menuList aura:id="checkboxMenu" class="checkboxMenu">
<aura:iteration items="{!v.status}" var="s">
<ui:checkboxMenuItem label="{!s}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
hideMenuAfterSelected Boolean Set to true to hide menu after the menu item is selected.
591
Reference ui:inputCheckbox
type String The concrete type of the menu item. Accepted values are 'action',
'checkbox', 'radio', 'separator' or any namespaced component descriptor,
e.g. ns:xxxxmenuItem.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
ui:inputCheckbox
Represents a checkbox. Its behavior can be configured using events such as click and change.
A ui:inputCheckbox component represents a checkbox whose state is controlled by the value and disabled attributes.
It's rendered as an HTML input tag of type checkbox. To render the output from a ui:inputCheckbox component, use the
ui:outputCheckbox component.
This is a basic set up of a checkbox.
<ui:inputCheckbox label="Reimbursed?"/>
592
Reference ui:inputCheckbox
The value attribute controls the state of a checkbox, and events such as click and change determine its behavior. This example
updates the checkbox CSS class on a click event.
<!-- Component Markup -->
<ui:inputCheckbox label="Color me" click="{!c.update}"/>
<aura:component>
<aura:attribute name="myBool" type="Boolean" default="true"/>
<ui:inputCheckbox aura:id="checkbox" label="Select?" change="{!c.onCheck}"/>
<p>Selected:</p>
<p><ui:outputText class="result" aura:id="checkResult" value="false" /></p>
<p>The following checkbox uses a component attribute to bind its value.</p>
<ui:outputCheckbox aura:id="output" value="{!v.myBool}"/>
</aura:component>
({
onCheck: function(cmp, evt) {
var checkCmp = cmp.find("checkbox");
resultCmp = cmp.find("checkResult");
resultCmp.set("v.value", ""+checkCmp.get("v.value"));
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
593
Reference ui:inputCheckbox
required Boolean Specifies whether the input is required. Default value is "false".
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change,click".
value Boolean Indicates whether the status of the option is selected. Default value is
“false”.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
594
Reference ui:inputCurrency
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputCurrency
An input field for entering a currency.
A ui:inputCurrency component represents an input field for a number as a currency, which is rendered as an HTML input
element of type text. It uses JavaScript's Number type MAX_SAFE_INTEGER and MIN_SAFE_INTEGER precision to determine the
supported number of digits, which is about 16 digits.
To apply Lightning Design System styling, we recommend that you use lightning:input with type="number" and
formatter="currency" instead of ui:inputCurrency. To render the output from a ui:inputCurrency component,
use the ui:outputCurrency component.
This is a basic set up of a ui:inputCurrency component, which renders an input field with the value $50.00 when the browser's
currency locale is $.
<ui:inputCurrency aura:id="amount" label="Amount" class="field" value="50"/>
To override the browser's locale, set the new format on the v.format attribute of the ui:inputCurrency component. This
example renders an input field with the value £50.00.
var curr = component.find("amount");
curr.set("v.format", '£#,###.00');
This example binds the value of a ui:inputCurrency component to ui:outputCurrency. To apply Lightning Design System
styling, we recommend that you use lightning:input with type="number" and formatter="currency" instead
of ui:inputCurrency. Similarly, we recommend using lightning:formattedNumber with style="currency"
instead of ui:outputCurrency.
<aura:component>
<aura:attribute name="myCurrency" type="integer" default="50"/>
<ui:inputCurrency aura:id="amount" label="Amount" class="field" value="{!v.myCurrency}"
updateOn="keyup"/>
You entered: <ui:outputCurrency value="{!v.myCurrency}"/>
</aura:component>
595
Reference ui:inputCurrency
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
format String The format of the number. For example, format=“.00” displays the number
followed by two decimal places. If not specified, the Locale default format
will be used.
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
596
Reference ui:inputDate
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputDate
An input field for entering a date.
A ui:inputDate component represents a date input field, which is rendered as an HTML input tag of type text on desktop.
To apply Lightning Design System styling, we recommend that you use lightning:input with type="date" instead of
ui:inputDate.
Web apps running on mobiles and tablets use an input field of type date for all browsers except Internet Explorer. The value is displayed
based on the locale of the browser, for example, MMM d, yyyy, which is returned by $Locale.dateFormat.
This is a basic set up of a date field with a date picker icon, which displays the field value Jan 30, 2014 based on the locale format.
On desktop, the input tag is wrapped in a form tag.
<ui:inputDate aura:id="dateField" label="Birthday" value="2014-01-30"
displayDatePicker="true"/>
597
Reference ui:inputDate
selecting a date on the date picker triggers the change handler on the component but the value is bound only on the blur event. This
example binds the date value to a value change handler.
<aura:component>
<aura:attribute name="myDate" type="Date" />
<!-- Value change handler -->
<aura:handler name="change" value="{!v.myDate}" action="{!c.handleValueChange}"/>
<ui:inputDate aura:id="mySelectedDate"
label="Select a date" displayDatePicker="true"
value="{!v.myDate}"/>
</aura:component>
This example sets today's date on a ui:inputDate component, retrieves its value, and displays it using ui:outputDate. To
apply Lightning Design System styling, we recommend that you use lightning:input with type="date" instead of
ui:inputDate. The init handler initializes and sets the date on the component.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="today" type="Date" default=""/>
({
doInit : function(component, event, helper) {
var today = new Date();
component.set('v.today', today.getFullYear() + "-" + (today.getMonth() + 1) + "-"
+ today.getDate());
},
598
Reference ui:inputDate
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
displayDatePicker Boolean Indicates if an icon that triggers the date picker is displayed in the field.
The default is false.
langLocale String Deprecated. The language locale used to format date time. It only allows
to use the value which is provided by Locale Value Provider, otherwise,
it falls back to the value of $Locale.langLocale. It will be removed in an
upcoming release.
required Boolean Specifies whether the input is required. Default value is "false".
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
599
Reference ui:inputDateTime
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputDateTime
An input field for entering a date and time.
A ui:inputDateTime component represents a date and time input field, which is rendered as an HTML input tag of type text
on desktop. To apply Lightning Design System styling, we recommend that you use lightning:input with type="datetime"
instead of ui:inputDateTime.
Web apps running on mobiles and tablets use an input field of type datetime for all browsers except Internet Explorer. The value is
displayed based on the locale of the browser, for example, MMM d, yyyy and h:mm:ss a, which is returned by
$Locale.dateFormat and $Locale.timeFormat.
This is a basic set up of a pair of date and time field with a date picker icon. The client-side controller sets the current date and time in
the fields. On desktop, the input tag is wrapped in a form tag; the date and time fields display as two separate fields. The time picker
displays a list of time in 30-minute increments.
<!-- Component markup -->
<aura:attribute name="today" type="DateTime" />
<ui:inputDateTime aura:id="expdate" label="Expense Date" class="form-control"
value="{!v.today}" displayDatePicker="true" />
600
Reference ui:inputDateTime
<ui:inputDateTime aura:id="mySelectedDateTime"
label="Select a date and time"
value="{!v.myDateTime}"/>
</aura:component>
This example retrieves the value of a ui:inputDateTime component and displays it using ui:outputDateTime. To apply
Lightning Design System styling, we recommend that you use lightning:input with type="datetime" instead of
ui:inputDateTime.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="today" type="Date" default=""/>
({
doInit : function(component, event, helper) {
var today = new Date();
component.set('v.today', today.getFullYear() + "-" + (today.getMonth() + 1) + "-"
+ today.getDate());
},
601
Reference ui:inputDateTime
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
displayDatePicker Boolean Indicates if an icon that triggers the date picker is displayed in the field.
The default is false.
langLocale String Deprecated. The language locale used to format date time. It only allows
to use the value which is provided by Locale Value Provider, otherwise,
it falls back to the value of $Locale.langLocale. It will be removed in an
upcoming release.
required Boolean Specifies whether the input is required. Default value is "false".
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
602
Reference ui:inputDefaultError
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputDefaultError
The default implementation of field-level errors, which iterates over the value and displays the message.
ui:inputDefaultError is the default error handling for your input components. This component displays as a list of errors below
the field. Field-level error messages can be added using set("v.errors"). You can use the error atribute to show the error message.
For example, this component validates if the input is a number.
<aura:component>
Enter a number: <ui:inputNumber aura:id="inputCmp" label="number"/>
<ui:button label="Submit" press="{!c.doAction}"/>
</aura:component>
603
Reference ui:inputDefaultError
}
}
Alternatively, you can provide your own ui:inputDefaultError component. This example returns an error message if the
warnings attribute contains any messages.
<aura:component>
<aura:attribute name="warnings" type="String[]" description="Warnings for input
text"/>
Enter a number: <ui:inputNumber aura:id="inputCmp" label="number"/>
<ui:button label="Submit" press="{!c.doAction}"/>
<ui:inputDefaultError aura:id="number" value="{!v.warnings}" />
</aura:component>
This client-side controller diplays an error by adding a string to the warnings attribute.
doAction : function(component, event) {
var inputCmp = component.find("inputCmp");
var value = inputCmp.get("v.value");
// is input numeric?
if (isNaN(value)) {
component.set("v.warnings", "Input is not a number");
} else {
// clear error
component.set("v.warnings", null);
}
}
This example shows a ui:inputText component with the default error handling, and a corresponding ui:outputText
component for text rendering.
<aura:component>
<ui:inputText aura:id="color" label="Enter some text: " placeholder="Blue" />
<ui:button label="Validate" press="{!c.checkInput}" />
<ui:outputText aura:id="outColor" value="" class="text"/>
</aura:component>
({
checkInput : function(cmp) {
var colorCmp = cmp.find("color");
var myColor = colorCmp.get("v.value");
if (!myColor) {
colorCmp.set("v.errors", [{message:"Enter some text"}]);
}
else {
colorCmp.set("v.errors", null);
}
604
Reference ui:inputEmail
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:inputEmail
Represents an input field for entering an email address.
A ui:inputEmail component represents an email input field, which is rendered as an HTML input tag of type email. To apply
Lightning Design System styling, we recommend that you use lightning:input with type="email" instead of
ui:inputEmail.
This is a basic set up of an email field.
<ui:inputEmail aura:id="email" label="Email" placeholder="abc@email.com"/>
605
Reference ui:inputEmail
This example retrieves the value of a ui:inputEmail component and displays it using ui:outputEmail. To apply Lightning
Design System styling, we recommend that you use lightning:input with type="email" instead of ui:inputEmail.
Similarly, we recommend using lightning:formattedEmail instead of ui:outputEmail.
<aura:component>
<ui:inputEmail aura:id="email" label="Email" class="field" value="manager@email.com"/>
</aura:component>
({
setOutput : function(component, event, helper) {
var cmpMsg = component.find("msg");
$A.util.removeClass(cmpMsg, 'hide');
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
606
Reference ui:inputEmail
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
607
Reference ui:inputNumber
ui:inputNumber
An input field for entering a number, taking advantage of client input assistance and validation when available.
A ui:inputNumber component represents a number input field, which is rendered as an HTML input element of type text.
It uses JavaScript’s Number type MAX_SAFE_INTEGER and MIN_SAFE_INTEGER precision to determine the supported number of digits,
which is about 16 digits. Numbers outside of the precision can get truncated or rounded.
To apply Lightning Design System styling, we recommend that you use lightning:input with type="number" instead of
ui:inputNumber. To render the output from a ui:inputNumber component, use the ui:outputEmail component.
Similarly, we recommend using lightning:formattedNumber instead of ui:outputNumber.
This example shows a number field, which displays a value of 10.
<aura:attribute name="num" type="integer" default="10"/>
<ui:inputNumber aura:id="num" label="Age" value="{!v.num}"/>
To render the output from a ui:inputNumber component, use the ui:outputNumber component. When providing a number
value with commas, use type="integer". This example returns 100,000.
<aura:attribute name="number" type="integer" default="100,000"/>
<ui:inputNumber label="Number" value="{!v.number}"/>
For type="string", provide the number without commas for the output to be formatted accordingly. This example also returns
100,000.
This example binds the value of a ui:inputNumber component to ui:outputNumber. To apply Lightning Design System
styling, we recommend that you use lightning:input with type="number" instead of ui:inputNumber. Similarly, we
recommend using lightning:formattedNumber instead of ui:outputNumber.
<aura:component>
<aura:attribute name="myNumber" type="integer" default="10"/>
<ui:inputNumber label="Enter a number: " value="{!v.myNumber}" updateOn="keyup"/> <br/>
608
Reference ui:inputNumber
<ui:outputNumber value="{!v.myNumber}"/>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
format String The format of the number. For example, format=“.00” displays the number
followed by two decimal places. If not specified, the Locale default format
will be used.
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
609
Reference ui:inputPhone
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputPhone
Represents an input field for entering a telephone number.
A ui:inputPhone component represents an input field for entering a phone number, which is rendered as an HTML input tag
of type tel. To apply Lightning Design System styling, we recommend that you use lightning:input with type="tel"
instead of ui:inputPhone.
This example shows a phone field, which displays the specified phone number.
<ui:inputPhone label="Phone" value="415-123-4567" />
610
Reference ui:inputPhone
</label>
<input class="input" type="tel">
</div>
This example retrieves the value of a ui:inputPhone component and displays it using ui:outputPhone. To apply Lightning
Design System styling, we recommend that you use lightning:input with type="tel" instead of ui:inputPhone.
Similarly, we recommend using lightning:formattedPhone instead of ui:outputPhone.
<aura:component>
<ui:inputPhone aura:id="phone" label="Phone Number" class="field" value="415-123-4567"
/>
<ui:button class="btn" label="Submit" press="{!c.setOutput}"/>
({
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
611
Reference ui:inputPhone
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
612
Reference ui:inputRadio
ui:inputRadio
The radio button used in the input.
A ui:inputRadio component represents a radio button whose state is controlled by the value and disabled attributes. It's
rendered as an HTML input tag of type radio. To apply Lightning Design System styling, we recommend that you use
lightning:radioGroup instead of ui:inputRadio.
To group your radio buttons together, specify the name attribute with a unique name.
This is a basic set up of a radio button.
<ui:inputRadio label="Yes"/>
This example retrieves the value of a selected ui:inputRadio component. To apply Lightning Design System styling, we recommend
that you use lightning:radioGroup instead of ui:inputRadio.
<aura:component>
<aura:attribute name="stages" type="String[]" default="Any,Open,Closed,Closed Won"/>
<aura:iteration items="{!v.stages}" var="stage">
<ui:inputRadio label="{!stage}" change="{!c.onRadio}" />
</aura:iteration>
<b>Selected Item:</b>
<p><ui:outputText class="result" aura:id="radioResult" value="" /></p>
</aura:component>
({
onRadio: function(cmp, evt) {
613
Reference ui:inputRadio
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether this radio button should be displayed in a disabled
state. Disabled radio buttons can't be clicked. Default value is "false".
required Boolean Specifies whether the input is required. Default value is "false".
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
value Boolean Indicates whether the status of the option is selected. Default value is
“false”.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
614
Reference ui:inputRichText
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputRichText
An input field for entering rich text. This component is not supported by LockerService.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
615
Reference ui:inputRichText
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
height String The height of the editing area (that includes the editor content). This can
be an integer, for pixel sizes, or any CSS-defined length unit.
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML
textarea element.
readonly Boolean Specifies whether the text area should be rendered as read-only. Default
value is “false”.
required Boolean Specifies whether the input is required. Default value is "false".
resizable Boolean Specifies whether or not the textarea should be resizable. Defaults to
true.
rows Integer The height of the text area, which is defined by the number of rows to
display at a time. Default value is “2”.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
width String The editor UI outer width. This can be an integer, for pixel sizes, or any
CSS-defined unit. If isRichText is set to false, use the cols attribute instead.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
616
Reference ui:inputSecret
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputSecret
An input field for entering secret text with type password.
A ui:inputSecret component represents a password field, which is rendered as an HTML input tag of type password. To
apply Lightning Design System styling, we recommend that you use lightning:input with type="password" instead of
ui:inputSecret.
This is a basic set up of a password field.
<ui:inputSecret aura:id="secret" label="Pin" class="field" value="123456"/>
617
Reference ui:inputSecret
This example displays a ui:inputSecret component with a default value. To apply Lightning Design System styling, we recommend
that you use lightning:input with type="password" instead of ui:inputSecret.
<aura:component>
<ui:inputSecret aura:id="secret" label="Pin" class="field" value="123456"/>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
618
Reference ui:inputSelect
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputSelect
Represents a drop-down list with options.
A ui:inputSelect component is rendered as an HTML select element. To apply Lightning Design System styling, we recommend
that you use lightning:select instead of ui:inputSelect.
ui:inputSelect contains options, represented by the ui:inputSelectOption components. To enable multiple selections,
set multiple="true". To wire up any client-side logic when an input value is selected, use the change event.
<ui:inputSelect multiple="true">
<ui:inputSelectOption text="All Primary" label="All Contacts" value="true"/>
<ui:inputSelectOption text="All Primary" label="All Primary"/>
<ui:inputSelectOption text="All Secondary" label="All Secondary"/>
</ui:inputSelect>
v.value represents the option's HTML selected attribute, and v.text represents the option's HTML value attribute.
Generating Options with aura:iteration
619
Reference ui:inputSelect
You can use aura:iteration to iterate over a list of items to generate options. This example iterates over a list of items and handles
the change event.
<aura:attribute name="contactLevel" type="String[]" default="Primary Contact, Secondary
Contact, Other"/>
<ui:inputSelect aura:id="levels" label="Contact Levels" change="{!c.onSelectChange}">
When the selected option changes, this client-side controller retrieves the new text value.
onSelectChange : function(component, event, helper) {
var selected = component.find("levels").get("v.value");
//do something else
}
The following client-side controller generates options using the options attribute on the ui:inputSelect component. v.options
takes in the list of objects and converts them into list options. The opts object constructs InputOption objects to create the
ui:inputSelectOptions components within ui:inputSelect. Although the sample code generates the options during
initialization, the list of options can be modified anytime when you manipulate the list in v.options. The component automatically
updates itself and rerenders with the new options.
({
doInit : function(cmp) {
var opts = [
{ class: "optionClass", label: "Option1", value: "opt1", selected: "true" },
{ class: "optionClass", label: "Option2", value: "opt2" },
{ class: "optionClass", label: "Option3", value: "opt3" }
];
cmp.find("InputSelectDynamic").set("v.options", opts);
}
})
class is a reserved keyword that might not work with older versions of Internet Explorer. We recommend using "class" with
double quotes. If you’re reusing the same set of options on multiple drop-down lists, use different attributes for each set of options.
Otherwise, selecting a different option in one list also updates other list options bound to the same attribute.
<aura:attribute name="options1" type="String" />
<aura:attribute name="options2" type="String" />
<ui:inputSelect aura:id="Select1" label="Select1" options="{!v.options1}" />
<ui:inputSelect aura:id="Select2" label="Select2" options="{!v.options2}" />
620
Reference ui:inputSelect
This example displays a drop-down list with single and multiple selection enabled, and another with dynamically generated list options.
It retrieves the selected value of a ui:inputSelect component. To apply Lightning Design System styling, we recommend that
you use lightning:select instead of ui:inputSelect.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="row">
<p class="title">Single Selection</p>
<ui:inputSelect class="single" aura:id="InputSelectSingle"
change="{!c.onSingleSelectChange}">
<ui:inputSelectOption text="Any"/>
<ui:inputSelectOption text="Open" value="true"/>
<ui:inputSelectOption text="Closed"/>
<ui:inputSelectOption text="Closed Won"/>
<ui:inputSelectOption text="Prospecting"/>
<ui:inputSelectOption text="Qualification"/>
<ui:inputSelectOption text="Needs Analysis"/>
<ui:inputSelectOption text="Closed Lost"/>
</ui:inputSelect>
<p>Selected Item:</p>
<p><ui:outputText class="result" aura:id="singleResult" value="" /></p>
</div>
<div class="row">
<p class="title">Multiple Selection</p>
<ui:inputSelect multiple="true" class="multiple" aura:id="InputSelectMultiple"
change="{!c.onMultiSelectChange}">
<ui:inputSelectOption text="Any"/>
<ui:inputSelectOption text="Open"/>
<ui:inputSelectOption text="Closed"/>
<ui:inputSelectOption text="Closed Won"/>
<ui:inputSelectOption text="Prospecting"/>
<ui:inputSelectOption text="Qualification"/>
<ui:inputSelectOption text="Needs Analysis"/>
<ui:inputSelectOption text="Closed Lost"/>
</ui:inputSelect>
<p>Selected Items:</p>
<p><ui:outputText class="result" aura:id="multiResult" value="" /></p>
</div>
<div class="row">
<p class="title">Dynamic Option Generation</p>
<ui:inputSelect label="Select me: " class="dynamic" aura:id="InputSelectDynamic"
change="{!c.onChange}" />
<p>Selected Items:</p>
<p><ui:outputText class="result" aura:id="dynamicResult" value="" /></p>
</div>
621
Reference ui:inputSelect
</aura:component>
({
doInit : function(cmp) {
// Initialize input select options
var opts = [
{ "class": "optionClass", label: "Option1", value: "opt1", selected: "true"
},
{ "class": "optionClass", label: "Option2", value: "opt2" },
{ "class": "optionClass", label: "Option3", value: "opt3" }
];
cmp.find("InputSelectDynamic").set("v.options", opts);
},
onSingleSelectChange: function(cmp) {
var selectCmp = cmp.find("InputSelectSingle");
var resultCmp = cmp.find("singleResult");
resultCmp.set("v.value", selectCmp.get("v.value"));
},
onMultiSelectChange: function(cmp) {
var selectCmp = cmp.find("InputSelectMultiple");
var resultCmp = cmp.find("multiResult");
resultCmp.set("v.value", selectCmp.get("v.value"));
},
onChange: function(cmp) {
var dynamicCmp = cmp.find("InputSelectDynamic");
var resultCmp = cmp.find("dynamicResult");
resultCmp.set("v.value", dynamicCmp.get("v.value"));
}
})
Usage Considerations
Using ui:inputSelect with Lightning Runtime for Flows is supported, but empty option labels are not supported. To create a
picklist field on an object and set an empty default value, use a formula inside the flow to substitute empty values to a value like
--EMPTY--. Using the substitute value ensures that the empty picklist value does not get replaced by the label of the picklist variable
created in the flow.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
622
Reference ui:inputSelect
multiple Boolean Specifies whether the input is a multiple select. Default value is “false”.
options List A list of options to use for the select. Note: setting this attribute will make
the component ignore v.body
required Boolean Specifies whether the input is required. Default value is "false".
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
623
Reference ui:inputSelectOption
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputSelectOption
An HTML option element that is nested in a ui:inputSelect component. Denotes the available options in the list.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
value Boolean Indicates whether the status of the option is selected. Default value is
“false”.
Events
Event Name Event Type Description
select COMPONENT The event fired when the user selects some text.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
624
Reference ui:inputText
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
click COMPONENT The event fired when the user clicks on the component.
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:inputText
Represents an input field suitable for entering a single line of free-form text.
A ui:inputText component represents a text input field, which is rendered as an HTML input tag of type text. To apply
Lightning Design System styling, we recommend that you use lightning:input instead of ui:inputText.
This is a basic set up of a text field.
<ui:inputText label="Expense Name" value="My Expense" required="true"/>
This example binds the value of a ui:inputText component to ui:outputText. To apply Lightning Design System styling,
we recommend that you use lightning:input instead of ui:inputText.
<aura:component>
<aura:attribute name="myText" type="string" default="Hello there!"/>
<ui:inputText label="Enter some text" class="field" value="{!v.myText}" updateOn="click"/>
625
Reference ui:inputText
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
626
Reference ui:inputTextArea
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:inputTextArea
An HTML textarea element that can be editable or read-only. Scroll bars may not appear on Chrome browsers in Android devices, but
you can select focus in the textarea to activate scrolling.
A ui:inputTextArea component represents a multi-line text input control, which is rendered as an HTML textarea tag. To
apply Lightning Design System styling, we recommend that you use lightning:textarea instead of ui:inputTextArea.
This is a basic set up of a ui:inputTextArea component.
<ui:inputTextArea aura:id="comments" label="Comments" value="My comments" rows="5"/>
This example retrieves the value of a ui:inputTextArea component and displays it using ui:outputTextArea. To apply
Lightning Design System styling, we recommend that you use lightning:textarea instead of ui:inputTextArea.
<aura:component>
<ui:inputTextArea aura:id="comments" label="Comments" value="My comments" rows="5"/>
627
Reference ui:inputTextArea
({
setOutput : function(component, event, helper) {
var cmpMsg = component.find("msg");
$A.util.removeClass(cmpMsg, 'hide');
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
cols Integer The width of the text area, which is defined by the number of characters
to display in a single row at a time. Default value is “20”.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML
textarea element.
readonly Boolean Specifies whether the text area should be rendered as read-only. Default
value is “false”.
required Boolean Specifies whether the input is required. Default value is "false".
resizable Boolean Specifies whether or not the textarea should be resizable. Defaults to
true.
628
Reference ui:inputTextArea
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
629
Reference ui:inputURL
ui:inputURL
An input field for entering a URL.
A ui:inputURL component represents an input field for a URL, which is rendered as an HTML input tag of type url. To apply
Lightning Design System styling, we recommend that you use lightning:input with type="url" instead of ui:inputURL.
This is a basic set up of a ui:inputURL component.
<ui:inputURL aura:id="url" label="Venue URL" class="field" value="http://www.myURL.com"/>
This example retrieves the value of a ui:inputURL component and displays it using ui:outputURL. To apply Lightning Design
System styling, we recommend that you use lightning:input with type="url" instead of ui:inputURL.
<aura:component>
<ui:inputURL aura:id="url" label="Venue URL" class="field" value="http://www.myURL.com"/>
({
setOutput : function(component, event, helper) {
var cmpMsg = component.find("msg");
$A.util.removeClass(cmpMsg, 'hide');
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
630
Reference ui:inputURL
maxlength Integer The maximum number of characters that can be typed into the input
field. Corresponds to the maxlength attribute of the rendered HTML input
element.
placeholder String Text that is displayed when the field is empty, to prompt the user for a
valid entry.
required Boolean Specifies whether the input is required. Default value is "false".
size Integer The width of the input field, in characters. Corresponds to the size
attribute of the rendered HTML input element.
updateOn String Updates the component's value binding if the updateOn attribute is set
to the handled event. Default value is "change".
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
631
Reference ui:menu
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
cut COMPONENT The event fired when the user cuts content to the clipboard.
onError COMPONENT The event fired when there are any validation errors on the component.
onClearErrors COMPONENT The event fired when any validation errors should be cleared.
change COMPONENT The event fired when the user changes the content of the input.
copy COMPONENT The event fired when the user copies content to the clipboard.
paste COMPONENT The event fired when the user pastes content from the clipboard.
ui:menu
A dropdown menu list with a trigger that controls its visibility. To create a clickable link and menu items, use ui:menuTriggerLink and
and ui:menuList component.
A ui:menu component contains a trigger and list items. To apply Lightning Design System styling, we recommend that you use
lightning:buttonMenu instead of ui:menu.
You can wire up list items to actions in a client-side controller so that selection of the item triggers an action. This example shows a
menu with list items, which when pressed updates the label on the trigger.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Opportunity Status"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<ui:actionMenuItem aura:id="item1" label="Any"
click="{!c.updateTriggerLabel}"/>
<ui:actionMenuItem aura:id="item2" label="Open" click="{!c.updateTriggerLabel}"
disabled="true"/>
<ui:actionMenuItem aura:id="item3" label="Closed"
click="{!c.updateTriggerLabel}"/>
<ui:actionMenuItem aura:id="item4" label="Closed Won"
click="{!c.updateTriggerLabel}"/>
</ui:menuList>
</ui:menu>
This client-side controller updates the trigger label when a menu item is clicked.
({
updateTriggerLabel: function(cmp, event) {
var triggerCmp = cmp.find("trigger");
if (triggerCmp) {
var source = event.getSource();
var label = source.get("v.label");
triggerCmp.set("v.label", label);
}
}
})
632
Reference ui:menu
The dropdown menu and its menu items are hidden by default. You can change this by setting the visible attribute on the
ui:menuList component to true. The menu items are shown only when you click the ui:menuTriggerLink component.
To use a trigger, which opens the menu, nest the ui:menuTriggerLink component in ui:menu. For list items, use the
ui:menuList component, and include any of these list item components that can trigger a client-side controller action:
• ui:actionMenuItem - A menu item
• ui:checkboxMenuItem - A checkbox that supports multiple selections
• ui:radioMenuItem - A radio item that supports single selection
To include a separator for these menu items, use ui:menuItemSeparator.
This example shows several ways to create a menu. To apply Lightning Design System styling, we recommend that you use
lightning:buttonMenu instead of ui:menu.
<aura:component access="global">
<aura:attribute name="status" type="String[]" default="Open, Closed, Closed Won, Any"/>
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Single selection with actionable
menu item"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<aura:iteration items="{!v.status}" var="s">
<ui:actionMenuItem label="{!s}" click="{!c.updateTriggerLabel}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
<hr/>
<ui:menu>
<ui:menuTriggerLink class="checkboxMenuLabel" aura:id="checkboxMenuLabel"
label="Multiple selection"/>
<ui:menuList aura:id="checkboxMenu" class="checkboxMenu">
<aura:iteration aura:id="checkbox" items="{!v.status}" var="s">
<ui:checkboxMenuItem label="{!s}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
<p><ui:button class="checkboxButton" aura:id="checkboxButton"
press="{!c.getMenuSelected}" label="Check the selected menu items"/></p>
<p><ui:outputText class="result" aura:id="result" value="Which items get
selected"/></p>
<hr/>
<ui:menu>
<ui:menuTriggerLink class="radioMenuLabel" aura:id="radioMenuLabel"
label="Select a status"/>
<ui:menuList class="radioMenu" aura:id="radioMenu">
<aura:iteration aura:id="radio" items="{!v.status}" var="s">
<ui:radioMenuItem label="{!s}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
<p><ui:button class="radioButton" aura:id="radioButton"
press="{!c.getRadioMenuSelected}" label="Check the selected menu items"/></p>
<p><ui:outputText class="radioResult" aura:id="radioResult" value="Which items
get selected"/> </p>
633
Reference ui:menu
<hr/>
<div style="margin:20px;">
<div style="display:inline-block;width:50%;vertical-align:top;">
Combination menu items
<ui:menu>
<ui:menuTriggerLink aura:id="mytrigger" label="Select Menu Items"/>
<ui:menuList>
<ui:actionMenuItem label="Red" click="{!c.updateLabel}" disabled="true"/>
({
updateTriggerLabel: function(cmp, event) {
var triggerCmp = cmp.find("trigger");
if (triggerCmp) {
var source = event.getSource();
var label = source.get("v.label");
triggerCmp.set("v.label", label);
}
},
updateLabel: function(cmp, event) {
var triggerCmp = cmp.find("mytrigger");
if (triggerCmp) {
var source = event.getSource();
var label = source.get("v.label");
triggerCmp.set("v.label", label);
}
},
getMenuSelected: function(cmp) {
var menuItems = cmp.find("checkbox");
var values = [];
for (var i = 0; i < menuItems.length; i++) {
var c = menuItems[i];
if (c.get("v.selected") === true) {
values.push(c.get("v.label"));
}
634
Reference ui:menuItem
}
var resultCmp = cmp.find("result");
resultCmp.set("v.value", values.join(","));
},
getRadioMenuSelected: function(cmp) {
var menuItems = cmp.find("radio");
var values = [];
for (var i = 0; i < menuItems.length; i++) {
var c = menuItems[i];
if (c.get("v.selected") === true) {
values.push(c.get("v.label"));
}
}
var resultCmp = cmp.find("radioResult");
resultCmp.set("v.value", values.join(","));
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:menuItem
A UI menu item in a ui:menuList component.
635
Reference ui:menuItem
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
hideMenuAfterSelected Boolean Set to true to hide menu after the menu item is selected.
selected Boolean The status of the menu item. True means this menu item is selected;
False is not selected.
type String The concrete type of the menu item. Accepted values are 'action',
'checkbox', 'radio', 'separator' or any namespaced component descriptor,
e.g. ns:xxxxmenuItem.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
636
Reference ui:menuItemSeparator
ui:menuItemSeparator
A menu separator to divide menu items, such as ui:radioMenuItem, and used in a ui:menuList component.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:menuList
A menu component that contains menu items.
This component is nested in a ui:menu component and can be used together with a ui:menuTriggerLink component.
Clicking the menu trigger displays the container with menu items.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Click me to display menu items"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<ui:actionMenuItem aura:id="item1" label="Item 1" click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item2" label="Item 2" click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item3" label="Item 3" click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item4" label="Item 4" click="{!c.doSomething}"/>
</ui:menuList>
</ui:menu>
ui:menuList can contain these components, which runs a client-side controller when clicked:
• ui:actionMenuItem
637
Reference ui:menuList
• ui:checkboxMenuItem
• ui:radioMenuItem
• ui:menuItemSeparator
See ui:menu for more information.
Attributes
Attribute Name Attribute Type Description Required?
autoPosition Boolean Move the popup target up when there is not enough space at the bottom
to display. Note: even if autoPosition is set to false, popup will still position
the menu relative to the trigger. To override default positioning, use
manualPosition attribute.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
closeOnClickOutside Boolean Close target when user clicks or taps outside of the target
closeOnTabKey Boolean Indicates whether to close the target list on tab key or not.
menuItems List A list of menu items set explicitly using instances of the Java class: aura.
components.ui.MenuItem.
visible Boolean Controls the visibility of the menu. The default is false, which hides the
menu.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
menuExpand COMPONENT The event fired when the menu list displays.
638
Reference ui:menuTrigger
menuCollapse COMPONENT The event fired when the menu list collapses.
menuFocusChange COMPONENT The event fired when the menu list focus changed from one menuItem to another
menuItem.
ui:menuTrigger
A clickable link that expands and collapses a menu. To create a link for ui:menu, use ui:menuTriggerLink instead.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
title String The text to display as a tooltip when the mouse pointer hovers over this
component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
639
Reference ui:menuTriggerLink
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
menuTriggerPress COMPONENT The event that is fired when the trigger is clicked.
ui:menuTriggerLink
A link that triggers a dropdown menu used in ui:menu
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
title String The text to display as a tooltip when the mouse pointer hovers over this
component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
640
Reference ui:message
blur COMPONENT The event fired when the user moves off from the trigger.
focus COMPONENT The event fired when the user focuses on the trigger.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
menuTriggerPress COMPONENT The event that is fired when the trigger is clicked.
ui:message
Represents a message of varying severity levels
The severity attribute indicates a message's severity level and determines the style to use when displaying the message. If the
closable attribute is set to true, the message can be dismissed by pressing the × symbol. To apply Lightning Design System styling,
we recommend that you use lightning:notificationsLibrary instead of ui:message.
This example shows a confirmation message that can be dismissed.
<ui:message title="Confirmation" severity="confirm" closable="true">
This is a confirmation message.
</ui:message>
This example shows messages in varying severity levels. To apply Lightning Design System styling, we recommend that you use
lightning:notificationsLibrary instead of ui:message.
<aura:component access="global">
<ui:message title="Confirmation" severity="confirm" closable="true">
This is a confirmation message.
</ui:message>
<ui:message title="Information" severity="info" closable="true">
This is a message.
</ui:message>
<ui:message title="Warning" severity="warning" closable="true">
This is a warning.
</ui:message>
<ui:message title="Error" severity="error" closable="true">
This is an error message.
</ui:message>
</aura:component>
641
Reference ui:outputCheckbox
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
closable Boolean Specifies whether to display an 'x' that will close the alert when clicked.
Default value is 'false'.
severity String The severity of the message. Possible values: message (default), confirm,
info, warning, error
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputCheckbox
Displays a checkbox in a checked or unchecked state.
A ui:outputCheckbox component represents a checkbox that is rendered as an HTML img tag. This component can be used
with ui:inputCheckbox, which enables users to select or deselect the checkbox. To select or deselect the checkbox, set the
value attribute to true or false. To display a checkbox, you can use an attribute value and bind it to the ui:outputCheckbox
component.
<aura:attribute name="myBool" type="Boolean" default="true"/>
<ui:outputCheckbox value="{!v.myBool}"/>
642
Reference ui:outputCheckbox
This example shows how you can use the ui:inputCheckbox component.
<aura:component>
<aura:attribute name="myBool" type="Boolean" default="true"/>
<ui:inputCheckbox aura:id="checkbox" label="Select?" change="{!c.onCheck}"/>
<p>Selected:</p>
<p><ui:outputText class="result" aura:id="checkResult" value="false" /></p>
<p>The following checkbox uses a component attribute to bind its value.</p>
<ui:outputCheckbox aura:id="output" value="{!v.myBool}"/>
</aura:component>
({
onCheck: function(cmp, evt) {
var checkCmp = cmp.find("checkbox");
resultCmp = cmp.find("checkResult");
resultCmp.set("v.value", ""+checkCmp.get("v.value"));
}
})
Attributes
Attribute Name Attribute Type Description Required?
altChecked String The alternate text description when the checkbox is checked. Default
value is “True”.
altUnchecked String The alternate text description when the checkbox is unchecked. Default
value is “False”.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
643
Reference ui:outputCurrency
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputCurrency
Displays the currency in the default or specified format, such as with specific currency code or decimal places.
A ui:outputCurrency component represents a number as a currency that is wrapped in an HTML span tag. We recommend
using lightning:formattedNumber with style="currency" instead of ui:outputCurrency.
This component can be used with ui:inputCurrency, which takes in a number as a currency. To apply Lightning Design System
styling, we recommend that you use lightning:input with type="number" and formatter="currency" instead
of ui:inputCurrency.
To display a currency, you can use an attribute value and bind it to the ui:outputCurrency component.
<aura:attribute name="myCurr" type="Decimal" default="50000"/>
<ui:outputCurrency aura:id="curr" value="{!v.myCurr}"/>
This example shows how you can bind data from a ui:inputCurrency component. We recommend using
lightning:formattedNumber with style="currency" instead of ui:outputCurrency.
<aura:component>
<aura:attribute name="myCurrency" type="integer" default="50"/>
<ui:inputCurrency aura:id="amount" label="Amount" class="field" value="{!v.myCurrency}"
updateOn="keyup"/>
You entered: <ui:outputCurrency value="{!v.myCurrency}"/>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
644
Reference ui:outputDate
currencyCode String The ISO 4217 currency code specified as a String, e.g. “USD”.
format String The format of the number. For example, format=“.00” displays the number
followed by two decimal places. If not specified, the default format based
on the browser's locale will be used.
value Decimal The output value of the currency, which is defined as type Decimal. Yes
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputDate
Displays a date in the default or specified format based on the user's locale.
A ui:outputDate component represents a date output in the YYYY-MM-DD format and is wrapped in an HTML span tag. We
recommend using lightning:formattedDateTime instead of ui:outputDate.
ui:outputDate can be used with ui:inputDate, which takes in a date input. To apply Lightning Design System styling, we
recommend that you use lightning:input with type="date" instead of ui:inputDate.
ui:outputDate retrieves the browser's locale information and displays the date accordingly. To display a date, you can use an
attribute value and bind it to the ui:outputDate component.
<aura:attribute name="myDate" type="Date" default="2014-09-29"/>
<ui:outputDate value="{!v.myDate}"/>
645
Reference ui:outputDate
This example shows how you can bind data from the ui:inputDate component. To apply Lightning Design System styling, we
recommend that you use lightning:input with type="date" instead of ui:inputDate.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="today" type="Date" default=""/>
({
doInit : function(component, event, helper) {
var today = new Date();
component.set('v.today', today.getFullYear() + "-" + (today.getMonth() + 1) + "-"
+ today.getDate());
},
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
langLocale String Deprecated. The language locale used to format date value. It only allows
to use the value which is provided by Locale Value Provider, otherwise,
it falls back to the value of $Locale.langLocale. It will be removed in an
upcoming release.
646
Reference ui:outputDateTime
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputDateTime
Displays a date, time in a specified or default format based on the user's locale.
A ui:outputDateTime component represents a date and time output that is wrapped in an HTML span tag. We recommend
using lightning:formattedDateTime instead of ui:outputDateTime.
This component can be used with ui:inputDateTime, which takes in a date input. To apply Lightning Design System styling, we
recommend that you use lightning:input with type="datetime-local" instead of ui:inputDateTime.
ui:outputDateTime retrieves the browser's locale information and displays the date accordingly. To display a date and time, you
can use an attribute value and bind it to the ui:outputDateTime component.
<aura:attribute name="myDateTime" type="Date" default="2014-09-29T00:17:08z"/>
<ui:outputDateTime value="{!v.myDateTime}"/>
This example shows how you can bind data from a ui:inputDateTime component.
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<aura:attribute name="today" type="Date" default=""/>
647
Reference ui:outputDateTime
({
doInit : function(component, event, helper) {
var today = new Date();
component.set('v.today', today.getFullYear() + "-" + (today.getMonth() + 1) + "-"
+ today.getDate());
},
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
langLocale String Deprecated. The language locale used to format date value. It only allows
to use the value which is provided by Locale Value Provider, otherwise,
it falls back to the value of $Locale.langLocale. It will be removed in an
upcoming release.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
648
Reference ui:outputEmail
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputEmail
Displays an email address in an HTML anchor (<a>) element. The leading and trailing space are trimmed.
A ui:outputEmail component represents an email output that is wrapped in an HTML span tag. We recommend using
lightning:formattedEmail instead of ui:outputEmail.
ui:outputEmail can be used with ui:inputEmail, which takes in an email input. To apply Lightning Design System styling,
we recommend that you use lightning:input with type="email" instead of ui:inputEmail.
The email output is wrapped in an HTML anchor element and mailto is automatically appended to it. This is a simple set up of a
ui:outputEmail component.
<ui:outputEmail value="abc@email.com"/>
This example shows how you can bind data from a ui:inputEmail component. To apply Lightning Design System styling, we
recommend that you use lightning:input with type="email" instead of ui:inputEmail.
<aura:component>
<ui:inputEmail aura:id="email" label="Email" class="field" value="manager@email.com"/>
</aura:component>
({
setOutput : function(component, event, helper) {
var cmpMsg = component.find("msg");
$A.util.removeClass(cmpMsg, 'hide');
649
Reference ui:outputNumber
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputNumber
Displays the number in the default or specified format. Supports up to 18 digits before the decimal place.
A ui:outputNumber component represents a number output that is rendered as an HTML span tag. We recommend using
lightning:formattedNumber instead of ui:outputNumber.
ui:outputNumber can be used with ui:inputNumber, which takes in a number input. To apply Lightning Design System
styling, we recommend that you use lightning:input with type="number" instead of ui:inputNumber.
ui:outputNumber retrieves the locale information and displays the number in the given decimal format. To display a number, you
can use an attribute value and bind it to the ui:outputNumber component.
<aura:attribute name="myNum" type="Decimal" default="10.10"/>
<ui:outputNumber value="{!v.myNum}" format=".00"/>
650
Reference ui:outputNumber
This example retrieves the value of a ui:intputNumber component, validates the input, and displays it using ui:outputNumber.
To apply Lightning Design System styling, we recommend that you use lightning:input with type="number" instead of
ui:inputNumber. Similarly, we recommend using lightning:formattedNumber instead of ui:outputNumber.
<aura:component>
<aura:attribute name="myNumber" type="integer" default="10"/>
<ui:inputNumber label="Enter a number: " value="{!v.myNumber}" updateOn="keyup"/> <br/>
<ui:outputNumber value="{!v.myNumber}"/>
</aura:component>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
format String The format of the number. For example, format=“.00” displays the number
followed by two decimal places. If not specified, the Locale default format
will be used.
value Decimal The number displayed when this component is rendered. Yes
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
651
Reference ui:outputPhone
ui:outputPhone
Displays the phone number in a URL link format.
A ui:outputPhone component represents a phone number output that is wrapped in an HTML span tag. We recommend using
lightning:formattedPhone instead of ui:outputPhone.
ui:outputPhone can be used with ui:inputPhone, which takes in a phone number input. To apply Lightning Design System
styling, we recommend that you use lightning:input with type="tel" instead of ui:inputPhone.
The following example is a simple set up of a ui:outputPhone component.
<ui:outputPhone value="415-123-4567"/>
This example shows how you can bind data from a ui:inputPhone component. To apply Lightning Design System styling, we
recommend that you use lightning:input with type="tel" instead of ui:inputPhone.
<aura:component>
<ui:inputPhone aura:id="phone" label="Phone Number" class="field" value="415-123-4567"
/>
<ui:button class="btn" label="Submit" press="{!c.setOutput}"/>
({
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
652
Reference ui:outputRichText
value String The phone number displayed when this component is rendered. Yes
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputRichText
Displays formatted text including tags such as paragraph, image, and hyperlink, as specified in the value attribute.
A ui:outputRichText component represents formatted text and can be used to display input from a
lightning:inputRichText or ui:inputRichText component. Using lightning:inputRichText is recommended
since ui:inputRichText is no longer supported when LockerService is enabled. Similarly, we recommend that you use
lightning:formattedRichText instead of ui:outputRichText.
ui:outputRichText renders formatted text. For example, URLs and email addresses enclosed by anchor tags are displayed as
hyperlinks.
This example sets bold text and binds the value to a lightning:inputRichText and ui:outputRichText component.
The slds-text-longform class adds default spacing and list styling in your output.
<aura:component>
<aura:attribute name="myVal" type="String" />
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<lightning:inputRichText value="{!v.myVal}"/>
<ui:outputRichText class="slds-text-longform" value="{!v.myVal}"/>
</aura:component>
During initialization, the value is set on both the lightning:inputRichText and ui:outputRichText component.
({
init: function(cmp) {
cmp.set('v.myVal', '<b>Hello!</b>');
653
Reference ui:outputText
}
})
ui:outputRichText supports the following HTML tags: a, b, br, big, blockquote, caption, cite, code, col,
colgroup, del, div, em, h1, h2, h3, hr, i, img, ins, kbd, li, ol, p, param, pre, q, s, samp, small, span, strong,
sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, var, strike.
Supported HTML attributes include: accept, action, align, alt, autocomplete, background, bgcolor, border,
cellpadding, cellspacing, checked, cite, class, clear, color, cols, colspan, coords, datetime,
default, dir, disabled, download, enctype, face, for, headers, height, hidden, high, href, hreflang,
id, ismap, label, lang, list, loop, low, max, maxlength, media, method, min, multiple, name, noshade,
novalidate, nowrap, open, optimum, pattern, placeholder, poster, preload, pubdate, radiogroup,
readonly, rel, required, rev, reversed, rows, rowspan, spellcheck, scope, selected, shape, size,
span, srclang, start, src, step, style, summary, tabindex, target, title, type, usemap, valign, value,
width, xmlns.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
linkify Boolean Indicates if the URLs in the text are set to render as hyperlinks.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputText
Displays text as specified by the value attribute.
654
Reference ui:outputText
A ui:outputText component represents text output that is wrapped in an HTML span tag. We recommend using
lightning:formattedText instead of ui:outputText.
ui:outputText can be used with ui:inputText, which takes in a text input. To apply Lightning Design System styling, we
recommend that you use lightning:input instead of ui:inputText.
To display text, you can use an attribute value and bind it to the ui:outputText component.
<aura:attribute name="myText" type="String" default="some string"/>
<ui:outputText value="{!v.myText}" />
This example shows how you can bind data from an ui:inputText component. To apply Lightning Design System styling, we
recommend that you use lightning:input instead of ui:inputText.
<aura:component>
<aura:attribute name="myText" type="string" default="Hello there!"/>
<ui:inputText label="Enter some text" class="field" value="{!v.myText}" updateOn="click"/>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
value String The text displayed when this component is rendered. Yes
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
655
Reference ui:outputTextArea
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputTextArea
Displays the text area as specified by the value attribute.
A ui:outputTextArea component represents text output that is wrapped in an HTML span tag. We recommend using
lightning:formattedText instead of ui:outputText.
ui:outputTextArea can be used with ui:inputTextArea, which takes in a multiline text input. To apply Lightning Design
System styling, we recommend that you use lightning:textarea instead of ui:inputTextArea.
To display text, you can use an attribute value and bind it to the ui:outputTextArea component. A ui:outputTextArea
component displays URLs and email addresses as hyperlinks.
<aura:attribute name="myTextArea" type="String" default="some string"/>
<ui:outputTextArea value="{!v.myTextArea}"/>
This example shows how you can bind data from the ui:inputTextArea component. To apply Lightning Design System styling,
we recommend that you use lightning:textarea instead of ui:inputTextArea.
<aura:component>
<ui:inputTextArea aura:id="comments" label="Comments" value="My comments" rows="5"/>
({
setOutput : function(component, event, helper) {
var cmpMsg = component.find("msg");
$A.util.removeClass(cmpMsg, 'hide');
656
Reference ui:outputURL
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
linkify Boolean Indicates if the URLs in the text are set to render as hyperlinks.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:outputURL
Displays a link to a URL as specified by the value attribute, rendered on a given text (label attribute) and image, if any.
A ui:outputURL component represents a URL that is wrapped in an HTML a tag. We recommend using
lightning:formattedUrl instead of ui:outputURL.
ui:outputURL can be used with ui:inputURL, which takes in a URL input. To apply Lightning Design System styling, we
recommend that you use lightning:input with type="url" instead of ui:inputURL.
To display a URL, you can use an attribute value and bind it to the ui:outputURL component.
<aura:attribute name="myURL" type="String" default="http://www.google.com"/>
<ui:outputURL value="{!v.myURL}" label="Search"/>
657
Reference ui:outputURL
This example shows how you can bind data from a ui:inputURL component.
<aura:component>
<ui:inputURL aura:id="url" label="Venue URL" class="field" value="http://www.myURL.com"/>
({
setOutput : function(component, event, helper) {
var cmpMsg = component.find("msg");
$A.util.removeClass(cmpMsg, 'hide');
Attributes
Attribute Name Attribute Type Description Required?
alt String The alternate text description for image (used when there is no label)
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
iconClass String The CSS style used to display the icon or image.
target String The target destination where this rendered component is displayed.
Possible values: _blank, _parent, _self, _top
title String The text to display as a tooltip when the mouse pointer hovers over this
component.
value String The URL of the page that the link goes to. Yes
658
Reference ui:radioMenuItem
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
ui:radioMenuItem
A menu item with a radio button that indicates a mutually exclusive selection and can be used to invoke an action. This component is
nested in a ui:menu component.
A ui:radioMenuItem component represents a menu list item for single selection. Use aura:iteration to iterate over a list
of values and display the menu items. A ui:menuTriggerLink component displays and hides your menu items.
<aura:attribute name="status" type="String[]" default="Open, Closed, Closed Won, Any"/>
<ui:menu>
<ui:menuTriggerLink class="radioMenuLabel" aura:id="radioMenuLabel" label="Select
a status"/>
<ui:menuList class="radioMenu" aura:id="radioMenu">
<aura:iteration items="{!v.status}" var="s">
<ui:radioMenuItem label="{!s}"/>
</aura:iteration>
</ui:menuList>
</ui:menu>
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
disabled Boolean Specifies whether the component should be displayed in a disabled state.
Default value is "false".
hideMenuAfterSelected Boolean Set to true to hide menu after the menu item is selected.
659
Reference ui:scrollerWrapper
type String The concrete type of the menu item. Accepted values are 'action',
'checkbox', 'radio', 'separator' or any namespaced component descriptor,
e.g. ns:xxxxmenuItem.
Events
Event Name Event Type Description
dblclick COMPONENT The event fired when the user double-clicks the component.
mouseover COMPONENT The event fired when the user moves the mouse pointer over the component.
mouseout COMPONENT The event fired when the user moves the mouse pointer away from the
component.
mouseup COMPONENT The event fired when the user releases the mouse button over the component.
mousemove COMPONENT The event fired when the user moves the mouse pointer over the component.
click COMPONENT The event fired when the user clicks on the component.
mousedown COMPONENT The event fired when the user clicks a mouse button over the component.
select COMPONENT The event fired when the user selects some text.
blur COMPONENT The event fired when the user moves off from the component.
focus COMPONENT The event fired when the user focuses on the component.
keypress COMPONENT The event fired when the user presses or holds down a keyboard key on the
component.
keyup COMPONENT The event fired when the user releases a keyboard key on the component.
keydown COMPONENT The event fired when the user presses a keyboard key on the component.
ui:scrollerWrapper
Creates a container that enables native scrolling in the Salesforce app.
A ui:scrollerWrapper creates a container that enables native scrolling in the Salesforce app. This component enables you to
nest more than one scroller inside the container. Use the class attribute to define the height and width of the container. To enable
scrolling, specify a height that's smaller than its content.
This example creates a scrollable area with a height of 300px.
<aura:component>
<ui:scrollerWrapper class="scrollerSize">
<!--Scrollable content here -->
</ui:scrollerWrapper>
660
Reference ui:scrollerWrapper
</aura:component>
The Lightning Design System scrollable class isn't compatible with native scrolling on mobile devices. Use
ui:scrollerWrapper if you want to enable scrolling in Salesforce for Android, iOS, and mobile web.
Usage Considerations
In Google Chrome on mobile devices, nested ui:scrollerWrapper components are not scrollable when border-radius
CSS property is set to a non-zero value. To enable scrolling in this case, set border-radius to a non-zero value on the outer
ui:scrollerWrapper component.
Here is an example.
<aura:component>
<ui:scrollerWrapper class="outerScroller">
<!-- Scrollable content here -->
<ui:scrollerWrapper class="innerScroller">
<!-- Scrollable content here -->
</ui:scrollerWrapper>
<!-- Scrollable content here -->
</ui:scrollerWrapper>
</aura:component>
Methods
This component supports the following method.
scrollTo(destination, xcoord, ycoord): Scrolls the content to a specified location.
• destination (String): The target location. Valid values: custom, top, bottom, left, and right. For custom destination, xcoord and
ycoord are used to determine the target location.
• xcoord (Integer): X coordinate for custom destination. The default is 0.
• ycoord (Integer): Y coordinate for custom destination. The default is 0.
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
661
Reference ui:spinner
ui:spinner
A loading spinner to be used while the real component body is being loaded
To toggle the spinner, use get("e.toggle"), set the isVisible parameter to true or false, and then fire the event.
This example shows a spinner that can be toggled.
<aura:component access="global">
<ui:spinner aura:id="spinner"/>
<ui:button press="{!c.toggleSpinner}" label="Toggle Spinner" />
</aura:component>
({
toggleSpinner: function(cmp) {
var spinner = cmp.find('spinner');
var evt = spinner.get("e.toggle");
if(!$A.util.hasClass(spinner, 'hideEl')){
evt.setParams({ isVisible : false });
}
else {
evt.setParams({ isVisible : true });
}
evt.fire();
}
})
Attributes
Attribute Name Attribute Type Description Required?
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
class String A CSS style to be attached to the component. This style is added in
addition to base styles output by the component.
isVisible Boolean Specifies whether or not this spinner should be visible. Defaults to true.
662
Reference wave:waveDashboard
Events
Event Name Event Type Description
toggle COMPONENT The event fired when the spinner is toggled.
wave:waveDashboard
Use this component to add a Salesforce Analytics dashboard to a Lightning Experience page.
Attributes
Attribute Name Attribute Type Description Required?
accessToken String A valid access token obtained by logging into Salesforce. Useful when
the component is used by Lightning Out in a non salesforce domain.
body Component[] The body of the component. In markup, this is everything in the body of
the tag.
dashboardId String The unique ID of the dashboard. You can get a dashboard’s ID, an
18-character code beginning with 0FK, from the dashboard's URL, or you
can request it through the API. This attribute can be used instead of the
developer name, but it can't be included if the name has been set. One
of the two is required.
developerName String The unique developer name of the dashboard. You can request the
developer name through the API. This attribute can be used instead of
the dashboard ID, but it can't be included if the ID has been set. One of
the two is required.
filter String Adds selections or filters to the embedded dashboard at runtime. The
filter attribute is configured using JSON. For filtering by dimension, use
this syntax: {'datasets' : {'dataset1': [ {'fields': ['field1'], 'selection': ['$value1',
'$value2']}, {'fields': ['field2'], 'filter': { 'operator': 'operator1', 'values':
['$value3', '$value4']}}]}}. For filtering on measures, use this syntax:
{'datasets' : {'dataset1': [ {'fields': ['field1'], 'selection': ['$value1', '$value2']},
{'fields': ['field2'], 'filter': { 'operator': 'operator1', 'values': [[$value3]]}}]}}.
With the selection option, the dashboard is shown with all its data, and
the specified dimension values are highlighted. With the filter option,
the dashboard is shown with only filtered data. For more information,
see https://help.salesforce.com/articleView?id=bi_embed_lightning.htm.
hideOnError Boolean Controls whether or not users see a dashboard that has an error. When
this attribute is set to true, if the dashboard has an error, it won’t appear
on the page. When set to false, the dashboard appears but doesn’t show
any data. An error can occur when a user doesn't have access to the
dashboard or it has been deleted.
663
Reference Messaging Component Reference
recordId String Id of the current entity in the context of which the component is being
displayed.
showHeader Boolean If true, the dashboard is displayed with a header bar that includes
dashboard information and controls. If false, the dashboard appears
without a header bar. Note that the header bar automatically appears
when either showSharing or showTitle is true.
showSharing Boolean If true, and the dashboard is shareable, then the dashboard shows the
Share icon. If false, the dashboard doesn't show the Share icon. To show
the Share icon in the dashboard, the smallest supported frame size is 800
x 612 pixels.
showTitle Boolean If true, the dashboard’s title is included above the dashboard. If false, the
dashboard appears without a title.
lightning:notificationsLibrary
lightning:notificationsLibrary provides an easy way to display messages in the app. This component requires API
version 41.0 and later. This component is supported in Lightning Experience, Salesforce app, and Lightning communities only.
Messages can be displayed in notices and toasts. Notices alert users to system-related issues and updates. Toasts enable you to provide
feedback and serve as a confirmation mechanism after the user takes an action. Include one
<lightning:notificationsLibrary aura:id="notifLib"/> tag in the component that triggers the notifications,
where aura:id is a unique local ID. Only one tag is needed for multiple notifications.
Notices
Notices interrupt the user's workflow and block everything else on the page. Notices must be acknowledged before a user regains control
over the app again. As such, use notices sparingly. They are not suitable for confirming a user’s action, such as before deleting a record.
To dismiss the notice, only the OK button is currently supported.
664
Reference lightning:notificationsLibrary
Here’s an example that contains a button. When clicked, the button displays a notice with the error variant.
<aura:component>
<lightning:notificationsLibrary aura:id="notifLib"/>
<lightning:button name="notice" label="Show Notice" onclick="{!c.handleShowNotice}"/>
</aura:component>
To create and display a notice, pass in the notice attributes using component.find('notifLib').showNotice(), where
notifLib matches the aura:id on the lightning:notificationsLibrary instance.
Notices inherit styling from prompts in the Lightning Design System.
Attributes
message String The message within the notice body. New lines are replaced by <br/>
and text links by anchors.
variant String Changes the appearance of the notice. Accepted variants are info,
warning, and error. This value defaults to info.
Toasts
Toasts are less intrusive than notices and are suitable for providing feedback to a user following an action, such as after a record is created.
A toast can be dismissed or can remain visible until a predefined duration has elapsed.
665
Reference lightning:overlayLibrary
Here’s an example that contains a button. When clicked, the button displays a toast with the info variant and remains visible until
you press the close button, denoted by the X in the top right corner.
<aura:component>
<lightning:notificationsLibrary aura:id="notifLib"/>
<lightning:button name="toast" label="Show Toast" onclick="{!c.handleShowToast}"/>
</aura:component>
To create and display a toast, pass in the toast attributes using component.find('notifLib').showToast(), where
notifLib matches the aura:id on the lightning:notificationsLibrary instance.
Toasts inherit styling from toasts in the Lightning Design System.
Attributes
message String A string representing the message. It can contain placeholders in the
form of {0} ... {N}. This placeholders will be replaced with the action
links on the message data.
messageData Object Array of inlined action links to replace within the toast message template.
variant String Changes the appearance of the toast. Accepted variants are info,
success, warning, and error. This value defaults to info.
mode String Determines how persistent the toast is. The default is dismissable.
Valid modes are:
• dismissable: Remains visible until you press the close button
or 3 seconds has elapsed, whichever comes first.
• pester: Remains visible until the close button is clicked.
• sticky: Remains visible for 3 seconds.
lightning:overlayLibrary
lightning:overlayLibrary provides an easy way to display relevant information and feedback. This component requires API
version 41.0 and later. This component is supported in Lightning Experience, Salesforce app, and Lightning communities only.
Messages can be displayed in modals and popovers. Modals display a dialog in the foreground of the app, interrupting a user’s workflow
and drawing attention to the message. Popovers display relevant information when you hover over a reference element. Include one
666
Reference lightning:overlayLibrary
<lightning:overlayLibrary aura:id="overlayLib"/> tag in the component that triggers the messages, where
aura:id is a unique local ID. Only one tag is needed for multiple messages.
Modals
A modal blocks everything else on the page until it’s dismissed. A modal must be acknowledged before a user regains control over the
app again. A modal is triggered by user interaction, which can be a click of a button or link. The modal header, body, and footer are
customizable. Pressing the Escape key or clicking the close button closes the modal.
Here’s an example that contains a button. When clicked, the button displays a modal with a custom body.
<aura:component>
<lightning:overlayLibrary aura:id="overlayLib"/>
<lightning:button name="modal" label="Show Modal" onclick="{!c.handleShowModal}"/>
</aura:component>
Your client-side controller displays the modal. To create and display a modal, pass in the modal attributes using
component.find('overlayLib').showCustomModal(), where overlayLib matches the aura:id on the
lightning:overlayLibrary instance.
({
handleShowModal: function(component, evt, helper) {
var modalBody;
$A.createComponent("c:modalContent", {},
function(content, status) {
if (status === "SUCCESS") {
modalBody = content;
component.find('overlayLib').showCustomModal({
header: "Application Confirmation",
body: modalBody,
showCloseButton: true,
cssClass: "mymodal",
closeCallback: function() {
alert('You closed the alert!');
}
})
});
}
})
667
Reference lightning:overlayLibrary
<aura:component>
<lightning:icon size="medium" iconName="action:approval" alternativeText="Approved"
/>
Your application has been approved.
</aura:component>
You can pass in your own footer via the footer attribute. This example creates a custom body and footer using
$A.createComponents().
<aura:component>
<lightning:overlayLibrary aura:id="overlayLib"/>
<lightning:button name="cancel" label="Cancel" onclick="{!c.handleCancel}"/>
<lightning:button name="ok" label="OK" variant="brand" onclick="{!c.handleOK}"/>
</aura:component>
Define what happens when you click the buttons in your client-side controller.
({
handleCancel : function(component, event, helper) {
//closes the modal or popover from the component
component.find("overlayLib").notifyClose();
},
handleOK : function(component, event, helper) {
//do something
}
})
668
Reference lightning:overlayLibrary
showCustomModal() and showCustomPopover() return a promise, which is useful if you want to get a reference to the
modal when it’s displayed.
component.find('overlayLib').showCustomModal({
//modal attributes
}).then(function (overlay) {
//closes the modal immediately
overlay.close();
});
showCloseButton Boolean Specifies whether to display the close button on the modal. The default
is true.
cssClass String A comma-separated list of CSS classes for the modal. Applies to visible
markup only.
Methods
You can use the following methods on the modal instance returned by the promise.
close(): Dismisses and destroys the modal.
hide(): Hides the modal from view.
show(): Displays the modal.
Popovers
Popovers display contextual information on a reference element and don’t interrupt like modals. A popover can be displayed when you
hover over or click the reference element. Pressing the Escape key closes the popover. The default positioning of the popover is on the
right of the reference element.
Here’s an example that contains a button and a reference div element. When clicked, the button displays a popover. The popover also
displays when you hover over the div element.
<aura:component>
<lightning:overlayLibrary aura:id="overlayLib"/>
<lightning:button name="popover" label="Show Popover" onclick="{!c.handleShowPopover}"/>
669
Reference lightning:overlayLibrary
Your client-side controller displays the popover. Although this example passes in a string to the popover body, you can also pass in a
custom component like in the previous modal example. Any custom CSS class you add must be accompanied by the cMyCmp class,
where c is your namespace and MyCmp is the name of the component that creates the popover. Adding this class ensures that the
custom styling is properly scoped.
({
handleShowPopover : function(component, event, helper) {
component.find('overlayLib').showCustomPopover({
body: "Popovers are positioned relative to a reference element",
referenceSelector: ".mypopover",
cssClass: "popoverclass, cMyCmp"
}).then(function (overlay) {
setTimeout(function(){
//close the popover after 3 seconds
overlay.close();
}, 3000);
});
}
})
Update the cssClass attribute. The cMyCmp class corresponds to your namespace and component name, and is case-sensitive.
cssClass: "slds-nubbin_left,slds-popover_walkthrough,no-pointer,cMyCmp"
Attributes
referenceSelector Object The reference element to which the popover is appended. The popover
is appended to the right of the reference element.
670
Reference Interface Reference
Methods
You can use the following methods on the modal instance returned by the promise.
close(): Dismisses and destroys the modal.
hide(): Hides the modal from view.
show(): Displays the modal.
Interface Reference
Implement these platform interfaces to allow a component to be used in different contexts, or to enable your component to receive
extra context data. A component can implement multiple interfaces. Some interfaces are intended to be implemented together, while
others are mutually exclusive. Some interfaces have an effect only in Lightning Experience and the Salesforce app.
clients:availableForMailAppAppPage
To appear in the Lightning App Builder or a Lightning Page in Lightning for Outlook or Lightning for Gmail, a component must
implement the clients:availableForMailAppAppPage interface. For more information, see Create Components for
Lightning for Outlook and Lightning for Gmail.
clients:hasEventContext
Enables a component to be assigned to an event’s date or location attributes in Lightning for Outlook and Lightning for Gmail. For
more information, see Create Components for Lightning for Outlook and Lightning for Gmail.
clients:hasItemContext
Enables a component to be assigned to an email’s or a calendar event’s item attributes in Lightning for Outlook and Lightning for
Gmail. For more information, see Create Components for Lightning for Outlook and Lightning for Gmail.
flexipage:availableForAllPageTypes
A global interface that makes a component available in the Lightning App Builder, and for any type of Lightning page. For more
information, see Configure Components for Lightning Pages and the Lightning App Builder.
To appear in the utility bar, a component must implement the flexipage:availableForAllPageTypes interface. For
more information, see Add a Utility Bar to Lightning Appsin Salesforce Help.
flexipage:availableForRecordHome
If your component is designed only for record pages, implement the flexipage:availableForRecordHome interface
instead of flexipage:availableForAllPageTypes. For more information, see Configure Components for Lightning
Experience Record Pages.
forceCommunity:availableForAllPageTypes
To appear in Community Builder, a component must implement the forceCommunity:availableForAllPageTypes
interface. For more information, see Configure Components for Communities.
force:appHostable
Allows a component to be used as a custom tab in Lightning Experience or the Salesforce app. For more information, see Add
Lightning Components as Custom Tabs in Lightning Experience.
671
Reference Interface Reference
force:lightningQuickAction
Allows a component to display in a panel with standard action controls, such as a Cancel button. These components can also display
and implement their own controls, but should handle events from the standard controls. If you implement
force:lightningQuickAction, you can’t implement force:lightningQuickActionWithoutHeader within
the same component. For more information, see Configure Components for Custom Actions.
force:lightningQuickActionWithoutHeader
Allows a component to display in a panel without additional controls. The component should provide a complete user interface for
the action. If you implement force:lightningQuickActionWithoutHeader, you can’t implement
force:lightningQuickAction within the same component. For more information, see Configure Components for Custom
Actions.
ltng:allowGuestAccess
Add the ltng:allowGuestAccess interface to your Lightning Out dependency app to make it available to users without
requiring them to authenticate with Salesforce. This interface lets you build your app with Lightning components, and deploy it
anywhere and to anyone. For more information, see Share Lightning Out Apps with Non-Authenticated Users.
IN THIS SECTION:
force:hasRecordId
Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the
current record. The current record ID is useful if the component is used on a Lightning record page, as an object-specific custom
action or action override in Lightning Experience or the Salesforce app, and so on. This interface has no effect except when used
within Lightning Experience, Salesforce app, and template-based communities.
force:hasSObjectName
Add the force:hasSObjectName interface to a Lightning component to enable the component to be assigned the API name
of current record’s sObject type. The sObject name is useful if the component can be used with records of different sObject types,
and needs to adapt to the specific type of the current record. This interface has no effect except when used within Lightning
Experience, Salesforce app, and template-based communities.
lightning:actionOverride
Add the lightning:actionOverride interface to a Lightning component to enable the component to be used to override
a standard action on an object. You can override the View, New, Edit, and Tab standard actions on most standard and all custom
components. This interface has no effect except when used within Lightning Experience and mobile.
lightning:appHomeTemplate
Implement the lightning:appHomeTemplate interface to enable your component to be used as a custom Lightning page
template for pages of type App Page. This interface has no effect except when used within Lightning Experience and the Salesforce
app.
lightning:availableForChatterExtensionComposer
Use the lightning:availableForChatterExtensionComposer interface to integrate your custom apps into the
Chatter publisher and place the custom app’s payload in the feed. This interface is available in Lightning communities.
lightning:availableForChatterExtensionRenderer
Use the lightning:availableForChatterExtensionRenderer interface to integrate your custom apps into the
Chatter publisher and place the custom app’s payload in the feed. This interface is available in Lightning communities.
lightning:availableForFlowScreens
Add the lightning:availableForFlowScreens interface to a Lightning component to make it available for flow
screens. This interface is supported only in Lightning runtime.
672
Reference force:hasRecordId
lightning:homeTemplate
Implement the lightning:homeTemplate interface to enable your component to be used as a custom Lightning page
template for the Lightning Experience Home page. This interface has no effect except when used within Lightning Experience.
lightning:recordHomeTemplate
Implement the lightning:recordHomeTemplate interface to enable your component to be used as a custom Lightning
page template for object record pages. This interface has no effect except when used within Lightning Experience.
lightningsnapin:prechatUI
Add the lightning:prechatUI interface to a Lightning component to enable Snap-ins to identify it as a custom Lightning
page template that can be used for the Snap-ins Chat pre-chat page. This interface has no effect except when used within Snap-ins
Chat hosted on a website, Visualforce page, or Community (using the Snap-ins Chat Community component).
force:hasRecordId
Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current
record. The current record ID is useful if the component is used on a Lightning record page, as an object-specific custom action or action
override in Lightning Experience or the Salesforce app, and so on. This interface has no effect except when used within Lightning
Experience, Salesforce app, and template-based communities.
This interface is a marker interface. A marker interface is a signal to the component’s container to add the interface’s behavior to the
component. You don’t need to implement any specific methods or attributes in your component, you simply add the interface name
to the component’s implements attribute.
The force:hasRecordId interface does two things to a component that implements it.
• It adds an attribute named recordId to your component. This attribute is of type String, and its value is an 18-character Salesforce
record ID, for example: 001xx000003DGSWAA4. If you added it yourself, the attribute definition would look like the following markup:
<aura:attribute name="recordId" type="String" />
Note: If your component implements force:hasRecordId, you don’t need to add a recordId attribute to the
component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a
runtime error.
• When your component is invoked in a record context in Lightning Experience or the Salesforce app, the recordId is set to the
ID of the record being viewed.
Important: The recordId attribute is set only when you place or invoke the component in an explicit record context. For
example, when you place the component directly on a record page layout, or invoke it as an object-specific action from a record
page or object home. In all other cases, such as when you invoke the component as a global action, or create the component
programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.
These unsupported contexts include a few contexts that might seem like they should have access to the current record. Examples
of these other contexts include the following:
• Invoking the component from a global action (even when you’re on a record page)
• Invoking the component from header or footer navigation in a community (even if the page shows a record)
force:hasRecordId and force:hasSObjectName are unsupported in these contexts. While the marker interfaces
still add the relevant attribute to the component, accessing either attribute generally returns null or undefined.
673
Reference force:hasSObjectName
Example: This example shows the markup required to add the force:hasRecordId interface to a Lightning component.
<aura:component implements="force:lightningQuickAction,force:hasRecordId">
</aura:component>
The component’s controller can access the ID of the current record from the recordId attribute, using
component.get("v.recordId"). The recordId attribute is automatically added to the component by the
force:hasRecordId interface.
force:hasSObjectName
Add the force:hasSObjectName interface to a Lightning component to enable the component to be assigned the API name of
current record’s sObject type. The sObject name is useful if the component can be used with records of different sObject types, and
needs to adapt to the specific type of the current record. This interface has no effect except when used within Lightning Experience,
Salesforce app, and template-based communities.
This interface is a marker interface. A marker interface is a signal to the component’s container to add the interface’s behavior to the
component. You don’t need to implement any specific methods or attributes in your component, you simply add the interface name
to the component’s implements attribute.
This interface adds an attribute named sObjectName to your component. This attribute is of type String, and its value is the API
name of an object, such as Account or myNamespace__myObject__c. For example:
<aura:attribute name="sObjectName" type="String" />
Note: If your component implements force:hasSObjectName, you don’t need to add an sObjectName attribute to
the component yourself. If you do add it, don’t change the access level or type of the attribute or the component will cause a
runtime error.
Important: The sObjectName attribute is set only when you place or invoke the component in an explicit record context.
For example, when you place the component directly on a record page layout, or invoke it as an object-specific action from a
record page or object home. In all other cases, such as when you invoke the component as a global action, or create the component
programmatically inside another component, sObjectName isn’t set, and your component shouldn’t depend on it.
These unsupported contexts include a few contexts that might seem like they should have access to the current record. Examples
of these other contexts include the following:
• Invoking the component from a global action (even when you’re on a record page)
• Invoking the component from header or footer navigation in a community (even if the page shows a record)
force:hasRecordId and force:hasSObjectName are unsupported in these contexts. While the marker interfaces
still add the relevant attribute to the component, accessing either attribute generally returns null or undefined.
Example: This example shows the markup required to add the force:hasSObjectName interface to a Lightning component.
<aura:component implements="force:lightningQuickAction,force:hasSObjectName">
</aura:component>
674
Reference lightning:actionOverride
The component’s controller can access the ID of the current record from the recordId attribute, using
component.get("v.sObjectName"). The recordId attribute is automatically added to the component by the
force:hasSObjectName interface.
lightning:actionOverride
Add the lightning:actionOverride interface to a Lightning component to enable the component to be used to override a
standard action on an object. You can override the View, New, Edit, and Tab standard actions on most standard and all custom components.
This interface has no effect except when used within Lightning Experience and mobile.
This interface is a marker interface. A marker interface is a signal to the component’s container to add the interface’s behavior to the
component. You don’t need to implement any specific methods or attributes in your component, you simply add the interface name
to the component’s implements attribute.
The lightning:actionOverride doesn’t add or require any attributes on components that implement it. Components that
implement this interface don’t automatically override any action. You need to manually override relevant actions in Setup.
Only components that implement this interface appear in the Lightning component menu of an object action Override Properties
panel.
Example: This example shows the markup required to add the lightning:actionOverride interface to a Lightning
component.
<aura:component
implements="lightning:actionOverride,force:hasRecordId,force:hasSObjectName">
<article class="slds-card">
<div class="slds-card__header slds-grid">
<header class="slds-media slds-media_center slds-has-flexi-truncate">
<div class="slds-media__body">
<h2><span class="slds-text-heading_small">Expense Details</span></h2>
</div>
</header>
<div class="slds-no-flex">
<lightning:button label="Edit" onclick="{!c.handleEdit}"/>
</div>
</div>
<div class="slds-card__body">(expense details go here)</div>
</article>
</aura:component>
In Lightning Experience, the standard Tab and View actions display as a page, while the standard New and Edit actions display in
an overlaid panel. When used as action overrides, Lightning components that implement the lightning:actionOverride
interface replace the standard behavior completely. However, overridden actions always display as a page, not as a panel. Your
component displays without controls, except for the main Lightning Experience navigation bar. Your component is expected to
provide a complete user interface for the action, including navigation or actions beyond the navigation bar.
675
Reference lightning:appHomeTemplate
lightning:appHomeTemplate
Implement the lightning:appHomeTemplate interface to enable your component to be used as a custom Lightning page
template for pages of type App Page. This interface has no effect except when used within Lightning Experience and the Salesforce app.
Components that implement this interface appear in the Custom Templates section of the Lightning App Builder new page wizard for
app pages.
Important: Each template component should implement only one template interface. Template components shouldn’t implement
any other type of interface, such as flexipage:availableForAllPageTypes or force:hasRecordId. A template
component can’t multi-task as a regular Lightning component. It’s either a template, or it’s not.
lightning:availableForChatterExtensionComposer
Use the lightning:availableForChatterExtensionComposer interface to integrate your custom apps into the Chatter
publisher and place the custom app’s payload in the feed. This interface is available in Lightning communities.
The lightning:availableForChatterExtensionComposer interface works with the
lightning:availableForChatterExtensionRenderer interface and the
lightning:sendChatterExtensionPayload event to integrate your custom apps into the Chatter publisher and to render
the app’s payload in the feed.
Note: For the full integration picture, see Integrate Your Custom Apps into the Chatter Publisher.
lightning:availableForChatterExtensionRenderer
Use the lightning:availableForChatterExtensionRenderer interface to integrate your custom apps into the Chatter
publisher and place the custom app’s payload in the feed. This interface is available in Lightning communities.
The lightning:availableForChatterExtensionRenderer interface works with the
lightning:availableForChatterExtensionComposer interface and the
lightning:sendChatterExtensionPayload event to integrate your custom apps into the Chatter publisher and to render
the app’s payload in the feed.
Note: For the full integration picture, see Integrate Your Custom Apps into the Chatter Publisher.
Fields
Attribute Name Type Description Required?
payload Object Payload data that was saved with the feed item is provided to the component No
that is implementing this interface
variant String An enum that can take one of two values: PREVIEW or RENDER. The selected No
value is provided to the component that is implementing this interface.
PREVIEW specifies that the attachment is used as a preview in the publisher.
RENDER specifies that the attachment is rendered with the feed item
676
Reference lightning:availableForFlowScreens
lightning:availableForFlowScreens
Add the lightning:availableForFlowScreens interface to a Lightning component to make it available for flow screens.
This interface is supported only in Lightning runtime.
This interface is a marker interface. A marker interface signals the component’s container to add the interface’s behavior to the component.
You don’t need to implement methods or attributes in your component. Instead, you just add the interface name to the component’s
implements attribute.
Example: This example shows the markup required to add the lightning:availableForFlowScreens interface to
a Lightning component.
<aura:component implements="lightning:availableForFlowScreens">
</aura:component>
For more information, see Customize Flow Screens By Using Lightning Components.
Attributes
Attribute Name Type Description Required?
availableActions String[] The navigation actions available for this screen. Valid actions are Next,
Previous, Finish, and Pause.
navigateFlow action References the appropriate navigation action to move away from this screen.
SEE ALSO:
Customize Flow Screens By Using Lightning Components
Control Flow Navigation from a Lightning Component
lightning:homeTemplate
Implement the lightning:homeTemplate interface to enable your component to be used as a custom Lightning page template
for the Lightning Experience Home page. This interface has no effect except when used within Lightning Experience.
Components that implement this interface appear in the Custom Templates section of the Lightning App Builder new page wizard for
Home pages.
Important: Each template component should implement only one template interface. Template components shouldn’t implement
any other type of interface, such as flexipage:availableForAllPageTypes or force:hasRecordId. A template
component can’t multi-task as a regular Lightning component. It’s either a template, or it’s not.
lightning:recordHomeTemplate
Implement the lightning:recordHomeTemplate interface to enable your component to be used as a custom Lightning page
template for object record pages. This interface has no effect except when used within Lightning Experience.
677
Reference lightningsnapin:prechatUI
Components that implement this interface appear in the Custom Templates section of the Lightning App Builder new page wizard for
record pages.
Important: Each template component should implement only one template interface. Template components shouldn’t implement
any other type of interface, such as flexipage:availableForAllPageTypes or force:hasRecordId. A template
component can’t multi-task as a regular Lightning component. It’s either a template, or it’s not.
lightningsnapin:prechatUI
Add the lightning:prechatUI interface to a Lightning component to enable Snap-ins to identify it as a custom Lightning page
template that can be used for the Snap-ins Chat pre-chat page. This interface has no effect except when used within Snap-ins Chat
hosted on a website, Visualforce page, or Community (using the Snap-ins Chat Community component).
This interface is a marker interface. A marker interface is a signal to the component’s container to add the interface’s behavior to the
component. You don’t need to implement any specific methods or attributes in your component, you simply add the interface name
to the component’s implements attribute.
In this case, the interface doesn’t add behavior but makes the custom component available as a pre-chat page from Snap-ins Setup.
Without this interface, the component doesn’t appear as a pre-chat page option in Snap-ins Setup. Use this interface with the
lightningsnapin:prechatAPI component to enable customization of your pre-chat user interface experience in Snap-ins
for web.
Example: This example shows the markup required to implement the lightningsnapin:prechatUI interface.
<aura:component implements="lightningsnapin:prechatUI">
<!-- ... -->
</aura:component>
Event Reference
Use out-of-the-box events to enable component interaction within Lightning Experience or the Salesforce app, or within your Lightning
components. For example, these events enable your components to open a record create or edit page, or navigate to a record.
Events belong to different namespaces, including:
force
Provides events that are handled by Lightning Experience and the Salesforce app.
forceCommunity
Provides events that are handled by Communities.
lightning
Provides events that are handled by Lightning Experience, the Salesforce app, and Communities.
ltng
Provides events that send the record ID or generic message to another component.
ui
Provides events that are handled by the legacy ui components.
wave
Provides events that are handled by Wave Analytics.
If you fire one of these force or lightning events in your Lightning apps or components outside of the Salesforce app or Lightning
Experience:
678
Reference force:closeQuickAction
• You must handle the event by using the <aura:handler> tag in the handling component.
• Use the <aura:registerEvent> or <aura:dependency> tags to ensure that the event is sent to the client, when
needed.
SEE ALSO:
aura:dependency
Events Handled in the Salesforce mobile app and Lightning Experience
Fire Component Events
Fire Application Events
force:closeQuickAction
Closes a quick action panel. Only one quick action panel can be open in the app at a time.
To close a quick action panel, usually in response to completing or canceling the action, run
$A.get("e.force:closeQuickAction").fire();.
This example closes the quick action panel after processing the input from the panel’s user interface and displaying a “toast” message
with the processing results. While the processing and the toast are unrelated to closing the quick action, the sequence is important.
Firing force:closeQuickAction should be the last thing your quick action handler does.
/*quickAddController.js*/
({
clickAdd: function(component, event, helper) {
})
Note: This event is handled by the one.app container. It’s supported in Lightning Experience and the Salesforce app only.
force:createRecord
Opens a page to create a record for the specified entityApiName, for example, “Account” or “myNamespace__MyObject__c”.
679
Reference force:createRecord
To display the record create page for an object, set the object name on the entityApiName attribute and fire the event.
recordTypeId is optional and, if provided, specifies the record type for the created object. defaultFieldValues is optional
and, if provided, specifies values to use to prepopulate the create record form.
This example displays the record create panel for contacts.
createRecord : function (component, event, helper) {
var createRecordEvent = $A.get("e.force:createRecord");
createRecordEvent.setParams({
"entityApiName": "Contact"
});
createRecordEvent.fire();
}
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, the Salesforce app, and Lightning
communities. This event presents a standard page to create a record. That is, it doesn’t respect overrides on the object’s create
action.
You can specify values for fields even if they’re not available in the create record form.
• If the field is hidden because it’s not on the page layout, the value specified in defaultFieldValues is saved with the new
record.
• If the current user doesn’t have create access to the field, due to field-level security, attempts to save the new record result in an
error.
Important: Error messages can’t reference fields the current user doesn’t have access to. This constraint means the user won’t
know why the error occurred or how to resolve the issue.
Firing the force:createRecord event tells the app to use the standard create record page. You can’t catch errors that
occur there, or alter the create page interface or behavior, for example, to show an improved error message. For this reason, it’s
essential to perform access checks in your own code, before firing the event.
You can’t prepopulate system-maintained fields, such as Id or record modification time stamps. Default values for these fields are
silently ignored.
Prepopulating rich text fields is unsupported. It might work for simple values, but the internal format of rich text fields is undocumented,
so setting complex values that include formatting is problematic. Use at your own risk.
680
Reference force:editRecord
Date and time field values must use the ISO 8601 format. For example:
• Date: 2017-07-18
• Datetime: 2017-07-18T03:00:00Z
Note: While the create record panel presents datetime values in the user’s local time, you must convert datetime values to UTC
to prepopulate the field.
defaultFieldValues String Prepopulates fields on a record create panel, including fields not displayed
on the panel. ID fields and rich text fields can’t be prepopulated. Users must
have create access to fields with prepopulated values. Errors during saving
that are caused by field access limitations don’t display error messages.
recordTypeId String The ID of the record type, if record types are available for the object.
force:editRecord
Opens the page to edit the record specified by recordId.
To display the record edit page for an object, set the object name on the recordId attribute and fire the event. This example displays
the record edit page for a contact that’s specified by recordId.
editRecord : function(component, event, helper) {
var editRecordEvent = $A.get("e.force:editRecord");
editRecordEvent.setParams({
"recordId": component.get("v.contact.Id")
});
editRecordEvent.fire();
}
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, the Salesforce app, and Lightning
communities.
force:navigateToComponent (Beta)
Navigates from one Lightning component to another.
Note: This release contains a beta version of force:navigateToComponent with known limitations.
To navigate from a Lightning component to another, specify the component name using componentDef. This example navigates
to a component c:myComponent and sets a value on the contactName attribute.
navigateToMyComponent : function(component, event, helper) {
var evt = $A.get("e.force:navigateToComponent");
681
Reference force:navigateToList
evt.setParams({
componentDef : "c:myComponent",
componentAttributes: {
contactName : component.get("v.contact.Name")
}
});
evt.fire();
}
When fired from a component embedded in Lightning Experience or Salesforce app, the app creates and renders the target component
in the app content area, replacing the current content. If you create a Lightning component tab and associate it directly with the
component, this event lets you navigate to the tab associated with the target component. To create a Lightning component tab and
associate it with the component, from Setup, enter Tabs in the Quick Find box, and then select Tabs.
This event doesn’t support target components that are embedded in another tab or in multiple tabs.
You can navigate only to a component that’s marked access="global" or a component within the current namespace.
Don’t depend on the URL generated by this event. It appears in the browser location bar and can be bookmarked, but the URL isn’t
permanent.
Note: This event is handled by the one.app container. It’s supported in Lightning Experience and Salesforce app only.
isredirect Boolean Specifies whether the navigation is a redirect. If true, the browser replaces
the current URL with the new one in the navigation history. This value
defaults to false.
force:navigateToList
Navigates to the list view specified by listViewId.
To navigate to a list view, set the list view ID on the listViewId attribute and fire the event. This example displays the list views for
contacts.
gotoList : function (component, event, helper) {
var action = component.get("c.getListViews");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
var listviews = response.getReturnValue();
var navEvent = $A.get("e.force:navigateToList");
navEvent.setParams({
"listViewId": listviews.Id,
"listViewName": null,
"scope": "Contact"
});
navEvent.fire();
}
});
682
Reference force:navigateToObjectHome
$A.enqueueAction(action);
}
This Apex controller returns all list views for the contact object.
@AuraEnabled
public static List<ListView> getListViews() {
List<ListView> listviews =
[SELECT Id, Name FROM ListView WHERE SobjectType = 'Contact'];
You can also provide a single list view ID by providing the list view name you want to navigate to in the SOQL query.
SELECT Id, Name FROM ListView WHERE SobjectType = 'Contact' and Name='All Contacts'
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning
communities.
listViewName String Specifies the name for the list view and doesn’t need to match the actual
name. To use the actual name that’s saved for the list view, set
listViewName to null.
scope String The name of the sObject in the view, for example, “Account” or
“namespace__MyObject__c”.
SEE ALSO:
CRUD and Field-Level Security (FLS)
force:navigateToObjectHome
Navigates to the object home specified by the scope attribute.
To navigate to an object home, set the object name on the scope attribute and fire the event. This example displays the home page
for a custom object.
navHome : function (component, event, helper) {
var homeEvent = $A.get("e.force:navigateToObjectHome");
homeEvent.setParams({
"scope": "myNamespace__myObject__c"
});
homeEvent.fire();
}
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, the Salesforce app, and Lightning
communities.
683
Reference force:navigateToRelatedList
resetHistory Boolean Resets history if set to true. Defaults to false, which provides a Back button
in the Salesforce app.
force:navigateToRelatedList
Navigates to the related list specified by parentRecordId.
To navigate to a related list, set the parent record ID on the parentRecordId attribute and fire the event. This example displays
the related cases on a record and assumes that your component implements the force:hasRecordId and
flexipage:availableForRecordHome interfaces. It uses the recordId attribute provided by the force:hasRecordId
interface. Implementing these interfaces means that you can drag-and-drop the component to the record pages you want via the
Lightning App Builder, such that it can navigate to related cases on an account record or contact record page, or any other record pages
that support the case related list.
gotoRelatedList : function (component, event, helper) {
var relatedListEvent = $A.get("e.force:navigateToRelatedList");
relatedListEvent.setParams({
"relatedListId": "Cases",
"parentRecordId": component.get("v.recordId")
});
relatedListEvent.fire();
}
Each object supports a subset of related lists. The page layout editor shows the related lists supported for each object. For example,
account records support these related lists: assets (Assets), cases (Cases), contacts (Contacts), opportunities (Opportunities),
among many others.
However, not all related lists are automatically available in your org. For example, the Contacts to Multiple Accounts feature must be
enabled for the “Related Contacts” (AccountContactRelations) related list to be available. To identify the relatedListId
value of a related list, navigate to the related list and observe the URL token /rlName/<relatedListId>/view that’s appended
to the Salesforce URL. However, don’t hard code the URL token in your component markup or JavaScript code as it might change in
future releases.
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning
communities.
relatedListId String The API name of the related list to display, such as “Contacts” or Yes
“Opportunities”.
force:navigateToSObject
Navigates to an sObject record specified by recordId.
To display the record view, set the record ID on the recordId attribute and fire the event.
684
Reference force:navigateToURL
The record view contains slides that display the Chatter feed, the record details, and related information. This example displays the related
information slide of a record view for the specified record ID.
Note: You can set a specific slide in the Salesforce app, but not in Lightning Experience.
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning
communities.
slideDevName String Specifies the slide within the record view to display initially. Valid options
are:
• detail: The record detail slide. This is the default value.
• chatter: The Chatter slide
• related: The related information slide
This attribute has no effect in Lightning Experience.
force:navigateToURL
Navigates to the specified URL.
Relative and absolute URLs are supported. Relative URLs are relative to the Salesforce mobile web domain, and retain navigation history.
External URLs open in a separate browser window.
Use relative URLs to navigate to different screens within your app. Use external URLs to allow the user to access a different site or app,
where they can take actions that don’t need to be preserved in your app. To return to your app, the separate window that’s opened by
an external URL must be closed when the user is finished with the other app. The new window has a separate history from your app,
and this history is discarded when the window is closed. This also means that the user can’t click a Back button to go back to your app;
the user must close the new window.
mailto:, tel:, geo:, and other URL schemes are supported for launching external apps and attempt to “do the right thing.”
However, support varies by mobile platform and device. mailto: and tel: are reliable, but we recommend that you test any other
URLs on a range of expected devices.
When using mailto: and tel: URL schemes, you can also consider using ui:outputEmail and ui:outputURL components.
685
Reference force:recordSave
This example navigates a user to the opportunity page, /006/o, using a relative URL.
gotoURL : function (component, event, helper) {
var urlEvent = $A.get("e.force:navigateToURL");
urlEvent.setParams({
"url": "/006/o"
});
urlEvent.fire();
}
//Find the text value of the component with aura:id set to "address"
var address = component.find("address").get("v.value");
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning
communities.
force:recordSave
Saves a record.
force:recordSave is handled by the force:recordEdit component. This examples shows a force:recordEdit
component, which takes in user input to update a record specified by the recordId attribute. The button fires the
force:recordSave event.
686
Reference force:recordSaveSuccess
Note: This event is handled by the one.app container. It’s supported in Lightning Experience and the Salesforce app only.
force:recordSaveSuccess
Indicates that the record has been successfully saved.
force:recordSaveSuccess is used with the force:recordEdit component. This examples shows a
force:recordEdit component, which takes in user input to update a record specified by the recordId attribute. The button
fires the force:recordSave event.
<aura:attribute name="recordId" type="String" default="a02D0000006V8Ni"/>
<aura:attribute name="saveState" type="String" default="UNSAVED" />
<aura:handler name="onSaveSuccess" event="force:recordSaveSuccess"
action="{!c.handleSaveSuccess}"/>
This client-side controller fires the event to save the record and handle it accordingly.
({
save : function(cmp, event) {
// Save the record
cmp.find("edit").get("e.recordSave").fire();
},
Note: This event is handled by the one.app container. It’s supported in Lightning Experience and the Salesforce app only.
force:refreshView
Reloads the view.
To refresh a view, run $A.get("e.force:refreshView").fire();, which reloads all data for the view.
This example refreshes the view after an action is successfully completed.
refresh : function(component, event, helper) {
var action = cmp.get('c.myController');
action.setCallback(cmp,
function(response) {
var state = response.getState();
if (state === 'SUCCESS'){
$A.get('e.force:refreshView').fire();
} else {
//do something
}
}
687
Reference force:showToast
);
$A.enqueueAction(action);
}
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning
communities.
force:showToast
Displays a toast notification with a message.
A toast displays a message below the header at the top of a view. The message is specified by the message attribute.
This example displays a toast message “Success! The record has been updated successfully.”.
Note: This event is handled by the one.app container. It’s supported in Lightning Experience, Salesforce app, and Lightning
communities.
The background color and icon used by a toast is controlled by the type attribute. For example, setting it to success displays the
toast notification with a green background and checkmark icon. This toast displays for 5000ms, with a close button in the top right
corner when the mode attribute is dismissible.
While message supports a text-only string, messageTemplate supports a string containing links. You can provide a string with
placeholders, which are replaced by labels provided in messageTemplateData. The parameters are numbered and zero-based.
For example, if you have three parameters, {0}, {1}, and {2}, the labels are substituted in the order they're specified. The label is also
used for the title attribute on the anchor tag.
This example displays a toast with a message that contains a link.
showMyToast : function(component, event, helper) {
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
mode: 'sticky',
message: 'This is a required message',
messageTemplate: 'Record {0} created! See it {1}!',
messageTemplateData: ['Salesforce', {
url: 'http://www.salesforce.com/',
label: 'here',
}
]
});
toastEvent.fire();
}
688
Reference forceCommunity:analyticsInteraction
messageTemplate String Overwrites message string with the specified message. Requires
messageTemplateData.
key String Specifies an icon when the toast type is other. Icon keys are available at
the Lightning Design System Resources page.
type String The toast type, which can be error, warning, success, or info.
The default is other, which is styled like an info toast and doesn’t display
an icon, unless specified by the key attribute.
mode String The toast mode, which controls how users can dismiss the toast. The default
is dismissible, which displays the close button.
Valid values:
• dismissible: Remains visible until you press the close button or
duration has elapsed, whichever comes first.
• pester: Remains visible until duration has elapsed. No close
button is displayed.
• sticky: Remains visible until you press the close buttons.
forceCommunity:analyticsInteraction
Tracks events triggered by custom components in Communities and sends the data to Google Analytics.
For example, you could create a custom button and include the forceCommunity:analyticsInteraction event in the
button's client-side controller. Clicking the button sends event data to Google Analytics.
onClick : function(cmp, event, helper) {
var analyticsInteraction = $A.get("e.forceCommunity:analyticsInteraction");
analyticsInteraction.setParams({
hitType : 'event',
eventCategory : 'Button',
eventAction : 'click',
eventLabel : 'Winter Campaign Button',
eventValue: 200
});
analyticsInteraction.fire();
}
Note:
• This event is supported in Lightning communities only. To enable event tracking, add your Google Analytics tracking ID in
Settings > Advanced in Community Builder and publish the community.
• Google Analytics isn’t supported in sandbox environments.
689
Reference forceCommunity:routeChange
eventCategory String Required. The type or category of item that was interacted with, such as a button or video.
eventAction String Required. The type of action. For example, for a video player, actions could include play,
pause, or share.
eventLabel String Can be used to provide additional information about the event.
forceCommunity:routeChange
The system fires the forceCommunity:routeChange event when a page’s URL changes. Custom Lightning components can
listen to this system event and handle it as required—for example, for analytics or SEO purposes.
lightning:openFiles
Opens one or more file records from the ContentDocument and ContentHubItem objects.
On desktops, the event opens the SVG file preview player, which lets you preview images, documents, and other files in the browser.
The file preview player supports full-screen presentation mode and provides quick access to file actions, such as upload, delete, download,
and share.
On mobile devices, the file is downloaded. If the device supports file preview, the device’s preview app is opened.
This example opens a single file.
openSingleFile: function(cmp, event, helper) {
$A.get('e.lightning:openFiles').fire({
recordIds: [component.get("v.currentContentDocumentId")]
});
}
690
Reference lightning:sendChatterExtensionPayload
Note: This event is supported in Lightning Experience, the Salesforce mobile web, and Lightning communities. It isn’t supported
in the deprecated Koa and Kokua community templates.
selectedRecordId String ID of the first record to open from the list specified in recordIds. If a value isn’t
provided or is incorrect, the first item in the list is used.
lightning:sendChatterExtensionPayload
Updates the payload and metadata that are saved during extension composition.
This event is used with the lightning:availableForChatterExtensionComposer and
lightning:availableForChatterExtensionRenderer interfaces.
Fields
Attribute Name Type Description Required?
payload Object Payload data to save with the feed item Yes
extensionTitle String App title to save with the feed item Yes
extensionDescription String App description to save with the feed item Yes
extensionThumbnailUrl String URL of the app thumbnail to save with the feed item No
SEE ALSO:
lightning:availableForChatterExtensionComposer
lightning:availableForChatterExtensionRenderer
Integrate Your Custom Apps into the Chatter Publisher
ltng:selectSObject
Sends the recordId of an object when it’s selected in the UI.
691
Reference ltng:sendMessage
To select an object, set the record ID on the recordId attribute. Optionally, specify a channel for this event so that your components
can select if they want to listen to particular event messages.
selectedObj: function(component, event) {
var selectedObjEvent = $A.get("e.ltng:selectSObject");
selectedObjEvent.setParams({
"recordId": "0061a000004x8e1",
"channel": "AccountsChannel"
});
selectedObj.fire();
}
channel String Specify this field if you want particular components to process some event messages
while ignoring others.
ltng:sendMessage
Passes a message between two components.
To send a message, specify a string of text that you want to pass between components. Optionally, specify a channel for this event so
that your components can select if they want to listen to particular event messages
sendMsg: function(component, event) {
var sendMsgEvent = $A.get("e.ltng:sendMessage");
sendMsgEvent.setParams({
"message": "Hello World",
"channel": "AccountsChannel"
});
sendMsgEvent.fire();
}
channel String Specify this field if you want particular components to process some event messages
while ignoring others.
ui:clearErrors
Indicates that any validation errors should be cleared.
To set a handler for the ui:clearErrors event, use the onClearErrors system attribute on a component that extends
ui:input, such as ui:inputNumber.
692
Reference ui:collapse
The following ui:inputNumber component handles an error when the ui:button component is pressed. You can fire and
handle these events in a client-side controller.
<aura:component>
Enter a number:
<!-- onError calls your client-side controller to handle a validation error -->
<!-- onClearErrors calls your client-side controller to handle clearing of errors -->
<!-- press calls your client-side controller to trigger validation errors -->
<ui:button label="Submit" press="{!c.doAction}"/>
</aura:component>
ui:collapse
Indicates that a menu component collapses.
For example, the ui:menuList component registers this event and handles it when it’s fired.
<aura:registerEvent name="menuCollapse" type="ui:collapse"
description="The event fired when the menu list collapses." />
You can handle this event in a ui:menuList component instance. This example shows a menu component with two list items. It
handles the ui:collapse and ui:expand events.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Contacts"/>
<ui:menuList class="actionMenu" aura:id="actionMenu"
menuCollapse="{!c.addMyClass}" menuExpand="{!c.removeMyClass}">
<ui:actionMenuItem aura:id="item1" label="All Contacts"
click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item2" label="All Primary" click="{!c.doSomething}"/>
</ui:menuList>
</ui:menu>
This client-side controller adds a CSS class to the trigger when the menu is collapsed and removes it when the menu is expanded.
({
addMyClass : function(component, event, helper) {
var trigger = component.find("trigger");
$A.util.addClass(trigger, "myClass");
},
removeMyClass : function(component, event, helper) {
var trigger = component.find("trigger");
$A.util.removeClass(trigger, "myClass");
}
})
693
Reference ui:expand
ui:expand
Indicates that a menu component expands.
For example, the ui:menuList component registers this event and handles it when it’s fired.
<aura:registerEvent name="menuExpand" type="ui:expand"
description="The event fired when the menu list displays." />
You can handle this event in a ui:menuList component instance. This example shows a menu component with two list items. It
handles the ui:collapse and ui:expand events.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Contacts"/>
<ui:menuList class="actionMenu" aura:id="actionMenu"
menuCollapse="{!c.addMyClass}" menuExpand="{!c.removeMyClass}">
<ui:actionMenuItem aura:id="item1" label="All Contacts"
click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item2" label="All Primary" click="{!c.doSomething}"/>
</ui:menuList>
</ui:menu>
This client-side controller adds a CSS class to the trigger when the menu is collapsed and removes it when the menu is expanded.
({
addMyClass : function(component, event, helper) {
var trigger = component.find("trigger");
$A.util.addClass(trigger, "myClass");
},
removeMyClass : function(component, event, helper) {
var trigger = component.find("trigger");
$A.util.removeClass(trigger, "myClass");
}
})
ui:menuFocusChange
Indicates that the user changed menu item focus in a menu component.
For example, this event is fired when the user scrolls up and down the menu list, which triggers a focus change in menu items. The
ui:menuList component registers this event and handles it when it’s fired.
You can handle this event in a ui:menuList component instance. This example shows a menu component with two list items.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Contacts"/>
<ui:menuList class="actionMenu" aura:id="actionMenu"
menuFocusChange="{!c.handleChange}">
<ui:actionMenuItem aura:id="item1" label="All Contacts" />
<ui:actionMenuItem aura:id="item2" label="All Primary" />
694
Reference ui:menuSelect
</ui:menuList>
</ui:menu>
ui:menuSelect
Indicates that a menu item has been selected in the menu component.
For example, the ui:menuList component registers this event so it can be fired by the component.
<aura:registerEvent name="menuSelect" type="ui:menuSelect"
description="The event fired when a menu item is selected." />
You can handle this event in a ui:menuList component instance. This example shows a menu component with two list items. It
handles the ui:menuSelect event and click events.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Contacts"/>
<ui:menuList class="actionMenu" aura:id="actionMenu" menuSelect="{!c.selected}">
<ui:actionMenuItem aura:id="item1" label="All Contacts"
click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item2" label="All Primary"
click="{!c.doSomething}"/>
</ui:menuList>
</ui:menu>
When a menu item is clicked, the click event is handled before the ui:menuSelect event, which corresponds to doSomething
and selected client-side controllers in the following example.
({
selected : function(component, event, helper) {
var selected = event.getParam("selectedItem");
deselectSiblings Boolean Deselects the siblings of the currently selected menu item
ui:menuTriggerPress
Indicates that a menu trigger is clicked.
695
Reference ui:validationError
For example, the ui:menuTrigger component registers this event so it can be fired by the component.
<aura:registerEvent name="menuTriggerPress" type="ui:menuTriggerPress"
description="The event fired when the trigger is clicked." />
You can handle this event in a component that extends ui:menuTrigger, such as in a ui:menuTriggerLink component
instance.
<ui:menu>
<ui:menuTriggerLink aura:id="trigger" label="Contacts"
menuTriggerPress="{!c.triggered}"/>
<ui:menuList class="actionMenu" aura:id="actionMenu">
<ui:actionMenuItem aura:id="item1" label="All Contacts"
click="{!c.doSomething}"/>
<ui:actionMenuItem aura:id="item2" label="All Primary" click="{!c.doSomething}"/>
</ui:menuList>
</ui:menu>
This client-side controller retrieves the label of the trigger when it’s clicked.
({
triggered : function(component, event, helper) {
var trigger = component.find("trigger");
ui:validationError
Indicates that the component has validation errors.
To set a handler for the ui:validationError event, use the onError system attribute on a component that extends ui:input,
such as ui:inputNumber.
The following ui:inputNumber component handles an error when the ui:button component is pressed. You can fire and
handle these events in a client-side controller.
<aura:component>
Enter a number:
<!-- onError calls your client-side controller to handle a validation error -->
<!-- onClearErrors calls your client-side controller to handle clearing of errors -->
<!-- press calls your client-side controller to trigger validation errors -->
<ui:button label="Submit" press="{!c.doAction}"/>
</aura:component>
696
Reference wave:discoverDashboard
wave:discoverDashboard
This event sends a global request to listening Analytics dashboard assets to respond with their identifying information. You can optionally
include your own parameter that will be included in the response.
The wave:discoverDashboard and wave:discoverResponse events work hand-in-hand, and are particularly useful for
discovering when a dashboard is being added dynamically to the page, or whether there are multiple dashboards on the page.
This event has one attribute; an optional identifier that will be included in the response data.
In this example, the Lightning component has already been defined, handlers have been set, and the wave:discoverDashboard
and wave:discoverResponse events have been registered in the custom component markup. The controller code below shows
how to fire the wave:discoverDashboard event, and how to use the result when the wave:discoverResponse event
is fired. The code also shows how to create dashboard components.
({
addDashboard: function(component, event, helper) {
var selectCmp = component.find("idTextBox");
component.set("v.dashboardId", selectCmp.get("v.value"));
var config = {
"dashboardId": selectCmp.get("v.value"),
"showHeader": false,
"height": 400
};
$A.createComponent("wave:waveDashboard", config,
function(dashboard, status, err) {
if (status === "SUCCESS") {
dashboard.set("v.rendered", true);
dashboard.set("v.showHeader", false);
component.set("v.body", dashboard);
697
Reference wave:discoverResponse
For more information about using the Analytics SDK with Lightning, see the Analytics SDK Developer Guide.
wave:discoverResponse
This event provides the response following a request for Analytics dashboards to identify their assets.
This event payload has five attributes; the unique ID of the dashboard, the component type, the dashboard title, the dashboard load
status, and an optional parameter if it was sent the the request.
The wave:discoverDashboard and wave:discoverResponse events work hand-in-hand, and are particularly useful for
discovering when a dashboard is being added dynamically to the page, or whether there are multiple dashboards on the page.
Refer to the wave:discoverDashboard event for details and an example using wave:discoverResponse.
UID String Optional parameter that was sent with the request, if present.
For more information about using the Analytics SDK with Lightning, see the Analytics SDK Developer Guide.
wave:selectionChanged
Event fired by a Wave dashboard. It provides selection information including the name of the step involved, and an array of objects
representing the current selection.
In this example, the Lightning component has already been defined and everything has been registered, so this controller code shows
how to receive and iterate through the payload. The payload is an array of objects representing the current selection.
({
handleselectionChanged: function(component, event, helper) {
var params = event.getParams();
var payload = params.payload;
if (payload) {
var step = payload.step;
var data = payload.data;
data.forEach(function(obj) {
for (var k in obj) {
if (k === 'Id') {
component.set("v.recordId", obj[k]);
698
Reference wave:update
}
}
});
}
}
})
noun String The type of the Wave asset for which a selection event occurred. Currently, only
dashboard is supported.
payload String Contains the selection information from the asset that fired the event.
payload.step (String). The name of the step in which the selection occurred.
payload.data (Object array). An array of objects representing the current selection.
Each object in the array contains one or more attributes based on the selection.
verb String The action that occurred on the Wave asset. Currently, only selection is supported.
For more information about using the Analytics SDK with Lightning, see the Analytics SDK Developer Guide.
wave:update
This event is used to set the filter on a Wave Analytics dashboard, or to interact with that dashboard by dynamically changing the
selection.
This event has three attributes; the unique ID of the Wave asset on which to apply the filter, the payload, and the asset type (currently
only dashboard). The payload is a JSON string that identifies the datasets, and any dimensions and field values.
In this example, the Lightning component has already been defined, handlers have been set, and the update event has been registered
in the custom component markup. The controller code below shows how to construct the payload for the update event—in this case,
setting StageName to Close Won in the oppty_test dashboard.
({
doInit: function(component, event, helper) {
component.set('v.filter', '{"oppty_test": {"StageName": ["Closed Won"]}}');
},
699
Reference System Event Reference
}
})
value String The JSON representing the filter or selection to be applied to the asset.
type String The type of the Wave asset. Currently, only dashboard is supported.
For more information about using the Analytics SDK with Lightning, see the Analytics SDK Developer Guide.
aura:doneRendering
Indicates that the initial rendering of the root application has completed.
Note: We don't recommend using the legacy aura:doneRendering event except as a last resort. Unless your component
is running in complete isolation in a standalone app and not included in complex apps, such as Lightning Experience or the
Salesforce app, you probably don’t want to handle this application event. The container app may trigger your event handler
multiple times.
This event is automatically fired if no more components need to be rendered or rerendered due to any attribute value changes. The
aura:doneRendering event is handled by a client-side controller. A component can have only one <aura:handler> tag
to handle this event.
<aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>
For example, you want to customize the behavior of your app after it’s finished rendering the first time but not after subsequent
rerenderings. Create an attribute to determine if it’s the first rendering.
<aura:component>
<aura:handler event="aura:doneRendering" action="{!c.doneRendering}"/>
<aura:attribute name="isDoneRendering" type="Boolean" default="false"/>
<!-- Other component markup here -->
<p>My component</p>
</aura:component>
This client-side controller checks that the aura:doneRendering event has been fired only once.
({
doneRendering: function(cmp, event, helper) {
if(!cmp.get("v.isDoneRendering")){
cmp.set("v.isDoneRendering", true);
700
Reference aura:doneWaiting
Note: When aura:doneRendering is fired, component.isRendered() returns true. To check if your element is
visible in the DOM, use utilities such as component.getElement(), component.hasClass(), or
element.style.display.
The aura:doneRendering handler contains these required attributes.
action Object The client-side controller action that handles the event.
aura:doneWaiting
Indicates that the app is done waiting for a response to a server request. This event is preceded by an aura:waiting event. This
event is fired after aura:waiting.
Note: We don't recommend using the legacy aura:doneWaiting event except as a last resort. The aura:doneWaiting
application event is fired for every server response, even for responses from other components in your app. Unless your component
is running in complete isolation in a standalone app and not included in Lightning Experience or the Salesforce app, you probably
don’t want to handle this application event. The container app may fire server-side actions and trigger your event handler multiple
times.
This event is automatically fired if no more response from the server is expected. The aura:doneWaiting event is handled by a
client-side controller. A component can have only one <aura:handler> tag to handle this event.
<aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>
701
Reference aura:locationChange
action Object The client-side controller action that handles the event.
aura:locationChange
This event is automatically fired when the hash part of the URL has changed.
Use an <aura:handler> tag to react to a hash value change. A component can have only one <aura:handler
event="aura:locationChange"> tag to handle this event.
This client-side controller handles the aura:locationChange event. In this example, the handler is wired to the update action.
({
update : function (component, event, helper) {
// Get the new hash from the event
var loc = event.getParam("token");
// Do something else
}
})
action Object The client-side controller action that handles the event.
aura:systemError
Indicates that an error has occurred.
This event is automatically fired when an error is encountered during the execution of a server-side action. The aura:systemError
event is handled by a client-side controller. A component can have only one <aura:handler event="aura:systemError">
tag in markup to handle this event.
<aura:handler event="aura:systemError" action="{!c.handleError}"/>
702
Reference aura:valueChange
This example shows a button that triggers an error and a handler for the aura:systemError event .
<aura:component controller="namespace.myController">
<aura:handler event="aura:systemError" action="{!c.showSystemError}"/>
<aura:attribute name="response" type="Aura.Action"/>
<!-- Other component markup here -->
<ui:button aura:id="trigger" label="Trigger error" press="{!c.trigger}"/>
</aura:component>
This client-side controller triggers the firing of an error and handles that error.
({
trigger: function(cmp, event) {
// Call an Apex controller that throws an error
var action = cmp.get("c.throwError");
action.setCallback(cmp, function(response){
cmp.set("v.response", response);
});
$A.enqueueAction(action);
},
The aura:handler tag for the aura:systemError event contains these required attributes.
action Object The client-side controller action that handles the event.
The aura:systemError event contains these attributes. You can retrieve the attribute values using
event.getParam("attributeName").
SEE ALSO:
Throwing and Handling Errors
aura:valueChange
Indicates that an attribute value has changed.
703
Reference aura:valueDestroy
This event is automatically fired when an attribute value changes. The aura:valueChange event is handled by a client-side
controller. A component can have multiple <aura:handler name="change"> tags to detect changes to different attributes.
<aura:handler name="change" value="{!v.items}" action="{!c.itemsChange}"/>
This example updates a Boolean value, which automatically fires the aura:valueChange event.
<aura:component>
<aura:attribute name="myBool" type="Boolean" default="true"/>
These client-side controller actions trigger the value change and handle it.
({
changeValue : function (component, event, helper) {
component.set("v.myBool", false);
},
The valueChange event gives you access to the previous value (oldValue) and the current value (value) in the handler action.
In this example, oldValue returns true and value returns false.
The change handler contains these required attributes.
value Object The attribute for which you want to detect changes.
action Object The client-side controller action that handles the value change.
SEE ALSO:
Detecting Data Changes with Change Handlers
aura:valueDestroy
Indicates that a component has been destroyed. Handle this event if you need to do custom cleanup when a component is destroyed.
This event is automatically fired when a component is being destroyed. The aura:valueDestroy event is handled by a client-side
controller.
A component can have only one <aura:handler name="destroy"> tag to handle this event.
<aura:handler name="destroy" value="{!this}" action="{!c.handleDestroy}"/>
704
Reference aura:valueInit
Let’s say that you are viewing a component in the Salesforce app. The aura:valueDestroy event is triggered when you tap on
a different menu item on the Salesforce mobile navigation menu, and your component is destroyed. In this example, the value
parameter in the event returns the component that’s being destroyed.
The <aura:handler> tag for the aura:valueDestroy event contains these required attributes.
value Object The value for which you want to detect the event for. The value that is being destroyed.
Always set value="{!this}".
action Object The client-side controller action that handles the destroy event.
aura:valueInit
Indicates that an app or component has been initialized.
This event is automatically fired when an app or component is initialized, prior to rendering. The aura:valueInit event is handled
by a client-side controller. A component can have only one <aura:handler name="init"> tag to handle this event.
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
Note: Setting value="{!this}" marks this as a value event. You should always use this setting for an init event.
value Object The value that is initialized, which must be set to {!this}.
705
Reference aura:valueRender
SEE ALSO:
Invoking Actions on Component Initialization
aura:valueRender
aura:valueRender
Indicates that an app or component has been rendered or rerendered.
This event is automatically fired when an app or component is rendered or rerendered. The aura:valueRender event is handled
by a client-side controller. A component can have only one <aura:handler name="render"> tag to handle this event.
<aura:handler name="render" value="{!this}" action="{!c.onRender}"/>
In this example, the onRender action in your client-side controller handles initial rendering and rerendering of the component. You
can choose any name for the action attribute.
Note: Setting value="{!this}" marks this as a value event. You should always use this setting for a render event.
The render event is fired after the init event, which is fired after component construction but before rendering.
The aura:valueRender event contains one attribute.
SEE ALSO:
aura:valueInit
Events Fired During the Rendering Lifecycle
aura:waiting
Indicates that the app is waiting for a response to a server request. This event is fired before aura:doneWaiting.
Note: We don't recommend using the legacy aura:waiting event except as a last resort. The aura:waiting application
event is fired for every server request, even for requests from other components in your app. Unless your component is running
in complete isolation in a standalone app and not included in Lightning Experience or the Salesforce app, you probably don’t want
to handle this application event. The container app may fire server-side actions and trigger your event handler multiple times.
This event is automatically fired when a server-side action is added using $A.enqueueAction() and subsequently run, or when
it’s expecting a response from an Apex controller. The aura:waiting event is handled by a client-side controller. A component can
have only one <aura:handler> tag to handle this event.
<aura:handler event="aura:waiting" action="{!c.showSpinner}"/>
706
Reference Supported HTML Tags
action Object The client-side controller action that handles the event.
We recommend that you use components in preference to HTML tags. For example, use lightning:button instead of <button>.
Components are designed with accessibility in mind so users with disabilities or those who use assistive technologies can also use your
app. When you start building more complex components, the reusable out-of-the-box components can simplify your job by handling
some of the plumbing that you would otherwise have to create yourself. Also, these components are secure and optimized for performance.
Note that you must use strict XHTML. For example, use <br/> instead of <br>.
Some HTML tags are unsafe or unnecessary. The framework doesn’t support these tags.
The HtmlTag enum in this open-source Aura file lists the supported HTML tags. Any tag followed by (false) is not supported.
For example, applet(false) means the applet tag isn't supported.
707
Reference Anchor Tag: <a>
Note: The linked file is in the master branch of the open-source Aura project. The master branch is our current development
branch and is ahead of the current release of the Lightning Component framework. However, this file changes infrequently and
is the best place to see if a tag is supported now or in the near future.
SEE ALSO:
Supporting Accessibility
If you use # in the href attribute, a secondary issue occurs. The hash mark (#) is a URL fragment identifier and is often used in Web
development for navigation within a page. Avoid # in the href attribute of anchor tags in Lightning components as it can cause
unexpected navigation changes, especially in the Salesforce app. That’s another reason not to use href.
708
Reference Anchor Tag: <a>
The record ID is passed into c:navToRecord by setting its recordId attribute. When c:navToRecord is used in Lightning
Experience, Salesforce app, or Lightning communities, the link navigates to the specified record.
709
INDEX
710
Index
aura:component 412
aura:dependency 413
C
Capture 194, 205
aura:doneRendering 700
Change handlers 303, 703
aura:doneWaiting 701
change handling 345
aura:event 414
Chrome extension 381
aura:expression 419
CLI
aura:html 420
custom rules 238
aura:if 38, 43, 420
Client-side controllers 187
aura:interface 415
Cloud Flow Designer
aura:iteration 421
configuring design resource 107
aura:locationChange 702
Communities 182
aura:method
Communities Lightning components
result asynchronous code 294
overview 140
result synchronous code 292
Community Builder
aura:renderIf 422
configuring custom components 140
aura:set 417–418
content layouts 144
aura:systemError 702
forceCommunity:analyticsInteraction 689
aura:template 224, 422
forceCommunity:routeChange 690
aura:text 423
lighting:openFiles 690
aura:unescapedHtml 423
Lightning components overview 140
aura:valueChange 703
profile menu 143
aura:valueDestroy 704
search 143
aura:valueInit 705
theme layouts 141
aura:valueRender 706
Component
aura:waiting 706
abstract 377
Aura.Action 410
attributes 33
AuraLocalizationService 310
aura:component 412
auraStorage:init 423
aura:interface 415
authentication
body, setting and accessing 36
guest access 182
documentation 68
B nest 34
rendering 706
Benefits 2
rendering lifecycle 216
Best practices
themes, vendor prefixes 253
events 215
Component attributes
Body
inheritance 375
JavaScript 276
Component body
Browsers
JavaScript 276
Lightning components 4
Component bundles
limited support 4
configuring design resources 107
recommendations 4
configuring design resources for Lightning Pages 132
requirements 4
configuring for Community Builder 140
supported versions 4
configuring for Lightning App Builder 124, 126, 139, 252
Bubbling 194, 205
configuring for Lightning Experience Record Home pages
Buttons
139
lightning:button 309
configuring for Lightning Experience record pages 126
local ID 309
configuring for Lightning pages 124, 126, 139, 252
pressed 309
create dynamic picklists for components on Lightning Pages
ui:button 309
132
711
Index
712
Index
713
Index
714
Index
715
Index
716
Index
N S
Namespace Salesforce app
creating 26 add Lightning components 111
default 25 Salesforce DX 237, 240, 248
examples 26 Salesforce Lightning Design System 249
explicit 25 Salesforce Lightning Inspector
implicit 25 Actions tab 390
organization 25 Component Tree tab 383
prefix 25 drop the action 394
Node.js 177 error response 393
Notices 664 Event Log tab 388
Notifications 664 install 382
modify action response 392
O override actions 391
OAuth 181 Performance tab 386
Object-oriented development Storage tab 395
inheritance 375 Transactions tab 387
Online version 6 use 382
Open source 4 SaveRecordResult 353
Overlay 666 Secure wrappers
JavaScript API 230
P Security 224
Package 24–26 Server-Side Controllers
Packaging action queueing 319
action override 123 calling actions 317, 319
Performance warnings creating 314
<aura:if> 397 errors 315
<aura:iteration> 398 overview 313
Popover 666 results 314
Prerequisites 9 returning data 314
Promises 296 sfdx 237–238, 240, 243–248
Proxy object 227 SharePoint 177
SLDS 249
Q Standard Actions
Queueing Lightning components 119, 121–123
queueing server-side actions 319 override 119, 121–123
packaging 123
R standard controller 334, 346–347, 349, 353, 430
Reference States 319
Components 411, 419 Static resource 52, 272
overview 401 Storable actions
Renderers 281 enable 323
Rendering 706 lifecycle 322
Rendering lifecycle 216 Storage service
Rerendering 286, 706 adapters 324
Rich Publisher Apps 170 Memory adapter 324
rules 242–248 SmartStore 324
WebSQL 324
Strict mode 225
717
Index
718
Index
719
Index
720