0% found this document useful (0 votes)
323 views

Programming Lightning Components - Students Guide PDF

Uploaded by

Anil S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
323 views

Programming Lightning Components - Students Guide PDF

Uploaded by

Anil S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 444
TRAILHEAD ° AGENDA «Programming Lightning Components>> Day One 15 minutes Introductions 30 minutes Introducing the Course About the Course Reviewing the Course Objectives Reviewing the Course Prerequisites Reviewing the System Requirements Improving Productivity with Chrome Plugins Reviewing the Class Project Reviewing the Data Schema Reviewing the Application Exercise 1-1: Meeting the Prerequisites (15 min) 290 minutes Getting Started + Using HTMLS and Lightning Components io Develop Apps Your Turn 2-1 (10 min): Reviewing Available Components + Gotting Started with Lightning Development Your Turn 2-2 (15 min): Creating and Deploying a Lightning Component + Theming Components with CSS Your Turn 2-3 (15 min): Theming a Lightning Component + Defining and Manipulating Component Attributes Your Turn 2-4 (30 min): Working with Component Attributes + Handling System and User Events Your Turn 2-5 (15 min): Handling Events + Debugging and Troubleshooting Your App Your Tum 2-6 (15 min): Debugging your Code + Working with Apex Your Turn 2-7 (20 min): Working with Apex + Using Base Lightning Components Your Turn 2-8 (30 min): Working with Base Lighining Compononts 15 minutes Wrap Up ‘Agonda eubjoctto chango, 120 minutes 180 minutes 60 minutes 15 minutes ‘Agonda eubjoctto chango, AGENDA «Programming Lightning Components>> Day Two Getting Started (continued) Raising and Handling Events Your Turn 2-9 (60 min): Working with Component and Application Events = Using Lightning Data Service for CRUD Operations Your Turn 2-10 (25 min): Using Lightning Data Service Lab: Using Lightning Data Service = Outputting Data from Lightning Data Service (40 min) = Using Lightning Data Service CRUD Operations (45 min) = Reading and Outputting Dynamic Data (30 min) Documenting and Unit Testing Components = Documenting 2 Component Your Turn 3-1 (16 min): Documenting a Component + Testing and Troubleshooting Apex Your Turn 3-2: Surfacing a Component in App Builder (15 min) Wrap Up AGENDA «Programming Lightning Components>> Day Three 210 minutes, Surfacing Lightning Components = Surfacing Lightning Components Your Turn 4-1 (20 min) = Deep-Diving into Building Lightning Pages with Components ‘and App Builder Your Turn 4-2: Surfacing a Component in App Builder (35min) + Building Components for Lightning Experience Record Pages Your Turn 4-3: Building Components for Lightning Experience Record Pages (30 min) + Overriding Standard Actions with Lightning Components Your Turn 4-4 (15 min): Overriding Standard Actions + Defining a Lightning Application Your Turn 4-5 (10 min): Creating 2 Lightning Application Using Lightning in Visualforce Pages with Lightning Out Your Turn 4-6 (15 min): Surfacing a Component in Visuatforce Pages ‘Installing and Using Components from AppExchange Your Turn 4-7 (10 min): Using @ Component from App Your Turn 4-8 (10 min): Creating an Unmanaged Package 200 minutes, Implementing Navigation and Layouts =” Using Your Turn §-1 (45 min): Implementing Vertical Navigation + Using lightning dataTable Your Tura &-2 (45 min): Using + Implementing Button Groups Your Turn §-3 (45 min): Implomenting Button Groups 15 minutes Wrap Up ‘Agonda eubjoctto chango, = 200 minutes 200 minutes 16 minutes ‘Agonda eubjoctto chango, AGENDA «Programming Lightning Components>> Day Four Implementing Navigation and Layouts (con't) = Building Responsive Layouts Your Turn 5-4 (20 min): Creating a Repsonsive Layout + Implementing Accordion Layouts Your Turn 5-5 (35 min): Implementing Accordion Layouts Building Advanced Components = Accessing the Component Body Join Me 6-1 (35 min): Creating a Modal Dialog Box + Defining Public Functions on Components Join Me 6-2 (20 min): Using Custom Events and Pubic Methods = Implementing Toasts and Model Notifications Your Turn 6-3 (35 min): Implomenting Notifications and Toasts + Dynamically Instantiating and Destroying Component Instances Your Turn 6-4 (30 min): Dynamically Instantiating Components + Localizing Content Your Turn 6-5 (20 min): Localizing Content + Using Renderers + Writing Device-Specific Code Wrap Up AGENDA «Programming Lightning Components>> Day Five 245 minutes, Creating, Reading, and Updating Salesforce Records Implementing Forms Join Me 7-1 (60 min): Implementing Forms + Validating Input Data Join Me 7-2 (30 min): Validating Form Data + Viewing and Editing Salesforce Records Your Tum 7-3 (75 min): Viewing and Editing Salestorce Records + Waiting for Server Requests to Complete Your Turn 7-4 (20 min): Wailing for Server Requests to Complete 160 minutes Getting Ready for Production (optional unit) + Thoming with Lightning Design Tokons Your Turn 8-1 (15 min): Using Lightning Design Tokens + Improving the Performance of Data Requests Your Turn 6-2 (15 min): Caching Data ‘Agonda eubjoctto chango, Unit 1 Table of Contents About the Course Reviewing the Course Objectives Reviewing the Course Prerequisites Reviewing the Sysiem Requirements Reviewing the Course Format Improving your Productivity with Chrome Plugins Reviewing the Class Project Roviowing the Data Schema Exorcise 1-1: Meoting tho Prorecuisites Stops Unit Summary Programming Lightning Components ‘Section 1 (©2018 salesforce.com, ine. Page2 Introducing the Course Introducing the Course About the Course ‘Section 1 DEV801: Programming Lightning Components is an instructor-led course ‘designed to intraduce you to the fundamental concepts of building high- performing, device-independent, HTML5-based applications that ‘communicate interactively with the Salesforce platform-as-a-service, ‘The course Is designed to be followed in sequence. Solutions are provided for each exercise to help you if you get “stuck” on a particular step. Figure 1: Your project ‘Today you wil build a desktop and mobile-compatible application to help trainers for the fictional AW Training Company manage their schedule and keep in contact with their students. Application features include: Dependent select boxes Invoking native Salesforce layouts ‘Assembly with Lightning App Builder ‘A dynamic query-by-example interface Note: This course is compatible with the Winter 2018 release. (©2018 salesforce.com, inc. Pages Programming Lightning Components Reviewing the Course Objectives After completing this course, you should be able to: + Efficiently create custom, reusable Lighining components ‘+ Surface Lightning components as custom tabs in Lightning Experience. + Build a Salesforce mobile applicaton that marshals data from your org. ‘+ Theme your application by using the Selesforce Lightning Design System, + Use the Salesforce Lightning Data Service to perform CRUD ‘operations on Salesforce record objects (sObjects) Reviewing the Course Prerequisites ‘The knowledge prerequisites for this course are: 1. Intermediate-level knowledge of JavaScript 2. Familiarity with HTMLS / CSS3 concepts. 3. Basic understanding of the Salesforce platform, Reviewing the System Requirements ‘Section 1 To participate in this course, you will need to have access to the following hardware and software resources: 1. Microsoft Windows 10 / Apple MacOS 10.11.6 (El Capitan) 2. Google Chrome 60 or later 3. Salesforce org login credentials provided by your instructor 4 ‘A mobile phone running either iOS or Android with the Salesforce App installed (optional) (©2018 salesforce.com, ine. Pages Introducing the Course Reviewing the Course Format mop 6 & ‘Section 1 This course is divided into several units, each of which presents new information and may contain demonstrations and exercises. At the end of each unit, you will ind a summary and a short review to tost your knowledge of the unit's content. The following icons are used throughout the guide: Concepts introduce new information and illustrate coding syntax and best praciices. Walkthroughs guide you through procedures in a hands-on context. Labs let you practice new skils on your own. ‘Summaries provice a briet synopsis of the unit's content. Reviews test how well you remember the concepts from the unit. Best Practices provide you with helpful insights and information, (©2018 salesforce.com, inc. Pages Programming Lightning Components Improving your Productivity with Chrome Plugins During this course you will use a variety of tools to create and troubleshoot your application. To improve your productivity in working with the platform ‘you will instal the following plugins for Google Chrome: + Clear Cacho (http:!bit.ly/1027eJR) The Clear Cache Plugin places a button on your browser's address bar that enables you to quickly clear your cache without any confirmation dialogs, pop-ups or other annoyances, © Force.com Logins (http:/bit.ly/tJylvfq) This plugin places a button on Chrome's address bar that enables you to login to the Salesforce Platform with a few clicks of your mouse. + Lightning Components inspector (http:/bit.ly/1MImLxpr) This plugin attaches to Google Chrome's detuager and enables you to easily introspect components that have been instantiated, review application performance, and much more! + Lightning Linter Plugin (http:!/bit.ly/2pvi2XB) Lightning Lintor exposes the lint endpoint of https: lightring- linter herokuapp.com to Developer Console. It validates your JavaScript in near realtime, outputting error messages to the Developer Console's Problems tab. ‘Section 1 (©2018 salesforce.com, ine. Page 6 Reviewing the Class Project ‘Section 1 Introducing the Course During this 5-day course you will create over a dozen components, including the following: Figure 2: Component wireframe Description StudentBrowser Defines the layout for the left-side of tha application. Invokes the StudentBrowserForm and StudentTies components StudentBrowserForm A simple query-by-exemple form with dependent, dynamically populated select boxes. StudentTiles Uses a responsive, column-based layout manager. lterates through data retrieved from the Salesforce Platform to dynamically generate and pass data to ‘StudentTile components. StudentTile A clickable button coniaining a contact’s photo if they've linked to social media. StudentDetail Displays information about the selected user. You enhance the output in Dev601 Programing Lightning Components. You will share code between the components by developing an abstract ‘component named Base and commuricate between the components by defining, fring, and listening for component and application events. (©2018 salesforce.com, inc. Page Programming Lightning Components Reviewing the Home Page The application “home” page contains a query-by-example interface that enables a user to locate students based upon which courses they taught land their instuctors. Clicking on a student name displays contact information in a pod on the right-side. At the bottom-right, a pod displays their cless attendance history and notes about them that the instructor captured during the course. ere Figure 3: Application "Home" Page Reviewing the Home Page Student Gallery ‘Tho Home Page Gallery View, as depicted in Figure 4, renders photos of the students (if available) as clickable buttons. Figure 4: Home Page "Gallery" View ‘Section 1 (©2018 salesforce.com, inc. Page 8 Introducing the Course Reviewing the Student Certification View ‘The Student Certification View, as ilustrated in Figure 5, shows a filtered list of students by the certifications thet they have eared. This view ‘enables a user 10 select multiple certifications and delete them as a batch. Figure 5: Studont Cortificaton View Reviewing the Trip Reports View ‘The Trip Reports View, depicted in Figure 6, displays @ list of reviews that instructors have written about restaurants, training centers, and their students. Figure 6: Trip Reports View ‘Section 1 (©2018 salesforce.com, inc. Page Programming Lightning Components Reviewing the Trip Reports Form The Trip Reports Form, depicted in Figure 7, enables instructors to add new reviews. It also cisplays a chatter feed containing helpful news. Figure 7: Trip Reports Form ‘Section 1 (©2018 salesforce.com, inc. Page 10 Introducing the Course Reviewing the Data Schema During this course you'll work with the Selesforce objects illustrated in Figure 8. You will also create a custom object named "TripReport” Figure 8: Data Schema Object Name Description User ‘Standard Object. Contains information about Salesforce Users. The Is_Insiructor_c fleld identifies insiructors. Contact ‘Standard Object. Contains contact information for students, Course_¢ Custom Object. Contains the list of courses that may be taught. Course_Delivery_¢ | Custom Object. Contains the dates, location, instructor, and start date for each course that was taught. Course_Attendee_¢ | The course attendees. In a Master-Detail relationship with the Course Delivery _c object ‘Section 1 (©2018 salesforce.com, inc. Page 11 Programming Lightning Components Exercise 1-1: Meeting the Prerequisites Steps ‘Section 1 During this exercise, you will install and configure the required software for the course. ‘+ Install and Configure Google Chrome + Download the Exercise Files + Install Chrome Extensions + Configure your User Account + Register a custom domain for your org + Enable Lightning Experience Install and Configure Google Chrome 1. Download and install Google Chrome from: https: //uww. google .com/int1/en/chrome/bro p/index. nem, Open Google Chrome 3. Enter the following URL: ser /deskto chrone://£lage/#enable-serol anchoring Set "Scroll Anchoring’ to "Disabled" 5. Click the Relauneh Now button Download the Exercise Files 6. Login to your Salesforce ora, using the credentials that were given to ‘you by your instructor. Select + | Files | Owned by Me Download the Dev601_ProgrammingLightningComponents_Labi zip file. 9. Unzip the fila to your desktop. 10. Rename the folder to Dev601 Install Chrome Extensions 11. Open the /Dev601/LinksInBook htm! file in your web browser. 12. Click on the hyperlinks in the web page to downioad and install the following Chrome plugins: Clear Cache (hhttps:l/goo.9l/508X2A) Force.Com Logins (https:/igoo.gl/STI4HK) Salesforce Lightning Inspector (https:1/goo.g(GyOPVX) Lightning JavaScript Linter (https://goo.gV/gTJqud) (©2018 salesforce.com, ine. Page 12 ‘Section 1 Introducing the Course Enter your Org Credentials into the Force.com Logins Plugin 13. In Google Chrome, click on the Force.com Logins plugin button. 14. Enter the account information for your org that was provided ky your instructor and choose Production / Dev from the Org Type dropdown. 16. Click the Save button. 16. Click the window button adjacent to your org login. e.. tab [email protected] 17. Follow the on-screen prompts to confirm your identity and successfully login to your org, Configure your User Account 18. Click on Admin User | My Settings (lf prompted to review Critical Updates, choose ignore) 19. In the left column, click on Personal | Advanced User Details | Edit 20. Entar your name in the First Name and Last Name fields. 21. Enter your email address into the Email field, 22. Enter your phone number info the Mobile field 23. Click the Save button. Verify your Custom Domain This Salesforce feature enables you to add a domain name to the URLs you use to log in to and navigate Salesforce.com, 24. Goto Setup | Domain Management | My Domain 28. Ifyou are presented with a screen that reads "Step 1: Choose a Domain Name," complete the following steps. Otherwise continue this exercise at step 29. 26. Enter a unique domain name and press the check for availability bution, 27. Press the Register Domain button. Note that it may take several minutes to complete tho My Domain request. 28. Every couple of minutes or after your receive an emai, press the reload button in your browser until the status chart updates to "Step 3 Domain Ready for Testing’ 28. Click the Log in button. 30. Click the Deploy to Users button, 31. Click OK. Disable the Component Cache 32. Click on Setup | Security Controls | Session Settings 33. Tum off the chackbox labalad "Enable secure and persistent browser caching to improve performance’ 34. Click the Save button, (©2018 salesforce.com, inc. Page 13 Programming Lightning Components Enable Lightning Experience 36. Click the Setup link, located in the top-right comer of the interface. 36. In the lof-column monu, click the Get Started button under tho Lightning Experience Migration Assistant heading. 37. Click on the Turn It On tab. 38. Click the toggle button, 39. Click Finish Enabling Lightning Experience. 40. In the menu atthe top of the page click Your Name | Switch to Lightning Experience. End of Exercise ‘Section 1 (©2018 salesforce.com, ine. Page 14 Introducing the Course Unit Summary + The course is presented through a combination of exposition and hands-on exercises. ‘+ The course assumes that you already understand basic HTML, CSS, and JavaScript concepts. + The course focuses on developing wob applications and adding foatures to Lightring Experience by using Lightning components, ‘Apex, and cther APIs/tools that are compatible across a broad spectrum of browsers and devices ‘Section 1 (©2018 salesforce.com, inc. Page 15 Section 2 Unit 2 Table of Contents Unit Objectives, Unit Topics. 2.4 Using HTMLS and Lightning Components to Develop Apps. Exercise 2-1: Reviewing Available Components 2.2 Getting Started with Lightning Development Exercise 2-2: Creating and Deploying a Lightning Component 2.3 Theming Components with CSS Exercise 2-3: Theming a Lightning Component 2.4 Defining and Manipulating Component Attributes Exercise 2-4: Working with Component Attrioutes 2.5 Handling System and User Events, Exercise 2-5: Handling Events 2.6 Debugging and Troubleshooting Your App Exercise 2-6: Debugging your Code 2.7 Working with Apex Exercise 2-7: Working with Apex 2.8 Using Base Lightning Components Exercise 2-8: Working with Base Lightning Components 2.9 Raising and Handling Events Exercise 2-9: Working with Component and Application Events BSSSAIRSSSSBRNSt aww 109 2.10 Using Lightning Data Service for CRUD Operations (optional unit for DEV-460) Unit Summary Unit Review (©2018 salesforce.com, inc. 115, 125 128 Page 1 ‘Section 2 (©2018 salesforce.com, inc. Page2 Getting Started Unit Objectives After completing this unit, you should be able to: + Recall the features, capabilites, and limitations of HTMLS applications. = Develop for the Salesforce mobile application stack using Lightning Components and Apex © Use best practices to develop a simple Lightning Component. Efficiently test and troubleshoot a Lightning component, Unit Topics HTMLS and Lightning Components to Develop Apps Defining a Lightning Application Defining a Simple Component Handling User Events Using Helpers for Client-Side Event Handling Documenting a Component Using OOTB Lightning Components Working with Apex Debugging and Troubleshooting Apex Section 2 (©2018 salesforce.com, inc. Pages Building Lightning Components and Applications 2.1 Using HTMLS5 and Lightning Components to Develop Apps Developers and corporate IT increasingly turn to HTMLS as a solution to meet the ciitical, time-sensitive demands of their organizations. Developing mobile apps with HTMLS offers several key advantages over native app development Native apps are developed to run ona single device platform, whereas HTMLS apps use the same codebase to run on multiple devices and operating systems © Nalve apps are typically distributed via app stores; however, HTMLS: ‘apps can also be deployed as mobile web sites that run in a user's, mobile web browser. + HTMLS apps use open-source technologies. + Native OS apps can get “lost” emong the hundreds of thousands of ‘apps in app stores. Mobile web apps can be engineered to be: “crawlablo” by search engines. ‘+ Mobile web apps are instantly updatable on a web server. + _ Instoad of having to leam Java or Objective-C, web dovelopers can leverage their existing skil sats to rapidly create mobile apps. ‘+ HITMLS-based apps tend to be less affected by changes in the mobile ‘operating system As a best practice, HTMLS mobile apps are implemented using a single- age architecture, or SPA. As the name implies, an app developed in this fashion is comprised of a single HTML page. Screen updates are handed entirely by JavaScript, which dynamically modifies the browser's document-object model and CSS rules. Data is passed to the serverin the background using the browser's XMLHttpRequest object. Full page reloads are discouraged in order to minimize http latency, improve overall performance, and more easily facilitate offline support. Understanding the Drawbacks of Developing with HTML5 Section 2 Drawbacks to using HTMLS instead of native development include: ‘+ Performance problems related to animation and http latency. + Inability to access some native device APIs. + Edge-case inconsistencies between desktop and mobile browser implementations. = Inability to lock device orientation unless you package the solution as a native app. © X-browser compatibility issues with newer APIs. (©2018 salesforce.com, ine. Pages Getting Started Reviewing the Lightning Component Architecture ‘This course teaches you how to use the Salesforce Lightning Component Framework to procuce reusable components and develop mobile apps. The Salesforce Lightning Component framework is geared towards developing custom dynemic mobile and web apps for Lightning Experience and the Salesforce mobile platform using a single-page applications architecture. It makes an excellent choice for the user interface tier for the following reasons: + The framework is based on wob standards (JavaScript, HTMLS, and CSS3) and MVClevent-driven programming techniques. © Awide variety of out-of-the-box components help speed development ‘and mnimize debugging. Ithas builtin hooks for using Apex on the server side. Calls to the server are made only when absolutely necessary and dat transmitted in JSON format. © The framework has excellent tooling (Lightning App Bullder, Developer Console) and you can use third-party JavaScript IDEs as well, such as Sublime Text and Eclipse. ‘+ Desktop, tablet, and phone form factors can be supported from 2 single codebase in a responsive design that runs on a wide variety of browsers and operating systems. + Lightning Components can bo deployed inside of a standalone Lightning App, into the Selesforce mobile app, on Lightring Record pages, in Lightning Home Pages, and used to override and extend Salesforce mobile tabs and fields, Salesforce Lightning Applications are top-level containers that are defined using markup, where you implement an epp's overall GUI and invoke Lightning Components. Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on the Salesforce Platform server in conjunction with calls to the Salesforce Platform API Using syntax that looks like Java and acts lice database stored procedures, ‘Apex enables developers to add business logic to most system events, including button clicks, retated record updates. and Visuaforce paves. ‘Apex code can be initiated by Web service requests and from triggers on objects. You will create Apex Controllers to marshal data and resources from Salesforce Platform into your Lightning Compenents. ‘Aura is an open-source framework developed by Selesforce.com. The Lightning Component framework was originally built on top of Aura and, as ‘a result, you will See various references to Aura within the Lightning APIs. Section 2 (©2018 salesforce.com, inc. Pages Building Lightning Components and Applications Surfacing Lightning Components You can use Lightning components across the Salesforce ecosystem as illustrated by the following tabee: Lightning | Salesforce | Seestorce | communities ‘Standalone | External Experionce | Mobile | Classic SOK. | ‘Lightning | Sitos Hybrid | “Apps: Apps. Lghining Yes Yes Yos Yes Yes Components Lightning Yes Yes Yes Yes Apps Lightning Yes Yes Component Tabs Lghining Yes Yes Pages: Lghining Yes Yes Yes Yos Yes Components for Visualforee Lghining Yes Yes out If you are new to the Salesforce platform, note the following: ‘+ Lightning Experience is the new GUI for the Salesforce platform that was launched in the Winter "16 release. + Salesforce Mobile is the HTMLS/Hybrid native app available from the Apple App Store and Google Pay. + Salesforce Classic is the GUI for the Salesforce platform that was in Use prior to the launch of Lightning Experience. + Salesforce Communities are branded spaces for your employees, ‘customers, and partners to connect. You can customize and create ‘communities to meet your business needs, then transition seamlessly between them. © Lightning Out is 2 feature that fist debuted with Winter 16 that allows you to directly embed lighining components in web pages that are not par of the Salesforce platform. They run directly in your DOM and ‘automatically take care of cross-domain (using CORS) communication ‘and environment initialization + Visualforce is the predecessor fo Lightning. It enables you to develop custom apps cn Salesforce Platform using whatever JavaScriot framework that you think is appropriate. Your app i usually sandboxed in an iframe. Section 2 ©2018 salesforce.com, inc. Pages Getting Started Using Lightning and Visualforce If you've successfully “surfaced” SPAs in Salesforce mobile by using a ‘combination of Visualforce and a JavaScript framework such as Angular, ‘Sencha Touch, |Query Mobile, Angular js, oF Ionic, you might be wondering why you should change your development practices touse Lightning Consider the following Visualforce requites the use of an iframe HTML component, adding performance overhead, ‘A primary goal of the Lightning framework is to increase custom app performance on Salesforce, Every JavaScript framework provides its own particular architectural approach that developers must follow, and while some do promote a more manageable component-based approach well-suited for scalable enterprise development, others provide litte i any guidance around ‘organizing or scaffoiding code modules, making code maintenance difficult, Components built in one framework are not likely going to be able to be used within a different framework, thereby limiting code sharing between application developers who are working at different companies, or different departments of the same company. Developing with Lightning is now the offcially recommended platform ‘of SFDC. As such, you can expect that thousands of third-party Lightning Components will become avaiable in due time. While Visuatforce will continue to be supported, itis recommended that most new “greenfield” projects be developed using Lightning. You can invoke Lightning Components from Visuaiforce. Lightning Components can be deployed across nearly every area of the Salesforce ecosystern. Developing with Lightning is fun! Note that suppott for Visuaiforce will continve into the far future. Developing custom solutions with Visualforce has been incredibly popular, with Visuaiforce pages receiving bilions and bilions of page views every month. Ifyou are already familiar with Visuatforce, the information presented in this ‘course will help you determine how best to leverage both technologies in ‘order to make the best choices for you and your customers. Section 2 (©2018 salesforce.com, inc. Page? Building Lightning Components and Applications Understanding the Optimal Use Cases for Lightning Components Use Ligntning Components to: + Develop custom single-page applications for Salesforce mobile, © Enable business users to create cusiom apps visually through a drag- ‘an¢-drop interface. ‘+ Develop custom user experiences that are not achievable through using standard Salesforce configuration capebilities. Do not use Lightning Components to: = Duplicate oxisting Salesforce functionality. + Develop a custom UX that is wholly inconsistent with Lightning Experience or Salesforce mobile. ‘= Re-implement an existing Visualforce application without carefully considering lavel-of-effort and RO1 Consider the following scenarios: 1. Client A has designed a custom object that contains information about ‘a customer's automobiles. The custom object contains fields for make, model, color, year, and purchase price. The customer wishes to ‘customize the layout of the data entry form. ‘Should Client A use Lightning Components? 2. Cliont B desires to croate a custom application that will be surfaced in 2 custom tab within Lightning Experience. Cliont B's IT staff is well- versed in React JS, but does not yat have experience with the Lightning Component Framework. The application will principally consist of a grid, a search form, and some dynamically generated HTML. Should Client B develop the application using Lightning Components? 3. Client C wants to implement a custom reporting dashboard that uses a responsive layout and is accessibe from both a custom tab in Lightning Experience as well as Salesforce mobile. The dashboard should include complex visualizations that are not currently available ‘as base lightning components, but can be implemented using the D3.js library (hitps:/3)s.crg)). ‘Should Client C develop the application using Lighining Components? Section 2 (©2018 salesforce.com, inc. Pages Getting Started Reviewing Out-Of-The-Box Lightning Components To browse the documentation for all of the components that nave been installed in your Salesforce instance, see the Components folder at htips//.ightning force.com/componentReference/suite.app, ‘where is the name of your custom Salesforce domain. Figure 1: Component documentation The documentation displays the following information about each unmanaged component that is installed in your Salesforce org: ‘+ An overview of the compcnent and how to instantiate it ‘+ The component source code, including: = Markup: + Tho cliont-side JavaScript contrallor = The CSS fle © Aworking example Note that, as illustrated by Figure 1, managed and "out of the box" ‘components will only display the following tabs: © Usage © Specification © Documentation Section 2 (©2018 salesforce.com, inc. Page Building Lightning Components and Applications Using Namespaces Section 2 Every component is part of a namespace, which is used to group related ‘components together. If your developer org has @ namespace prefix set, use that namespace to access your components. Otherwise, use the default namespace of (c) to access your components, Note that custom namespaces can only be created in a developer-edition ong. Another component or application can reference a component by adding in its markup. For example, ifthe helloWWorld component was in the docsample namespace. another ‘component could reference it as in its markup. In your organization, you can choose to set a namespace prefix. f you do, that namespace is used for al of your Lightning Components. A namespace prefix is required if you plan to offer managed packages on the ‘AppExchange. Lightning Components that Salesforce provides are grouped into the following namespaces: ed aura High-level output tags that define the top level of an app or component, define expressions, iterate through compiox data typos, implomont branching, and rondor texthiml, eg., forceChatter Components for integrating Chatter into your custom applications forceCommunity | Contains an abstract component for customizing tho navigation menu in a community, which loads menu data and handles navigation. UX components that integrate the Salesforce Lightning Design System, Itng The lightning namespace only contains one member, , that is used to load JavaScript and CSS. into a component or application. ui Unstyled ux components, most of which will be deprecated in favor of their counterparts that exist in the lightning namespace. This course will cover using and , as well as the components which handle localization. wave Indudes the wave:waveDashboard component to add a Salesforce Analytics cloud dashboard to 2 SFX page Components from third-party managed packages have namespaces from the providing organizations. (©2018 salesforce.com, inc. Page 10 Getting Started Exercise 2-1: Reviewing Available Components Steps Section 2 During this exercise you will enable Lightning Components for Salestorce mobile and review the OOTE Lightning Components, Figure 2: Accessing the documentation system, Review Available Components 4. Open the following ur: 2. netps: // lightning. force .ccm/componentkeference/ (Whore is the name of the domain that you entered during exorcise 1-1.) Bookmark the page in your browser. Review the list of available components, Click Components | ul: button Review the ui:button usage, specification, and documentation. Click Components | lightning:button and review its usage, specification, and documentation. Note how the lightring:button is ‘themed for Lightring Exporionce while ui:button is not. ean 7. Review the following components that youll be using to create the Awinstructors application: + ligntning:cara + ightningayout * ligntning:formattedEmail © lightning'select + ligntning:formattedRichText —* —_ightningtabset + lightning:tile * _ui'scrollerWrapper_ (©2018 salesforce.com, inc. Page 11 Building Lightning Components and Applications End of Exercise Section 2 (©2018 salesforce.com, inc. Page 12 Getting Started 2.2 Getting Started with Lightning Development By default, the framework uses the Google Closure Compiler to compress ‘and minify your JavaScript. Function names and code are heavily n the Enable Debug Mode checkbox as illustrated in Figure 3 disables this functonality, making it easiar for you to troubleshoot your runtime problems using your browser's developer tools. Figure 3: Enabling Debug Mode. To enable debug mode: 1. From Setup, choose Platform Tools | Custom Code | Lightning Components, Select the Enable Debug Mode checkbox as illustrated in Figure 3. 3. Click Save. ‘Section 2 (©2018 salesforce.com, inc. Page 13 Building Lightning Components and Applications Programming Lightning Components Lightning Components are defined by a ‘component bundle, which has the folowing fies: © ComponenvApplication (emp or .app file) The only required resource in a bundle. Contains markup for the component or app. Each bundle contains only one component or app resource. + Controller (js) Client-side functions to handle events ‘bunate Version Serangs, Taised by the component. Figure 4: Toggiing between resources. © Helper (js fle) JavaScript functions that can be called from any JavaScript code in a ‘component's bundle. * Style (.css file) Styles for the component. Style classes are encapsulated within a namespace so as not to conflict with other CSS definitions that might have been authored for other components that have been instantiated ‘ona page. Documentation (.auradec file) A description, sample code, and one or multiple references to example ‘components, + Renderer (,s file) Glient-side renderer to override the default rendering fora component. + Design (design file) Enables you to design a form that enables business users to set values for component attributes from within the Lightning App Builder Gul = SVG (svg file) Custom icon resource for components used in the Lightning App Builder. All resources in the component bundle are automaticaly wired together. Section 2 (©2018 salesforce.com, inc. Page 14 ‘Section 2 Getting Started ‘You can croato a new component by selecting Filo | New | Lightning Component from the Devolopor Console as illustrated in Figure 6. New Lightning Bundle x Name: i Description: Component Confguration Create bundle with any ofthe folowing configurations (optional) ‘Lightning Tab Etightiing Page lugninng Record Pape Lightning Communities Page [il tigntring Quick Action Submit Figure §: Creating a New Component The Component Configuration options automatically add attributes to your tag that enable your component to be surfaced in different areas of Salesforce.com. Tuming on the “Lightning Page ‘checkbox, for instance, makes your component avalable to Lightning App Builder These options will be discussed in more detail in unit 3 of the DEVS01:Programming Lightning Components course (©2018 salesforce.com, inc. Page 15 Building Lightning Components and Applications Using HTML Markup in Lightning Component CMP files Component resources contain markup and have a .cmp suffix. Components must be wrapped by the tag. The markup can contain toxt or reforonces to other components, and alse declares metadata about the component. Assimple “Hello World” component would therefore resemble the following: An HTML tag is treated as a first-class component by the framework. Each HTML tags translated into a component, allowing it to enjoy tho samo rights and privileges as any other component. Note that you must use strict XHTML. For example, use
instead of . Using OOTB components offors the following benefits: + Components are designed with accessibility in mind, so users with isabilties or tose who use assistive technologies can also use your app. + When you start building more complex components, the reusable out- ‘of-tie-box components can simplify your job by handing some of the plumbing that you would otherwise have to create yourself. + OOTB components are secure and optimized for performance. + components are themed to automatically use the Salesforce Lightning Design System Section 2 (©2018 salesforce.com, inc. Page 16 Getting Started Invoking Lightning Components from a CMP File You can invoke Lightning components from CMP files using xhiml syntax a illustrated by the following snippet:
Here is a chatter feed:
Note that your custom components and any components that you install from an unmanaged package will have ac" namespace, eg. ‘
Im invoking a custom component:
Using Available Tooling Section 2 There are several different authoring environments for creating Lightning applications, including + Developer Console Browser-based editor providing code hinting and code validation for Lightning components as well es debugging, unit testing, and debugging services for Apox. + Force.comIDE 2 Based on the Eclipse platiorn, this powerful, open-source client application enables you to create, modity and deploy Salesforce Platform applications from within 2 single environment. © Schema Builder Browser-based editor enabling you to add custom, relational database ‘objects to your Salesforce schema and view the relationships between them. + Lighting App Builder This browser-based tool enables virtually anyone to combine custom and off-tho-shelf Lightring Components to assemble beautiful apps visually. Third-party development environments that support Lightning include: = Sublime Text 3 For those of you who want to code using a native text editor, there is 2 nifty Lightning extension for Sublime Text 3 that is available. © Clouds ‘A powerful cloud-based IDE that supports Lightning Components and has many enterprise features. + Illuminated Cloud A powerful Salesforce Platform development tool hosted within the JetBrains InteliJ IDEA (Community Edition and Ultimate Edition) IDE. n Salesforce Platform IDE which allows. working with Apex, Visualforce, HTML, CSS, JavaScript, any images 2s well as executing unit tess, SOQL queries, anonymous apex and. provides many other handy features from a single development too! (©2018 salesforce.com, inc. Page 17 Building Lightning Components and Applications Using the Developer Console Section 2 ‘The Developer Console, depicted in Figure 6, is an integrated development environment with a collection of too's you can use to create, debug, and test applications in your Salesforce organization. ‘To be able to use the Developer console, you need the following permissions: cd ‘Open the Developer Console Execute anonymous Apex ‘Author Apex Use Code search and run queries in the query tab| API Enabled ‘Save changes to Apex classes and triggers Author Apex ‘Save changes to Lightring resources Customize Application To open the Developer Console, click Setup | Developer Console. Figure 6: The Developer Console ‘The developer consol is split into the following panels: + Logs Use the Logs tab to view a list of logs and open them in the Log Inspector—a context-sensitive execution viewer that shows the source of an operation, what triggered the operation, and what occurred afterward. Useful for troubleshooting database events, Apex processing, workifow, and validation logic. + Tests Enables you to select and run Apex test classes including unit tests, functional tests, and regression tests. Also displays the code coverage percentage for each class in your organization. You can also view ‘code coverage for a class in the Source Code Editor. (©2018 salesforce.com, inc. Page 18 Getting Started Checkpoints You can use the Developer Console to set and view checkpoints to identify tho source of errors in your Apox cods. = Query Editor Enabies you to edit and execute Salesforce Object Query Language (SQQL) and Salesforce Object Search Language (SOSL) queries. «View State Enables you to examine the view state of a Visualforce nage + Progress Dispiays all asynchronous requests being made by the developer ‘conso’e in real time, + Problems Shows the details of compilation errors in the Source Code Editor for your Apex server-side controllers. Changes you make are compiled ‘and validated in the background. While you're editing code, an error indicator displays beside lines that contain errors. Click a row in the Problems tab to jump to the line of code that caused the error. Opening Lightning Resources Section 2 To open your Lightning application or a resource in its component bundie, select File > Open Lightning Resources or type Ctrl+Shift+A. The Open Lightning Resources cialog box will appear as illustrated in Figure 7. Figure 7: Opening Lightning Resources Click on a resource or folder, and then cick the Open Selected button to open it as a new tab in the Developer Console. Note that you can ctr-click ‘on multiple resources to open several at the same time. The tab order of the opened resources in your editor corresponds to the order in which you selected resources from the Open Lightning Resources dalog box. (©2018 salesforce.com, inc. Page 19 Building Lightning Components and Applications Automatically Formatting your Code From within Developer Console you can automatically indent your code by selecting it and then pressing Shift*Tab or by selecting the option from the Edit monu as illustrated by Figuro 8. we Faeesanbeveape Cama 1 Sere ite eEDintr@inyasestrcesom srnonipmseivaioeesiaae Tes Ga Ohgs ete wm be < Figure 8: Developer Console can Automatically Format your Code Using Lightning App Builder ‘a drag-and-drop GUI that enables less technical ‘+ Create a single-page app for Lightning Experience and Salesforce mobile = Customize the Lightning Experiance Home Page © Customize Lightning Experience Record Pages Lightning Pages occupy a middle ground between page layouts and Visuaiforce pages. Like a page layout. Lightning Pages allow you to add custom items toa page. However. these items, instead of being fields or \Visuatforce components, are Lightning components, which allow much more flexibility. Figure 9: Dragging and dropping a Lightning Component onto the Lightning ‘App Buller design canvas Section 2 Getting Started Using the Schema Builder ‘Schema Builder provides a dynamic environment for viewing and modifying all the objects and relationships in your app. This greatly simplifies the task ‘of designing, implementing, and medifying your data model, or schema, You can view your existing schema and interactively add new custom objects, custom fields, and relationships simply by dragging and dropping. ‘Schema Builder automatically implements the changes and saves the layout of your schema any time you move an object. ‘Schema Builder provides details such as the field values, required fields, ‘and how objects are related by displaying lookup and master-detail relationships. You can view the fields and relationships for both standard ‘and custom objects. Figure 10: Schema Builder ‘Schema Builder is enabled by default and lots you add the following to your ‘schoma: + Custom objects + Lockup relationships + Master-detal relationships + All custom felds except: Geolocation ‘Access the Schema Builder by cicking Setup | Schema Builder. ‘Section 2 (©2018 salesforce.com, inc. Page 21 Building Lightning Components and Applications Using your Desktop Browser to Test a Component in Salesforce mobile Section 2 Application in Salesforce mobile by You can browse to your Lightnit ‘accessing Google Chrome's Developer Tools and turning on mobile ‘emulation as illustrated Figure 11 With mobilo emulation activated, reloading Lightring Experience should automatically trigger the activation of the Salesforce mobile GUI as your browser is redirected to http: // [yourdonain| /one/one app. EL Awunivecsiy Figure 11: Testing Lightning Components Running in a Salesforce App. (©2018 salesforce.com, inc. Page 22 Getting Started Exercise 2-2: Creating and Deploying a Light Component ‘As depicted in Figure 12, during this exercise you wil create a Lightning Component and Lightning Page thet can be run from Salesforce motile. Figure 12: The output from this exercise. Tasks During this exercise you wil: 1. Define a Component that is Surfaced in Lightning App Builder 2. Define the Student Browser Form Component 3. Invoke the Student Browser Form Component 4. Deploy the Student Browser Gomponent as @ Custom Tab in Lightning Experience. Steps Enable Lightning Component Debugging 1. Loginto your Salesforce org, 2. Click Setup | Custom Code | Lightning Components. 3. Check the Enable Debug Mode checkbox. 4. Click the Save button, (Note: you will not receive confirmation thet your change has been put into effect) Define a Component that is Surfaced in Lightning App Builder 8. From Lightning Experience, select Setup | Developer Console ‘Section 2 (©2018 salesforce.com, inc. Page 23 Building Lightning Components and Applications 6. Soloct File | New| Lightning Component 7. Enter the following information: + Name: StudentBrowser + Lightning Page: checkea Click Submit Save the file Define the Student Browser Form Component 10. Select File | New | Lightning Component 11. Enter the following information: + Name: StudentBrowserForm 12. Click Submit 13. Between the tags, insert the folowing markup: Pilter form goes here 14, Save the file. Invoke the Student Browser Form Component 15, Return to StudentBrowser.cmp in Developer Console. 16. Between the tags, invoke the StudentBrowserForm ‘component, omponent implement s="flexipage: avai labler access="global"> “ALLPageTypes” < :StudentBrowserForm /> 17. After the StudentBrowserForm invocation, use lightning:tabset to define a “scoped” tab panel with a single tab named Gallery. omponent implement s="f1exipage: avai lableForAL1PageTypes” access="glopal”> Photo gallery of students goes here 18. Save the file. Section 2 (©2018 salesforce.com, inc. Page 24 Section 2 Getting Started ‘Surface the Application as a Custom Tab in Lightning Experience 19. From Lightning Experience, go to Setup | User Interface | Lightning App Builder. 20. Click the New button, 21, Select App Page and click Next. 22. Enter a Label of Awinstructors and click Next. 23. Select Header and Right Sidebar and click 24, Drag and Drop the StudentBrowser component into the bottom-left box of the design canvas. 28. Drag a Chatter Feed into the bottom-right box of the design canvas. 26. Click the Save button. 21. Click the Activate button. 28. Click on the Lightning Experience tab and click the Add page to app bution, 29. Click on the Mobile tab and click the Add page to app bution. 30. Click the Save button. 31. Return to Lightning Experience and click on the Awinstructors tab. You should see output similar to Figure 12. 32. Test the application i the Salesforce mobile app. End of Exercise (©2018 salesforce.com, inc. Page 25 Building Lightning Components and Applications 2.3 Theming Components with CSS ‘You can theme your components by defining custom CSS classes or by applying pradefined classes ftom the Salesforce Lightning Design System (SLDS). In order to future-proof your application so that it remains consistent with evolving Lighning Experience standards, use SLDS classes whenever possible Introducing the Salesforce Lightning Design System (SLDS) ‘Announced at Dreamforce 2015, and available at ‘wivw.lightningdesignsystem.com, the Saiestorce Lightning Design System isa set of design guidelines, a CSS framework, and html markup prototypes of Lightning Components for building great experiences on the Salesforce platform. LIGHTNING DESIGN SYSTEM at Figure 13: www lightningdesignsystem.com. The design guidelines represent an ontiroly new design language for Salesforce.com apps and include concrete best practices with reusable visual and interaction design patterns to produce excellent and consistent User experiences. SLDS also includes a UI Library that cocuments OOTB components and ‘component examples rendered from real markup and CSS, as well as accessible and semantic markup. SLDS was developed using the Sass (Syntactically Awesome Stylesheets) preprocessor. Section 2 (©2018 salesforce.com, ine. Page 26 Loading SLDS Getting Started SLDS is automatically included in your org. SLDS is automatically available to Lightning components that are running in the following contexts: + Salesforce mobile + Lightning Experience + Lightning Communitios To lead the SLDS styleshest from a Lightning application, add the ‘extends="iorce:sids" to your tag as illustrated by the folowing snippet: You will also need to extend force:sids in Lightning Out and Lightning Components for Visuaiforce Pages. You'll review these techniques in more detail in DEV601:Programming Lightning Components. Reviewing the SLDS Prototype Components Section 2 SLDS contains CSS style classes that enable you to visualize HTML markup as a series of components. Note that Winter 18 includes @ number of these prototypes as fully realized lightning components (indicated in bold). = Accordion + Docked Composer + List Builder © Activity Timeline Docked Form © Lookups = Alert Footer + Media Objects + Docked Utiity Bar ‘+ Dueling Pickiist + App Launcher + Avatar + Menus: + Modals © Badges + Bynamicleons Navigation ‘+ Expandable ificati + Breadcrumbs Seton + Notifications + Buttons «Feeds + Page Headers + Button Groups. File Selector + Path + Button Icons © Files + Panels + Buttons = FormElements * Picklist + Cards + Pills + Form Layout + Global Header ‘© Global Navigation * Popovers + Checkbox Button * Checkbox Group + Process = Combobox + Gria System © Publishers + Data Tables = Icons + Rich Text Editor + Datepickers + images + Spinners (©2018 salesforce.com, inc. Page 27 Building Lightning Components and Applications * Tabs + Tooltips © Walkthrough + Tiles + Trees + Vertical Navigation Note that SLDS is used strictly for visualization. You will need to code additional JavaScript to handle user interactivity to fully implement the SLDS prototype components that have not already been added to the namespace. Applying SLDS Classes ‘The Lightning Design System CSS uses a standard class naming convention called “BEM (Block-Element Modifier): * Block represents a high-level component (e.g. sids-button) ‘+ Element represents a descendent of a component (eg. sids-button_icon) + Modifier represents a cifferent state of a block or element (e.g. sids-button_noutral) ‘SLDS not only includes a number of classes to replicate the look and feel of native Lightning Experience components, but also to handle typography, Positioning, user interactions, and more. Note that SLDS diverges from BEM in some cases for reasons of brevity ‘and comprehension. For example, to absolutely center text within a container, simply add the sids-align_absolute-center class to a block tag as illustrated by the following snippet
Centered Content
‘You will earn more about SLDS classes as you progress throughout this Section 2 (©2018 salesforce.com, inc. Page 28 Using SLDS Icons Section 2 Getting Started SLDS ships with over 200 icons that you can use within your application. As illustrated by Figure 14, these icons are grouped into the foliowing categories: © Action © Standard = Custom = Utility, © Doctype Figure 14: SLDS leans To use an icon in a base lightning component you must refer to it as ccategoryname:iconname. For example, to depioy the add_contact action icon within a lightning:card component, the syntax would be similar to the following: // content gocs here
(©2018 salesforce.com, inc. Page 29 Building Lightning Components and Applications Styling a Component with Custom CSS Add CSS toa component bundle by |g clicking the STYLE button in the = ‘a Developer Console sidebar. © > Bi isevasnaghnngsrcec Al top-level elements in a component have a special THIS CSS class added to them in order to add a namespace to your CSS. Using the namespace helps prevent a component's CSS from confiicting with other components’ styling. The framework throws an error if the CSS file does not follow this, ‘convention, Figure 15: Styling a Component. ‘The following snippet illustrates setting different background color ‘styles on component markup. foo.cmp:
foo.css: THIS background { width: 200px; height: 200px; border: Ipx solid red; background-color: #344AS5; THIS -background2 { width: 100px7 height: 100px; margin: aut background-color: #FOPIF’ Note: The CSS selector for direct descendants of a component is THIS.classname. Section 2 (©2018 salesforce.com, inc. Page 20 Getting Started Handling CSS 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 ass, thereby ‘enabling you to specity override values for specific prefixes. For example, spectying the following style: class { border-radius: 2px; Gonerates the following output: cla “webkit-border-radius: 2px: -moz-border-radius: 20x; border-radius: 2px; Coding for Background Changes in Lightning Experience Winter 18 Section 2 In Winter ‘18, Lightning Experience was tweaked to include a background color and image. This means thet you wil need to check custom Lightning ‘components and components you've downloaded from the AppExchange to ensure that their content remain readable. Components which are being used on a Lightning page now need to have a Sold background in order to remain legible on the new background. To adjust your custom components, simply tweak your component's CSS a illustrated by the following snippet: : { background-color: #fff; ) Alternately, you can wrap your camponent with to provide more legible output
// content goes here By using Base Lightning Components, you automaticaly inherit any future ‘changes to SLDS, such as the fact thet cards in Winter 18 have a white background instead of a gray background, (©2018 salesforce.com, inc. Page 31 Building Lightning Components and Applications Section 2 Since some orgs might havo a significant number of components that nood to bo updated, you can dolay the rollout of the nw look until all of your updates have been completed. As an Admin, you can disable this background image and color in Setup as illustrated in Figure 16, reverting the background color of pages to the same white color usad in Summer 47, Figure 16: Removing the background image from Lightning Experionco (©2018 salesforce.com, inc. Page 22 Getting Started Exercise 2-3: Ther ‘As depicted in Figure 17, during this exercise you will theme the ‘components that you developed in the previous exercise. g a Lightning Component Sweupaates foriier Figure 17: The output from this exercise. Tasks During this exercise you will: 1. Review the Capabilities of lightning:card Use lightning:card to add contrast to the search form. Use SLDS to Add Margin toa Component Use SLDS to apply padding within a Component Apply custom CSS seer Review the Capabilities of lightning:card 4. Open the following URL: https: // .] ightning. force .com/componentReference/ suite.app 2. Click on lightning:card and review the Basic Card example. 3. Click on the Specification and review the title and iconName attribute definitions. 4. Retum to Developer Console and StudentBrowserForm.cmp ‘Section 2 (©2018 salesforce.com, inc. Page 33 Building Lightning Components and Applications Use lightning:card to add contrast to the Search Form 5. Wrap the

block in a lightning:card component with the following attributes: + title: Filter Students + iconNvame: utity:search 6. Save the file and refresh the application in Lightning Experience. Verify that the heading text is now on a white backaround. Use SLDS to Add Margin to a Component 7. Open https:/llightningdesignsystem.com! in your browser. 8. Select Utilities | Margin 9. Review the examples for Bottom margin 410. Open StudentBrowser.cmp in Developer Console. 11. Wrap the tag in a
block with the following attribute + class: sids-mbottom smal 12. Save the file and reload the Awinstructors tab. There should now be visible margin between the Filters Students form and the Gallery tab. Use SLDS to Apply Padding within a Component 13. Open https:/ightningdesignsystem.comy in your browser. 14, Select Utilities | Padding 15. Review the examples for Hoxizontal padding 16. Return to Developer Console and StudentBrowserForm.cmp 17. Wrap the

block with a
tag that uses the following attribute: + class: side p-horizontal_small 18. Save the file and test the application. The heading text should no longer be placed against the left edge of the component. Apply Custom CSS 19. Return to Developer Console and StudentBrowserForm.cmp 20. Add the following attribute to the

tag 21. Click on the STYLE button, or pross Cirl+Shitt+4 22. Define the “crazycomic" class to apply the font Comic Sans and add a text shadow. Your code should appear similar to the following’ THIS .crazycomic { font-family: Comic Sans M3; text-shadow: 2px 2px Fe0ed<0; Section 2 (©2018 salesforce.com, inc. Page 34 Getting Started 23. Save the filo and test the application. You should see results similar to what ie dopicted in Figure 17 End of Exercise Section 2 (©2018 salesforce.com, inc. Page 35 Building Lightning Components and Applications 2.4 Defining and Manipulating Component Attributes Component attributes enable you te make compenents more dynamic and flexible. They are typed fields that are set on a specticinstance of a ‘component, and can be referenced from within the component's markup using an expression syntax as illustrated by the following snippet:
Hello, (!v.firstName +" ' + v.lastNane!
Note the following: + Attribute names must start with a letter or underscore. They can also contain numbers after the first character. + Attribute names must be two or more characters. + You cannot use ettributes with hyphens in expressions. ‘+ Though nota strict requirement, tags are usually the first things listed in a componert's markup, as it provides an easy way to read tho component's shape at a glance. Configuring Scope Section 2 Use the access attribute of to control its scope. The following access values are supported: co eel global _The attribute can be used in any namespace. Public (default) The attribute can be used within the same namespace only. private The attribute can be used only within the container app, interface, component, or event, and can't be referenced extemally Typically, you will implement private attributes to store variables that are set exclusively by a component's event handlers in ts controller or helper. Note that components, apps. events, and interfaces all have scope. (©2018 salesforce.com, inc. Page 36 Getting Started Configuring an Attribute's Data Type The following data types are supported. = Boolean = Double = Date + Integer © DateTime = Long © Decimal String = Object + List = Map + set Use brackst notation to specify a typed array, 0.g The List type is an ordered collection of tems: A Set is a collection thal contains no duplicate elements. The order for set items is not guaranteed. For example, "1,2,3" might be returned as "3,2,1." caurarattribute name="col lection" type="set default="1,2,3" /> You can also define Salesforce standard and custom cbjects as data types, ‘as well as custom apex classes, covered later in this course. Data Types can also be sObjects. For instance, you can dectare an attribute to be of type Contact or a custom Object. ‘Section 2 (©2018 salesforce.com, inc. Page 37 Building Lightning Components and Applications Passing Attributes to a Component Declaratively You can pass attributes to a component declaratively using the same syntax that's found in HTML as illustrated by the folowing example: add2Nums.cmp: omponent> rattribute name="numl" type="Decimal" dcfault="0"/> tribute name="num2" type="Decimal" cefault="0" /> { !v.numl + v.num2) AddTest.app: 141 = Using Expressions Section 2 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 thom to attributes. ‘An expression is any set of literal values, veriables, sub-expressions, or ‘operators that can be resolved to a single value. Function calls are not allowed in exoressions. ‘The expression syntax is either (#expression) or (!expression) where expression is a placeholder for an expression. Anything inside the {1} delimiters is evaluated and dynamically replaced when the component is rendered or when the value is modified by the ‘component. Whitespace is ignored. This is referred to as a bound ‘expression, Anything inside the (#} delimiters is evaluated and dynamically replaced ‘when the component is rendered, however its output is net refrashed when the value is modified by the component. This is referred to as an unbound expression 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 spocific evaluation order. 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 function such as an action function, and other useful resutts. If you're including Iteral values in expressions. enclose text values within single quotes, such as {#'Some text '} Include numbers without quotes, for example, (#123). (©2018 salesforce.com, inc. Page 38 Getting Started To output the value of a component attribute, use the following syntax: {#v.attributeNane) or (1v-attributeName} Note: The v prefix represents a value provider for the component view. Using Numeric Literals You can use numeric literals inside of an expression, as ilustrated by the folowing snippet: saura:component >
? + {1 v.numl j= {! 2 + v.numl }
ediv>2000 = {1 203 }

Running this code results in the following output: 202-4 2000 ~ 2000 24 mull = 2 Using Arithmetic Operators Expressions based on arithmetic operators result in numerical values. The standard operators of +.-,*/,%, and are all supported, as illustrated by the following component: aura: component soura:attribute name-"numl" yame="nam2" type: default
(!v.nunl — v.num2)
{!v.nunl * v.num?}
{!v.numl} / {!v.num2) {!v.nunl / v.num2}
‘Section 2 (©2018 salesforce.com, inc. Page 39 Building Lightning Components and Applications
(!v-numl} & (/v.num2) = {!v.numl % v.num2}
Negative {!v.aunl} = { !-v.numl }
Passing in attribute values of num1=2 and num2=4 into the component generates the following output: +4 -4 a4 v4 a4 gat. ENN iegative 2 Using Math Functions Section 2 ‘The following math functions are supported. Note that all function names are case-sensitive: ees oneareomd add concat add(1.2) + sub subtract sub(10.2) - mult multiply mult(10,2) . div divide div(4,2) \ mod modulus moa(s,2) % abs abs(-1) neg negate neg(100) ~(unary) For example:
2 + 2 = {# add(2,2) }
2 - 2 = {4 sub(2,2) }
abs (-5) = {# abs(-) }
Outputs: (©2018 salesforce.com, inc. Page 40 Getting Started Using String Literals Literal strings must be enclosed in single quotation marks. Double ‘quotation marks are reserved for enclosing attribute values, and must be ‘escaped in strings. Use the “character to escape strings, including: ant Newline ae Tab we Carriage return aa Double quote v Single Quote a Backstash_ You can encode unicode characters as ‘wif###" where # represents a hexadecimal digit. All unicode characters require 4 digi. For example:
Copyricht {# "\u00A9"} 2015. Salesforce.com. Al] Rights Reserved.
Outputs: copyright © 2015. Salesforce.com. All Rights Reserved Implementing String Concatenation Use the + operator on string values to join them together. For oxamplo, the following component outputs an HTML mailto: link: (! velabel J ‘Section 2 (©2018 salesforce.com, inc. Page 41 Building Lightning Components and Applications You can also use the concat() function instead of the + operator: Generating Conditional Markup with the Ternary Operator ‘You can use the ternary operator to conditionally output one of two values dependent on a condition, as illustrated by the folowing snippet: Generating Conditional Markup with You can also use the command to generate conditional markup, which renders content within the tag ifthe expression contained in its isTrve attribute evaluates to true. The framework evaluates the isTrue expression and instantiates ‘components either in its tag body or else attribute. For example: ttribute name="edit" type="Boolean* default="truc"/> £ isTrue="{!v.edit}"> utton label="Bdit"/> You can’t edit this. Section 2 (©2018 salesforce.com, inc. Page 42 Getting Started Using Conditional Operators Lightning uses the same comparison operators as JavaScript, but also ‘supports @ two-cheracter altemative for each as well as a function. ree err) equals (vari, var2) eq pe notequaie(varl,var2) < lessthan (wart, var?) > gt sreaterthan (wari, vard) < jp leosthanorequal (varl, var2) oe ge sreaterthanorequal (vari, var2) For example, the following code snippet validates an argument's value to ‘ensure that an invalid math operation is not performed: (1 v-num2 You can't divide by zero! {1 v-numl / v.num2}

oy Using Logical Operators “The Lightning framework uses the same logical operators as JavaScript: a 2 {1 v.ieEnabled ££ v.hasPermission } ‘AND || {1 visrnabled || v-hasPermission } OR 1 (1 tweisBnabled false } NoT ‘Section 2 (©2018 salesforce.com, inc. Page 43 Building Lightning Components and Applications ‘You must oscape the && operator to camp; samp; to uso it in component markup. Alternatively, you can use the and ) function and pass it two arguments. For oxamplo, and(icEnabled, hasPermiseion). For example: = 0 gamp;éamp; v-num2 >= 0)"> caurazif isTeuo="{! v.num2 == 0 }"> You can't divide by zero! set attribute="clse"> uml / v.num2} Error - both numbers must be positive. Determining if a Variable is Empty Use the length@ function to determine the length of an array or sting, Use the empty() function to retum true if one of the following condition: met: is empty + Astring is empty Note:{! lempty(v.myArray) } evaluates faster than {Wv.myArray && v.myArray.length > 0}. Looping through Arrays and Objects Use the auraiiteration component to loop through an atray as ilustrated by the following snippet: omponent > aurarattribute nane="nyNanes type="String[] default="[ "Steve", Dave", "Joe", "Jyoti'}" />
    <1i>{ !thisName}
Section 2 (©2018 salesforce.com, inc. Page 44 Getting Started Commenting your Component Markup ‘Section 2 ‘The Lightning Component framework uses the same comment tags as HTML - ‘omponent extends="c:wrapInBox"> This is sone child content that will appear as v.body in the parent tag. Defining Abstract Components Object-oriented languages, such as Java, support the concept of an abstract ciass that provides a partial implementation for an object but leaves the remaining implementation to concrete sub-dasses. An abstract cass 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 2 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 implomentation. An abstract component carit be used directly in markup. To define an abstract component, add the abstract=true attribute to the tag as llustrated by the following snippet. saura:component abstract="truc eltag:requize stylos="{ !$Resource -MyCustomeSs }"/> {!v.body? Section 2 (©2018 salesforce.com, inc. Page 82 Getting Started Working with Inherited Attributes, Events, Helpers, and Controllers When a component contains another component, we refer in the ‘documentation to parent and chidd components in the containment hierarchy. Whon a component extonds another component, wo rofer to sub ‘and super compononis in the inheritance hierarchy. Note the following = Assub component that extends a super camponent inherits the attributes of the super component. Use in the markup of a sub component fo set the value of an attribute inherited from a super ‘component, © Assub component that extends a super component can handle events fired by the super component. The sub component automatically inherits the event handers from the super component. + The super and sub component can handle the same event in different ways by adding an tag fo the sub component. The framework doesnt guarantee the order of event handing = Assub component's helper inhorits the functions from the helper of its super component. A sub component can averride a super component's helper function by defining a function with the same name as an inherited function © Assub 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 irectly call the action using the {lc.doSomething} syntax. Section 2 (©2018 salesforce.com, inc. Page 83 Building Lightning Components and Applications Exercise 2-7: Working with Apex Tasks Steps Section 2 During this exercise, you will call an Apex method from a Lightning Component and rendar the result as a series of ties. In this lab, you will perform the following tasks: ‘+ Invoke functions directly from the browser console. During this exercise you will: 1. Create an Apex Class and method that can be accessed by a Lightning Component. Define an Abstract Component to facilitate code sharing. 3. Define a Helper method to invoke Apex methods in a consistent manner. Request data trom Salesforce Platform. 5. Output a set of Contacts as tiles Create the Apex Class. 1. Open Developer Console 2. Select File | New| Apex Class 3. Enter an Apex class name of StudentBrowser and press OK. (©2018 salesforce.com, ine. Page 84 Section 2 Getting Started 4. Add “with sharing’ to the class definition. public with sharing class Stusdentlrow 5. Define a Lightning Component accessible function named getStudents thal retums a list of contacts and accepis two string arguments — instructorid and courseDeliveryid. @auraEnabled public static List getstudents( String instructorld, String courseDeliveryld) { ) 6. Copy the contents of /snippets/exercise2-7.apxc into the getStudents() function. 7. Save the file. Define an Abstract Component to Facilitate Code Sharing 8. From Developer Console, select File | New | Lightning Component 9. Enter a component name of Base and press Submit. 10. Modify the component to be defined as an abstract component. (!v.bedy} 11. Click on Helper. 12. Copy and paste the contents of /snippels/exercise2-7helper js.ixt and paste it into the helper, overwriting the "helperMethod"™ 13. Save the file Roquost Data from Salesforce Platform 14. Open StudentBrowser.cmp in Developer Console 15, Ad¢ attributes to the tag that link the component to the StudentBrowser Apex class and the c-Base Lightning Component. 16. Save the file. 17. Click on Helper. 18. Define a new function named queryStudents that accepts the following arguments: = component + helper + instructorid courseDeliveryld (©2018 salesforce.com, inc. Page 85 Building Lightning Components and Applications Section 2 19. Inside the quoryStuderts function, invoke helper.callServer to call tho gotStudents() Apex method that you defined carlior in this exorcise and store the results in the component's studentList attribute, helper .callserver( component, "e.getstudents”, function (response) { component .set ("v.studentList', response) ; hed instructorld : instructorId, coursebeliveryid: courseDeliveryid r de 20. Delete the contents of the onlnit() function, 21. Inside the onlnit() function, call the queryStudents function, passing along referencas to the component, helper, and two empty strings. onInit : function (component, event, helper) { helper. queryStudents (component, helper ,"","") ; 22. Save the file. 23. Refresh the Awinstructors tab. You should now see multiple names that were read from Salesforce Platform. End of Exercise (©2018 salesforce.com, ine. Page 86 Getting Started 2.8 Using Base Lightning Components OTB Lightring Input components that ere themed with SLDS include: ~ < ——_ Using displays an him