<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mehdi Maujood on Medium]]></title>
        <description><![CDATA[Stories by Mehdi Maujood on Medium]]></description>
        <link>https://medium.com/@maujood?source=rss-c5ced674e8c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9sdLRYkb6wapPrgC_tyiuQ.jpeg</url>
            <title>Stories by Mehdi Maujood on Medium</title>
            <link>https://medium.com/@maujood?source=rss-c5ced674e8c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:43:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maujood/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Build-your-own Teams Feature for Custom Objects in Salesforce]]></title>
            <link>https://medium.com/salesforce-zolo/build-your-own-teams-feature-for-custom-objects-in-salesforce-963ed3630f4?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/963ed3630f4</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Wed, 22 Sep 2021 01:56:57 GMT</pubDate>
            <atom:updated>2021-09-22T03:41:01.520Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LZgBxwWKjgZpQ_ij6ctX3w.png" /></figure><p>Teams for Custom Objects, similar to Accounts Teams and Case Teams, is an <a href="https://trailblazer.salesforce.com/ideaView?id=08730000000BrPKAA0">often-requested but yet-unavailable</a> feature. Manual sharing can meet the needs to <em>some</em> extent, but there are two major limitations:</p><ul><li>Manual sharing can be managed only by record owners, their higher-ups in the role hierarchy, and users with “modify all” permissions to the object</li><li>Manual sharing records are deleted when a record owner changes</li></ul><p>While there are solutions on AppExchange available, it’s actually pretty simple to spin up your own Teams feature for custom objects. I built this as an example for my Pluralsight course on <a href="https://app.pluralsight.com/library/courses/sharing-visibility-features-salesforce/table-of-contents">advanced sharing and visibility features</a>, but ended up not using this example in the course so sharing it here:</p><h3>Build-your-own Teams Feature</h3><p>This example is based around a custom object named <em>Class</em>, and you can build something similar for any object you wish to add a teams feature to. We will build a <em>Class Teams</em> feature that allows users to add and remove <em>Class Team Members </em>from classes. Team members are then given access to class records through <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_bulk_sharing_creating_with_apex.htm">Apex Managed Sharing</a>.</p><p>The solution is available on github (<a href="https://github.com/maujood/class-teams">teams for custom objects example</a>) and has the following big pieces:</p><ul><li>Custom Object <strong>Class Team Member</strong> that has a lookup or master-detail to Class, a lookup to User, and picklist for choosing <em>Edit or Read </em>as access levels. Users can add team members to classes using this object.</li><li>An <strong>Apex Trigger </strong>on the Class Team Member object. Any time team members are added, removed, or updated, the trigger adds or removes sharing for the parent Class record through <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_bulk_sharing_creating_with_apex.htm">Apex Managed Sharing</a>.</li><li>A sharing recalculation <strong>batch apex </strong>class that can be run to recalculate sharing records for all classes. Why do we need this? Several reasons: the system recalculates sharing and runs recalculation classes when OWD changes, we may need to recalculate sharing data in case our logic had bugs, and in some cases we may need to add sharing to pre-existing data although we do not have any such need in this example implementation as classes won’t have pre-existing team members.</li></ul><h4>Step 1: Create Apex Sharing Reason</h4><p>Before we can share Class records through Apex, we need to create an Apex sharing reason on the Class object. Apex sharing reasons are currently available only in Classic.</p><p>In Salesforce Classic Setup, navigate the object settings for the Class object, and scroll down to the Apex Sharing Reasons related list. On this list, you can click <em>New</em> to create a new Apex sharing reason. I created the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D7YC-s9McLJIGYOFcfeMrQ.png" /><figcaption>Apex sharing reason on the Class object with API Name “Class_Team” and label “Class Team”</figcaption></figure><h4>Step 2: Create Class Team Member object</h4><p>In the Object Manager, create a Class Team Member object (pick Auto Number for Name) and add the following fields:</p><ul><li><strong>Team Member</strong>: Lookup to User.</li><li><strong>Class</strong>: Lookup or Master-detail to parent. Whether you choose Lookup or Master-detail depends on your requirements. In my case, I chose to inherit record-level security from the parent Class record by using a Master-detail relationship.</li><li><strong>Access Level: </strong>Picklist with picklist values <em>Read</em> and <em>Edit.</em></li></ul><p>This is what the fields on my Class Team Member object look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*bf4M8RUPslByDm7_S4rxBw.png" /><figcaption>Fields defined on the object Class Team Member</figcaption></figure><p>You would want to add the Team Members related list to your object’s page layout and configure permissions and sharing for the Team Member object as needed.</p><h4>Step 3: Automation on Class Team Member object</h4><p>Next, we create an Apex Trigger on the Class Team Member object to manage sharing records in the Class__share object. If you’re unfamiliar with sharing objects, I recommend <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_bulk_sharing_understanding.htm">reading more about sharing</a>. The trigger has the following logic:</p><ul><li><strong>If a Class Team Member is inserted</strong>, insert a new record into the Class__share object to give the selected user read or edit access to the parent class. This logic has to take care of one important fact: inserting a new record with the same ParentId, UserOrGroupId, and RowCause <em>results in an overwrite of any existing record with the same ParentId, UserOrGroupId, and RowCause. </em>This kind of behavior is unique to sharing objects. If we’re not careful, a team member who already has Edit access to Classes can have that access changed to Read just because someone added the same person twice as a team member with Read access. We should ensure the highest access is given to a team member.</li><li><strong>If a Class Team Member is deleted</strong>, remove access from the sharing object <em>unless the user should retain access through another Class Team Member record. </em>If the user should retain a lower access level, reduce the access level in the sharing object.</li><li><strong>If a Class Team Member is updated</strong>, perform the delete logic followed by insert logic outlined above.</li></ul><p>The logic above could be simplified if we prevent duplicate Team Member/Parent Class combinations in the Class Team Member object, but the logic above is more flexible because it allows for both possibilities.</p><p>The trigger and classes are <a href="https://github.com/maujood/class-teams/blob/master/force-app/main/default/triggers/Class_Team_Member.trigger">Class_Team_Member.trigger</a> and <a href="https://github.com/maujood/class-teams/blob/master/force-app/main/default/classes/ClassTeamMemberTriggerHandler.cls">ClassTeamMemberTriggerHandler.cls</a>. You will also find an associated test class in the github project.</p><ul><li><a href="https://github.com/maujood/class-teams/blob/master/force-app/main/default/triggers/Class_Team_Member.trigger">class-teams/Class_Team_Member.trigger at master · maujood/class-teams</a></li><li><a href="https://github.com/maujood/class-teams/blob/master/force-app/main/default/classes/ClassTeamMemberTriggerHandler.cls">class-teams/ClassTeamMemberTriggerHandler.cls at master · maujood/class-teams</a></li></ul><h4>Step 4: Apex Sharing Recalculation</h4><p>Like we discussed earlier, in certain circumstances apex sharing needs to be recalculated.</p><p>An example is when an object’s OWD is changed. If OWD is changed to Public Read/Write or Public Read, Salesforce deletes all unnecessary sharing records. If OWD is then switched back to Private, Salesforce would need to recalculate sharing for <em>all </em>records on the object, which can be done using batch apex.</p><p>Another example is if we discover that the logic we deployed was incorrect, and we need to delete all sharing records and insert new sharing records.</p><p>The batch apex class <a href="https://github.com/maujood/class-teams/blob/master/force-app/main/default/classes/ClassTeamMemberSharingRecalculation.cls">ClassTeamMemberSharingRecalculation.cls</a> does exactly this: it goes over <em>all </em>Class records in batches, queries team members, deletes any existing sharing records associated with the classes, and inserts new sharing records.</p><p><a href="https://github.com/maujood/class-teams/blob/master/force-app/main/default/classes/ClassTeamMemberSharingRecalculation.cls">class-teams/ClassTeamMemberSharingRecalculation.cls at master · maujood/class-teams</a></p><p>An extra step for sharing recalculation classes is that they need to be selected in the object’s settings so Salesforce can automatically execute them when necessary. In the case of this example, the recalculation class needs to be selected for the Class Team Member object. Once again, this is available only in Salesforce Classic on the object page, right below Apex Sharing Reasons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bSb9NWW3CWuzzGHt1Uy0hA.png" /><figcaption>A batch apex class set as a Sharing Recalculation class for the Class object</figcaption></figure><p>This example does not include an implementation for default teams, but adding default teams into this solution should not be very hard.</p><p>If you find this solution difficult to follow, you can clone the <a href="https://github.com/maujood/class-teams">github project</a> and follow the instructions in the README file to deploy it to scratch org and run it. I would also recommend learning more about sharing through the links to documentation or through my course.</p><p>If you have any thoughts, comments, or questions, feel free to comment!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=963ed3630f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/build-your-own-teams-feature-for-custom-objects-in-salesforce-963ed3630f4">Build-your-own Teams Feature for Custom Objects in Salesforce</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Engineers: Pay Attention to Salesforce]]></title>
            <link>https://medium.com/salesforce-zolo/software-engineers-pay-attention-to-salesforce-c4e9d645b3f2?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4e9d645b3f2</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 02:37:50 GMT</pubDate>
            <atom:updated>2021-03-11T19:27:46.637Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPswPSIh42T61ChIKrixog.png" /></figure><p>If you ever want to gauge how passionate the Salesforce community is, take a look at Dreamforce. You will find thousands of excited nerds sporting hoodies, bags, and other Salesforce goodies getting all fired up about new features. The enthusiasm is infectious; I myself who once harbored an irrational animosity towards laptop stickers now sport a Salesforce cloud on both my laptop and phone.</p><p>I started my career with .NET and JavaScript. When given the opportunity to work with Salesforce, a platform that described itself as “low-code”, I was hesitant. I <em>love</em> writing code. Low-code is a word that’s more suited to trigger a fight-or-flight response in people like me, not win over.</p><p>As I embarked on a journey of self-discovery, however, I learned that my love for a bigger paycheck was stronger than my fear of low-code.</p><p>As I started discovering the power of the platform and the opportunities for technical depth it provides, my concerns started disappearing quickly. Well past the fear, I’m now someone who would enthusiastically go knocking cubicle to cubicle asking people if they have a moment to talk about Salesforce.</p><p>There are many like me. But also many that are not. Salesforce often struggles to win over software developers — especially developers not deeply involved with the platform. While some developer dissatisfaction is driven by the platform’s limitations and quirks, I believe a lot of it exists simply because the platform is, as we will discuss below, misunderstood.</p><p>Regardless of where low-code and Salesforce fall on your avoid-o-meter, there is good reason to be paying attention to what’s going on. Contrary to the marketing hype claiming that low-code means no more developers, the low-code world is in <em>desperate</em> need of software developers. The prospects for talented developers today couldn’t be better.</p><h3>So what’s going on?</h3><p>Salesforce has not stopped growing and it doesn’t look like it will stop any time soon. Research firms like Gartner and Forrester project high growth for the low-code industry, with Gartner predicting that <a href="https://www.mendix.com/resources/gartner-magic-quadrant-for-low-code-application-platforms/#">75% of companies will be using at least 4 low-code platforms by 2024</a> and <a href="https://www.salesforce.com/news/stories/forrester-names-salesforce-a-leader-among-low-code-app-development-platforms/">naming Salesforce as a leader</a>, and <a href="https://go.forrester.com/blogs/predictions-2021-software-developers-face-mounting-pressure/">Forrester placing accelerated low-code adoption at the top of its 2021 predictions</a>. <a href="https://www.marketsandmarkets.com/Market-Reports/low-code-development-platforms-market-103455110.html">Markets And Markets projects the low-code industry to grow from USD 13.2 billion in 2020 to USD 45.5 billion in 2025</a>. According to IDC, the Salesforce ecosystem is expected to <a href="https://www.salesforce.com/news/press-releases/2019/10/25/new-research-finds-the-salesforce-economy-will-create-more-than-1-trillion-in-new-business-revenues-and-4-2-million-jobs-between-2019-and-2024/">create 4.2 million jobs between 2019 and 2024</a>.</p><p>Numbers like that warrant attention.</p><h3>Developer satisfaction and technology success</h3><p>The struggle Salesforce has with winning over developers reminds me a lot about JavaScript a decade or two ago. With React, TypeScript, Node.js, and a lot of other fancy tech, JavaScript is finally cool. “This is cool”, however, was hardly the sentiment among developers around me at the time. Most expected and wanted it replaced with a “real” language and for that reason avoided it.</p><p>Yet, JavaScript continued to grow. Developer dissatisfaction did not stop it from taking over the world. Why? <em>Because JavaScript delivered value</em>.</p><p>While many worked on the cross-platform development dream, JavaScript ultimately delivered it because it could run on anything with a web browser. And a web browser was everywhere. The nights I spent sobbing in a pillow trying to figure out <a href="https://alistapart.com/article/prototypal-object-oriented-programming-using-javascript/">object-oriented JavaScript</a> did nothing to change that fact.</p><p>Working with Salesforce today, I can draw many parallels. It delivers a lot of value in the form of accelerated delivery and empowering “citizen” developers, but at the same time struggles to win over a lot of software developers.</p><p>Developers have reasons to be dissatisfied. One reason is technological limitations. Salesforce did not work well with source control for a long time, deployments have been ridiculously complicated, and logging and debugging still has a long way to go. Developers <em>love </em>these things. Any platform that does not provide them is going to be frustrating to work with.</p><p>The good news is that Salesforce has been very aggressively addressing them as part of a push towards developer experience. Another good news is that developers who are around for the show and contributing to the solutions, just like the developers who were around for the show with JavaScript, will greatly benefit.</p><p>The second reason for dissatisfaction, and in my opinion the bigger reason, is that the platform is just misunderstood. My Pluralsight course <a href="https://app.pluralsight.com/library/courses/salesforce-platform-fundamentals-developers/table-of-contents">Salesforce Platform Fundamentals for Developers</a> discusses these at length: Salesforce requires a very different approach to software development, and not approaching it correctly leads to problems and frustration.</p><h3>The World’s Most Misunderstood Platform</h3><p>Douglas Crockford called JavaScript “The World’s Most Misunderstood Programming Language”. The same appears to be true for Salesforce and for low-code platforms in general. Both among developers and everyone else, they appear to be the world’s most misunderstood platforms.</p><p>Let’s address a few of these misunderstandings.</p><h4>The Rise of “Anyone”</h4><p>You may have heard the marketing hype. With low-code tools, <em>anyone </em>can now build software — no Software Engineers required!</p><p>Sure.</p><p>Armed with WebMD, anyone can also be a doctor.</p><p>True to some extent, but if the fever isn’t going away you still need the doctor.</p><p>I don’t want to downplay the power these tools place in the hands of end-users. They truly do get end-users from building spreadsheets to building their own software. What is important to note is that these are software solutions simple enough to be built by point-and-click tools. Most of these solutions would be similar in complexity to a spreadsheet.</p><p>There is a reason low-code rather than no-code is the buzzword. Any solution beyond simple will require code. While low-code tools do create a wonderful opportunity for citizen developers to dabble into code, you still need people who <em>can</em> write maintainable code. Take a look at the <a href="https://trailhead.salesforce.com/sample-gallery">Sample Gallery at Salesforce Trailhead</a> for an example. I picked the <a href="https://github.com/trailheadapps/ebikes-lwc">“E-Bikes” app</a>: There’s no way “anyone” is going to write <a href="https://github.com/trailheadapps/ebikes-lwc/tree/master/force-app/main/default/classes">these Apex classes</a>, these <a href="https://github.com/trailheadapps/ebikes-lwc/tree/master/force-app/main/default/lwc">JavaScript-based web components</a>, or even manage it all in a git repository let alone worry about security, error-handling and performance.</p><p>Low-code tools can be incredibly effective in the hands of skilled and experienced developers.</p><h4>Revolution and Evolution</h4><p>In 2014, Forrester Research coined the term “low-code” to describe this new rising category of software development platforms. As a developer, you would notice many similarities to tools you may have used in the past.</p><p>In my opinion, the real revolution in 2014 was not the platforms, but the marketing world’s discovery of a magic phrase to sell these tools to executives who pay people 6-digit salaries to write code.</p><p>Don’t get me wrong — the evolution of these tools has been fantastic. Modern low-code tools like Salesforce are powerful and in addition to delivering software fast, they address many of the problems surrounding maintainability and performance that plagued tools of the past. But the fact is that the idea of using visual tools to speed up development is not new at all. It has been around ever since the capability to build visual tools has been around. CASE tools, RAD tools, code generators, UI builders all shared that goal. In fact, even the idea of allowing non-programmers to create their own software solutions isn’t new.</p><p>As a developer, I see modern low-code tools as a natural evolution and improvement of these tools of the past.</p><p>Microsoft’s Visual Basic 6, while not the first tool to attempt it, is the earliest low-code success story I can think of. A point-and-click interface with an easy-to-understand language and a plugin-based system enabled quick delivery of software and opened doors for people who weren’t skilled programmers. I myself, a middle-school student at the time with barely any programming knowledge, was able to hack things together.</p><p>Wordpress, another example from the mid 2000s, could well be classified as a low-code tool. A lot of no-code capabilities to build a specific class of software (content-based websites) with the ability to extend through code using a plugin-based system.</p><p>Oracle Application Express (APEX), which dates back to early 2000s when it was known as HTML DB, is another example.<a href="https://www.developer.com/db/article.php/3384201"> They were marketing the same idea in 2004 for instance</a>, but did not have the word “low-code” in there. The phrase they <em>do</em> have in there, however, will make all marketers collectively cringe: <em>declarative development tool.</em></p><p>Good luck selling declarative development tools to the suits in the ivory tower.</p><p>They have learned the lesson now: The magic word “low-code development platform” now appears in the first sentence of the <a href="https://apex.oracle.com/en/">Oracle APEX landing page</a> along with other executive-grade phrases such as “20x faster” and “100x less code”.</p><h4>New Ways of Working</h4><p>A common reason for developer dissatisfaction is that building solutions with Salesforce is very different from building solutions with .NET, JavaScript, C++ or the like. This centers around the fact that low-code platforms trade flexibility for rapid delivery, and our ways of working are very much modeled to take advantage of the flexibility that development environments provide.</p><p>For instance, we’re used to building user-interface wireframes before jumping into development, but that doesn’t always work very well with Salesforce because Salesforce puts together most of the user interface for us. Regardless, I’ve seen the pattern many times: put together wireframes, realize Salesforce doesn’t agree with the wireframes, write completely custom-coded pages in Salesforce to get around the lack of flexibility, and finally sob in the corner bathroom stall. <a href="https://medium.com/@mehdimaujood/embrace-rapid-prototyping-with-salesforce-2d9541561c69">What might work better, instead, is rapid prototyping</a>.</p><p>The rapid delivery for flexibility tradeoff also means <em>all</em> stakeholders need to be on board with it. End users, product owners, business sponsors all need to understand that we may often have to choose a Salesforce way of doing something as opposed to custom-coding an alternative just to get a solution out there fast.</p><p>Knowing the platform deeply and it’s intricacies matters a lot too. As a .NET developer, I did not always have to know details about specific features. I just needed to know enough to know what to Google when the time comes. With Salesforce, however, it <em>is </em>important to know a lot of detail about features because decisions on whether to use out-of-the-box components/features or custom-coding often come down to knowing these details. Opting to go with out-of-the-box Salesforce components and learning about their limitations the hard way is a common pitfall and could put you in that corner bathroom stall again.</p><p>Low-code is changing the software delivery landscape, and developers are desperately needed. Not only because code still does and will always require expertise, but also because citizen developers who have the opportunity to jump into the world of code need guides and mentors.</p><p>The platforms are evolving fast too. Salesforce, for example, recently launched <a href="https://developer.salesforce.com/blogs/2018/12/introducing-lightning-web-components.html">Lightning Web Components</a>, a web development framework based on the <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">Web Component standard</a>. As part of Salesforce DX, Salesforce also enabled <a href="https://developer.salesforce.com/platform/dx">source-control integration that finally works</a>. Salesforce Functions, a feature currently in pilot, will allow developers to write serverless containerized functions in their language of choice to extend Salesforce apps. All of these new developments are ripe with opportunities for talented developers to not only whet their appetite for technical depth, but also to evangelize, build upon, and shape the direction of the platform.</p><p>Dan Appleman, a former Microsoft MVP, took advantage of such an opportunity when he authored <a href="https://advancedapex.com/">the most well-known book on Apex programming</a>. Andrew Fawcett probably wasn’t too thrilled about the lack of good design patterns and practices in the Salesforce world — so he wrote <a href="https://www.packtpub.com/product/salesforce-lightning-platform-enterprise-architecture-third-edition/9781789956719"><em>the </em>book about it</a>. David Liu took the opportunity to build <a href="https://www.sfdc99.com/">a website teaching newcomers how to code in Salesforce</a> and expanded it to <a href="https://www.pluralsight.com/courses/apex-absolute-beginner-guide-coding-salesforce">a series on Pluralsight</a>.</p><p>As the Salesforce Platform continues to grow, we will continue to see the addition of more and more programmatic capabilities targeted at developers and these will continue to present great opportunities for developers.</p><p>The landscape is changing — and developers who are paying attention will benefit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4e9d645b3f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/software-engineers-pay-attention-to-salesforce-c4e9d645b3f2">Software Engineers: Pay Attention to Salesforce</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embrace Rapid Prototyping with Salesforce]]></title>
            <link>https://maujood.medium.com/embrace-rapid-prototyping-with-salesforce-2d9541561c69?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d9541561c69</guid>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Mon, 06 Jul 2020 17:56:24 GMT</pubDate>
            <atom:updated>2020-07-06T17:56:24.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VesfaDPcakqC0kYD4mZU8Q.png" /></figure><p>Early and continuous feedback from both users and stakeholders is critical to any software project’s success. Take some examples: through early feedback, <a href="https://gfycat.com/elasticsizzlingblackwidowspider">this piece of software</a> could potentially have avoided what I imagine must have been post-release user riots. I can also imagine users facing a medical emergency (or at least a change of pants) after seeing <a href="https://www.reddit.com/r/CrappyDesign/comments/6aapp2/nearly_gave_me_a_heart_attack_upon_first_glance">this popup</a> around midnight which could also have been prevented through early feedback.</p><p>Beyond user experience horrors, early feedback can also course-correct incorrect requirements well before they are fully translated into wasted electrical signals.</p><h3>Rapid prototyping</h3><p>Prototyping is a powerful early-feedback tool no matter what technology you work with. Research shows that <a href="https://www.cs.colostate.edu/~bieman/Pubs/GordonBieman93SQJ.pdf">software meets user needs better if a prototyping is used as a technique</a>, and if you have experience with it you probably don’t need research to tell you that. Getting it right, however, has always required a good deal of skill and discipline along with the right tools …</p><p>… But as we will see, Salesforce makes rapid prototyping very, very easy.</p><h3>Idea to functioning app: hours, not days</h3><p>A fully functional app within hours instead of the traditional weeks is the point of low-code platforms like Salesforce. In fact, a functional app within hours is how almost <em>every </em>Salesforce project starts. You put together a data model, create an app, configure page layouts and start working from that shell of an application.</p><p>This presents a tremendous opportunity. Instead of lengthy requirement gathering and design activities before development starts, we can put a fully functional application (or well, at least a barely functional application) in front of users and stakeholders <em>as soon as we have a basic idea of what the data model should be. </em>Put that basic app out there, present to users and stakeholders and gather feedback. Rinse and repeat.</p><h3>Evolutionary and Throwaway Prototyping</h3><p>Prototyping has consistently been shown to be effective but it does come with risks — one of the biggest risks being the prototype evolving into a full application with enough technical debt to warrant an immediate bankruptcy. A less risky approach is to use “throwaway” prototyping which mandates that you throw away your hacky prototype once it’s clear what needs to be built, and then start from scratch for the less-hacky production system.</p><p>Evolutionary prototyping is where Salesforce shines. For starters, you begin by developing and refining the key entities and their relationships, which ensures your early iterations weed out potential issues with the data model giving you solid base to build on. As you refine the foundation, the technical debt you incur is far easier to clear out because you’re still dealing mostly with declarative elements — which means manageable metadata, not spaghetti code. By the time you have a clear enough vision of the end goal, the odds are that you have a solid base to build on.</p><p>That said, all circumstances are unique, and you may find yourself mired in levels of uncertainty that <em>do</em> warrant a throwaway prototype. Managed properly, the Salesforce metadata-driven model is <em>resistant</em> but not <em>immune</em> to technical debt and your prototype may still need a good amount of code.</p><h3>Top-down and bottom-up</h3><p>In the software development world, we tend to do design what we intend to build <em>before</em> we build it. We may still do some sort of prototyping like wireframes, interactive mockups or even use a specialized approach to prototyping like quick and dirty JavaScript apps, but the ultimate goal is to know what you’re building before you build it.</p><p>This <em>top-down</em> approach is not a bad thing at all. The last time an empty head on a sharp suit asked you to build something but nobody knew what that something was probably didn’t leave you with positive memories.</p><p>With Salesforce, however, things turn out very different when you design too much first because <em>Salesforce is very opinionated about what your solution should look like.</em></p><p>This trait is not unique to Salesforce. The majority of RAD or low-code tools I have come across are very opinionated on what the solution should look like, but developers approaching the tool with a top-down mindset often end up “fighting” the tool when it fails to enable their preconceived designs.</p><p>What works better instead is that you first understand the business problem that needs to be solved, start by building a basic app/prototype that would solve part or all of the business problem, and rapidly iterate to evolve it into a functional solution.</p><h3>Embracing Rapid Prototyping</h3><p>It’s easier said than done. The industry often does a fantastic job of replacing any interaction between developers and users/stakeholders with several layers of experts skilled in the art of missing the point. You not only have to embrace the practice yourself, but you also have to <em>sell</em> the idea to users, fellow techies and everyone in between.</p><p>Prototypes themselves face little resistance. Users and stakeholders love seeing something visual. The <em>harder </em>thing to sell is the fact that a bottom-up approach means Salesforce makes a lot of decisions on what the solution should look like — and this one usually comes down to the person with the checkbook understanding that it saves them a ton of money.</p><p>Regardless of the unique circumstances, however, there should be a good amount of benefit you could gain by embracing a bottom-up rapid prototyping approach to building applications on the Salesforce platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d9541561c69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Please don’t use the Process Builder for that]]></title>
            <link>https://medium.com/salesforce-zolo/please-dont-use-the-process-builder-for-that-97e148f109c5?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/97e148f109c5</guid>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Sat, 19 Oct 2019 16:32:12 GMT</pubDate>
            <atom:updated>2019-10-19T17:08:12.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQW8XJJCeozhJ7D-ZKP8xA.png" /><figcaption>Just don’t</figcaption></figure><p>The low-code revolution with its point-and-click solutions has a pretty clear message for us developers: avoid Apex whenever possible. The guidelines dictate that solutions that write Apex for something that could have been done through a point-and-click tool are inferior.</p><p>Most of the time, the advice is sound. Unfortunately, the whole message around low-code and point-and-click makes it too easy for us to miss the following immensely important message which you’ll find somewhere deep inside the developer guide:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*mBi6hLBQlUyaeE82Btuwig.png" /></figure><p>When you’re all revved-up about low-code solutions and ready to point-and-click your way out of every problem, it’s easy to glance over the above. Just to make a point about how important it is, I’m going to post a zoomed-in picture of the above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*POJNtxx6h3B8DKytJD7j4A.png" /><figcaption>Source: <a href="https://sforce.co/31X1Arl">https://sforce.co/31X1Arl</a></figcaption></figure><p>Now let’s talk about why.</p><h3>Isn’t low-code better?</h3><p>Yes, it is. Low-code solutions are always good. They’re easier to maintain, faster to implement, and they’re what make low-code platforms like Salesforce so powerful. When we’re looking to solve a problem through Salesforce, our first instinct should be to use a no-code or a low-code solution.</p><p>The pitfall that we’re looking at here happens when the word “low-code” compels us to write workflow rules or create a process on an object that has or will have a trigger running on it as well.</p><p>The good design choice is this: If requirements around an object are complex enough to warrant an Apex trigger now <em>or in the future</em>, stick only to Apex triggers.</p><h4>And what really is wrong with mixing the automation tools?</h4><p>The first problem is that you can’t control the order of execution.</p><p>Imagine that you have a requirement complex enough to warrant a before insert Apex trigger to update some fields. You also have a Workflow Rule running that updates a field value, and you need the workflow update <em>before</em> your trigger executes.</p><p>You code it and it runs fine. Looks like the workflow rule updates the value before your trigger runs. You did get lucky though — and this is where you realize that mixing automation tools can be a problem: a process would not have executed before the trigger. But for now, everything’s well, users are happy, your boss loves you and you love your boss.</p><p>But beneath those smooth executions and flawless field updates, there is an ugly truth waiting for its moment to alienate your users and destroy whatever’s going on between you and your boss: <em>Triggers execute </em><strong><em>before</em></strong><em> workflow rules.</em></p><p>Wait, what?</p><p>But then why did your code work in the first place? <em>Because a workflow field update causes triggers to re-run. </em>And you probably won’t discover that until you’re coding something else.</p><p>I don’t know about you, but I feel that the above scenario is uglier than a <a href="https://www.irishtimes.com/news/science/blobfish-voted-world-s-ugliest-creature-1.1525234">Blobfish</a>. I’m writing this at 9 pm and just the thought of the above is going to prevent me from having a good night’s sleep.</p><p>There are other problems too: Your solution becomes harder to understand because logic is distributed in multiple places, more error-prone because you don’t get the same level of testing, debugging and error-handling, and also trickier deployments because you’re now dealing with a new metadata item per-version, not to mention the manual step of activating the process after every deploy.</p><p>With that in mind, let’s lay down some …</p><h3>… ground rules</h3><p>We find broadly two kinds of projects in the low-code world: Ones built and supported by professional software developers, and ones supported (and maybe also built) by not-software-developers who understand the point-and-click side of Salesforce.</p><h4>Avoid processes and workflows for developer-supported projects</h4><p>If your project is complex enough to require constant support from Apex developers, you may want to avoid processes and workflows altogether. Anything you do with the Process Builder is never too hard with Apex, and creating processes puts you at risk of having to migrate it all to Apex if the need for triggers arises in the future.</p><h4>Use processes to their fullest for non-developer-supported projects</h4><p>If you conclude, however, that the application you’re building will be supported by admins or <a href="https://www.gartner.com/it-glossary/citizen-developer/">citizen developers</a> who can only work with the point-and-click side of Salesforce, you have a very good use case for using <em>only</em> the process builder, going as far as calling Apex methods from the process where necessary instead of a trigger.</p><p>For projects like these, calling Apex through a process instead of writing a trigger leaves the door open for point-and-click developers to extend the application because they can control when exactly your Apex executes.</p><h4>Favor processes over workflow rules</h4><p>If you choose to use point-and-click automation on an object, choose to work with the process builder instead of workflow rules when you can. This also means <a href="https://trailhead.salesforce.com/en/content/learn/modules/workflow_migration/workflow_migration_intro">migrating existing workflow rules to the process builder</a> because you want only one automation tool.</p><h4>Is this object ever going to need an Apex trigger in the future?</h4><p>Even if you have a project that you know will require support from software developers — and for some reason you really, really want to — you would be just fine using the process builder if you can be certain that your object won’t require Apex in the future. Be careful though: if requirements were that easy to predict, we would all happily be following the waterfall model.</p><h4>Remember to migrate workflows to processes or processes to triggers</h4><p>If you’re working on a complex project, chances are that you’re dealing with objects that have all three on one object. If your automation tool of choice is the Process Builder, you should migrate workflow rules to processes and if you have apex triggers, you should migrate processes and workflow rules to triggers.</p><p>There is for sure a cost associated with that migration, but treat it as any other technical debt. The cost of not migrating to the right automation tool is probably a lot more than taking the time to fix things early.</p><p>The Salesforce world is filled with Objects that have a bunch of workflow rules, a couple of processes and (hopefully just one) trigger. Things can get ugly really fast if we mix of all of that, and chances are you’ve lost sleep over a bug caused by mixing these automation tools.</p><p>The verdict from Salesforce is clear: Only use one automation tool per object. And the best tool might just be Apex.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97e148f109c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/please-dont-use-the-process-builder-for-that-97e148f109c5">Please don’t use the Process Builder for that</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StripInaccessible: The great new way to enforce security in Apex]]></title>
            <link>https://medium.com/salesforce-zolo/stripinaccessible-the-great-new-way-to-enforce-security-in-apex-e2cf79cb9500?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2cf79cb9500</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[apex]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Wed, 05 Jun 2019 22:54:12 GMT</pubDate>
            <atom:updated>2019-06-23T23:36:28.128Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T567f9-EtOjrquPnYsoDIg.png" /></figure><p>Summer ’19 brings us a great new update to enforce security in Apex through the Security and SObjectAccessDecision classes. Put simply, the new feature (which is still in pilot phase as of this writing) allows us to clear field values on lists of sObjects that the user doesn’t have access to. In this post, we will dive into this new feature, code some experiments to see how exactly it works and explore different scenarios that the <a href="https://releasenotes.docs.salesforce.com/en-us/summer19/release-notes/rn_apex_Security_stripInaccessible.htm">release notes</a> didn’t cover.</p><p>We’ll start with a little background on Apex and Security which you can skip if you’re comfortable with the idea of the system execution context and the difference between field/object-level and record-level security in Apex.</p><h3>Apex and Security: Background</h3><h4>The System Context</h4><p>Any time you attempt to access data in Apex (through a SOQL query, for example), you get to query <em>all </em>fields on <em>all</em> objects. You also get to create and update records for objects that the current user <em>doesn’t</em> have access to. Not just fields and objects, you can even query <em>all</em> records regardless of the currently logged in user. This is the magic (or horror, in case you discovered this the hard way) of the <strong>system context</strong>.</p><p>There are exceptions to that rule. A Standard Controller in a Visualforce page will respect the user’s permissions, executing on what we can call the <strong>user context</strong>. That is why if you’re creating a custom Visualforce edit page or a Visualforce record page, Salesforce will thankfully ensure that an oversight from you doesn’t end up broadcasting confidential information to users. The Salesforce community has done a great job of documenting the <a href="https://salesforce.stackexchange.com/questions/172060/types-of-execution-system-mode-or-user-mode">different cases in which Apex executes in either the system context or the user context</a>.</p><p><strong>Object-level vs Record-level security</strong></p><p>When we talk about security in Apex, there are generally two distinct kinds we consider: record-level security and object/field-level security.</p><p>The world of record-level security is relatively simple: we can <a href="https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_keywords_sharing.htm">use with sharing, without sharing and inherited sharing keywords</a> to enforce the record-level security we need for Apex scripts running in the system context. Field-level and object-level security, however, are more complicated to deal with. By default, this kind of security is not enforced at all. While there <em>are</em> ways to enforce field-level security in Apex, updates in the Summer ’19 release give us a far cleaner alternative to the existing methods.</p><h3>Strip inaccessible fields</h3><p>The release notes for the new feature provide the following sample code:</p><pre>List&lt;Opportunity&gt; opportunities = new List&lt;Opportunity&gt;{<br>    new Opportunity(Name=&#39;Opportunity1&#39;),<br>    new Opportunity(Name=&#39;Opportunity2&#39;, Probability=95)<br>};<br><br>// Strip fields that are not creatable<br><strong>SObjectAccessDecision decision</strong> = <strong>Security.stripInaccessible</strong>(<br>    <strong>AccessType.CREATABLE</strong>,<br>    opportunities);<br><br>// Print stripped records<br>for (SObject strippedOpportunity : <strong>decision.getRecords()</strong>) {<br>    System.debug(strippedOpportunity);<br>}</pre><p>The idea is simple: fields that the user does not have access to will be <strong>unset</strong>. Emphasis on the word unset because this is different from setting a field’s value to null — A null value is saved to the database in case of a DML operation while a value of “unset” will be ignored.</p><p>The code passes the value AccessType.CREATABLE to the stripInaccessible function to indicate that fields that the user cannot <em>create</em> should be stripped, but we can also pass AccessType.UPDATABLE and AccessType.READABLE to strip out fields that the current user cannot update or read.</p><p>There are a few questions you could be asking at this point. What happens if the user doesn’t have access to the entire object? What if we query data and include parent fields? Will the parent fields be stripped as well? What happens if we include child objects in a sub-query? The release notes don’t mention all of those, so let’s dive in and find out!</p><h4>Case 1: No access to sObject at all</h4><p>For my first experiment, I removed all access for my test user for the Account sObject. I then had the following Apex executed in the system context while logged in as the test user:</p><pre>List&lt;Account&gt; accounts = [SELECT Id, Name, AccountNumber, Phone FROM Account];</pre><p>The query would, of course, return all Account records with every field with Name, AccountNumber and Phone fields set regardless of the test user’s permissions. That is how the system context works.</p><p>I then had this account list passed through the following function to get rid of fields that the user does not have <em>read</em> access to:</p><pre>private List&lt;Account&gt; secureAccounts(List&lt;Account&gt; accounts) {<br>    SObjectAccessDecision decision = <strong>Security.stripInaccessible</strong>(<br>        <strong>AccessType.READABLE</strong>,<br>        accounts);<br>    return (List&lt;Account&gt;) <strong>decision.getRecords()</strong>;<br>}</pre><p>This is what I got back from the call to stripInaccessible:</p><pre>System.NoAccessException: No access to entity: Account</pre><p>stripInaccessible does <em>not</em> throw an exception if the user <em>doesn’t</em> have access to certain fields, but it looks like it <em>does</em> throw an exception if the user doesn’t have access to the sObject to begin with. This behavior makes sense because stripInaccessible is not supposed to remove any <em>records</em> from the passed list (remember that this function is not supposed to enforce record-level security), and a list of Accounts with null in every field is not a sensible thing for the function to return either.</p><p><strong>enforceRootObjectCRUD</strong></p><p>The stripInaccessible function has an optional parameter called enforceRootObjectCRUD which is true by default. If we pass false instead of the default value, however, we can avoid the exception and get back a completely useless list with null for every field.</p><p>Completely useless for now, but we’ll see it can make sense for some other cases we’ll explore soon.</p><h4>Case 2: No access to fields on parent sObject</h4><p>For this experiment, I queried Contacts and included information from the Account sObject:</p><pre>List&lt;Contact&gt; contactsWithAccount = [SELECT Id, LastName, Phone, Account.Id, Account.Name, Account.Phone FROM Contact];</pre><p>My test user did not have access to the Phone fields on either the Contact sObject or the Account sObject. The result was pretty much what I hoped for: the Phone and Account.Phone fields were null after being passed through stripInaccessible. It’s good to see that this feature strips out fields from parent sObjects as well.</p><h4>Case 3: No access to parent sObject</h4><p>For this experiment, I ran the exact same query as above but revoked <em>all</em> access to the Account sObject for my test user. The result? All the account fields were set to null. I was afraid that contactsWithAccount[0].Account itself would be set to null resulting in a NullPointerException upon trying to access contactsWithAccount[0].Account.Name, but was greeted with pleasant design choice of setting only the fields to null.</p><p>Interestingly, this time there was no System.NoAccessException.</p><h4>Case 4: No access to object at all, but access to parent sObject</h4><p>This experiment uses the same query I’ve used for the last two experiments:</p><pre>List&lt;Contact&gt; contactsWithAccount = [SELECT Id, LastName, Phone, Account.Id, Account.Name, Account.Phone FROM Contact];</pre><p>This time I tried something more interesting. I revoked my test users’ access to the Contact sObject, but left them read access for Account. The result was what I expected: System.NoAccessException.</p><p>And this is where the formerly uselessenforceRootObjectCRUD comes in.</p><p>When I set enforceRootObjectCRUD to false, the stripInaccessible function returned the records with null for Contact fields (as the user had no access to the Contact sObject) but had values for the Account fields.</p><h4>Case 5: Subqueries</h4><p>To experiment with lists that include child records, I tried the following list of sObjects:</p><pre>List&lt;Account&gt; accountsWithContacts = <br>    [SELECT Id, Name, Phone, <br>        (SELECT Id, LastName, Phone FROM Account.Contacts) <br>    FROM Account];</pre><p>Once again, I passed it through stripInaccessible to remove all fields that the user did not have read access to. I tried removing read access for the Phone field on Contacts, and tried removing access completely for the Contact sObject. The result in both cases was the same: nothing is removed from the child records.</p><p>It looks like stripInaccessible removes field values only on the original sObject list, but does not recursively remove field values on records obtained through subqueries. This is not a bad design choice — it gives us the flexibility to not have child records sanitized if we don’t need them sanitized. We always have the option of making a second call to stripInaccessible on the child list if we need to.</p><p>I did, however, receive feedback that the ability to strip fields from results of subqueries is on the roadmap and may be there in the beta release.</p><h3>Conclusion</h3><p>Overall, the feature looks very promising. Field and object-level security has never been fun to implement in Apex and this feature looks like it will make many use cases much easier to implement. I am looking forward to seeing this get past the pilot phase into a beta release and then generally available!</p><p>I do want to give a special thanks to <a href="https://ca-peterson.com/">Chris Peterson</a> for <a href="https://www.reddit.com/r/salesforce/comments/bxa9ar/stripinaccessible_the_great_new_way_to_enforce/erf0vm3/?context=3">giving some detailed feedback</a> on this article and correcting me in a few places.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2cf79cb9500" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/stripinaccessible-the-great-new-way-to-enforce-security-in-apex-e2cf79cb9500">StripInaccessible: The great new way to enforce security in Apex</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The easy guide to understanding JS Promises]]></title>
            <link>https://medium.com/salesforce-zolo/the-easy-guide-to-understanding-js-promises-78f5f19539e0?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/78f5f19539e0</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Sat, 06 Apr 2019 23:01:25 GMT</pubDate>
            <atom:updated>2019-04-06T23:01:25.252Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUmm_LLe1f-P4ZQthgmvpA.jpeg" /></figure><p>I’ll be honest. I struggled to understand promises when I first started learning about them. I had to walk through multiple articles and examples and experiment a good bit to get a handle on what was going on. I felt that most explanations I read left too much to the reader and didn’t impart the justice demanded by any complex idea: breaking it down into small, understandable parts.</p><p>The goal of promises is to write cleaner code by eliminating the excessive use of callback functions. If you’ve spent some serious time with JavaScript you may be familiar with something we call the “callback hell” which is something that starts with you passing lots of functions around and ends with you lamenting every single decision that led to the creation of JavaScript. Just ask this guy <a href="https://github.com/maxogden">Max Ogden</a> — he apparently got so upset with the callback hell that he made a website about it: <a href="http://www.callbackhell.com/">callbackhell.com</a>.</p><p>We do have a big-brained elite among us who just need to go over the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">MDN page on using promises</a> and they’re churning out promise-based code right after. I evidently was not one of them and if you’re like me, keep reading. I promise you’ll walk away with a good understanding of promises.</p><h3>Getting started with promises</h3><p>To put it as simple as possible, a promise is an <em>object</em> that represents an <em>operation</em>. Usually, promises are used to represent asynchronous operations like AJAX calls or an animation.</p><p>Since the above two sentences do absolutely nothing to further our understanding of promises, let’s try putting together an example of using a promise object to represent a very simple operation:</p><pre>function doLog() {<br>  console.log(&#39;Hello World!&#39;);<br>}</pre><p>doLog is a function, and functions are operations. This is how we build a promise object to represent doLog:</p><pre>var myPromise = new Promise(doLog);</pre><p>All we did is we passed doLog to the promise constructor and we now have a promise object representing the task to be carried out by doLog. And what happens when we execute the above line? We see the following in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*eMXzClQs_-jpIS1LEpv4pw.png" /></figure><p>Do you see what happened when you created a promise representing the function doLog? C<em>reating a promise object just called the function.</em></p><p>Think about that for a moment. new Promise(doLog) had the exact same effect as doLog(). The promise constructor just ran the function passed to it.</p><h4>The Promise object</h4><p>In order to further our understanding of what a promise object does, let’s see what information the myPromise object holds. If I type myPromise in the console, I see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/351/1*BsaMtRBA_weZqnDDJLxkCA.png" /></figure><p>myPromise has two properties — [[PromiseStatus]] and [[PromiseValue]]. The status is pending while the value is undefined.</p><p>Why is the status pending? The operation this promise represents, doLog, is complete. Shouldn’t the status be “completed” or something?</p><p>The reason the status is pending is that the <em>promise object doesn’t know that the task is complete</em>. As far as the promise is concerned, doLog may have sent out an AJAX call, set off a timer or started an animation that will take a few seconds to finish. There is no way for the promise object to know this — all it knows is that it was passed a function to execute.</p><p>It is doLog’s responsibility to tell the promise object when it’s done, and the promise object provides us with a way to do that. Take a look at the following modification to our code:</p><pre>function doLog(resolve, reject) {<br>  console.log(&#39;Hello World!&#39;);<br>  resolve();<br>}<br>var myPromise = new Promise(doLog);</pre><p>When the promise constructor calls doLog, it passes to it two functions that we’ll name resolve and reject. doLog can call resolve to let the promise object know that the task is complete, or call reject to let the object know that our task failed. Until resolve or reject are called, the promise would stay pending.</p><p>When the above piece of code finishes executing, the status of myPromise will be completed.</p><h3>Experimenting with a long-running task</h3><p>This is where things start getting interesting. Promises are designed to represent asynchronous processes, so let’s try our experiment with something like a timeout:</p><pre>function doWork(resolve, reject) {<br>  setTimeout(<strong>function () {<br>    console.log(&#39;Work done&#39;);<br>    resolve();<br>  }</strong>, 5000);<br>}<br>var myPromise = new Promise(doWork);</pre><p>Notice the callback function I’ve highlighted in bold. It will be called 5 seconds after doWork is called (a timeout of 5 seconds) and myPromise will stay pending for 5 seconds. Once 5 seconds have passed, myPromise will be resolved. I would encourage you to hit F-12, put the code in in your console and see how myPromise changes state after 5 seconds.</p><p><strong>.then()</strong></p><p>We can call then() to attach functions to a promise object that will be called when a promise is either resolved or rejected. Take a look at the following piece of code:</p><pre>function doWork(resolve, reject) {<br>  setTimeout(function () {<br>    console.log(&#39;Work done&#39;);<br>    resolve();<br>  }, 5000);<br>}<br>var myPromise = new Promise(doWork);<br><strong>myPromise.then(function () {<br>  alert(&#39;Success!&#39;);<br>}, function () {<br>  alert(&#39;Error!&#39;);<br>});</strong></pre><p>Notice that we’ve passed two functions to then. The first function gets called as soon as the promise is resolved (or gets immediately called if the promise is already resolved) and the second function gets called when the promise is rejected. When we execute this code, we will see “Work done” in the console after 5 seconds, immediately followed by an alert message saying “Success!”. This will happen because the first function we passed to then will be called right when the promise is resolved. The second function would have been called if the promise was rejected.</p><h4>The promise value</h4><p>In the beginning of this article, we saw that the promise object has two properties — value and status. We now know exactly what the promise status is, but we haven’t taken a look at what the value property does.</p><p>To cut it short, we can pass a value to the resolve and reject functions, and whatever we pass to them gets set as the promise value. Furthermore, the value we pass to resolve or reject also gets passed into the functions we attach to the promise object using then. Let’s look at an example:</p><pre>function doWork(resolve, reject) {<br>  setTimeout(function () {<br>    <strong>resolve(&#39;Work done!&#39;);</strong><br>  }, 5000);<br>}<br>var myPromise = new Promise(doWork);<br><strong>myPromise.then(function (msg) {<br>  alert(&#39;Success: &#39; + msg);<br>});</strong></pre><p>Let’s put all of this information together and create a promise to represent an AJAX call.</p><h3>Putting it together: an AJAX call</h3><p>This is how you would code an AJAX call using a Promise to represent it. For simplicity, I’m using jQuery’s ajax function.</p><pre>function myAjaxCall() {<br>  return new Promise(function (resolve, reject) { <br>    $.ajax({ <br>      url: &#39;/ajax/imaginary_url.html&#39;,<br>      success: function (data) {<br>        resolve(data);<br>      },<br>      error: function (xhr, status, error) {<br>        reject(error);<br>      }<br>    });<br>  });<br>}</pre><p>Notice that we’ve passed the function directly to the promise constructor this time instead of declaring it first. Then somewhere later in the code:</p><pre>myAjaxCall().then(function (data) {<br>  //this will be called when the ajax call is successful<br>}, function (error) {<br>  //this will be called if there&#39;s an error<br>});</pre><p>I now wish to communicate to my readers an ah-ha thought that may have occurred after seeing the above:</p><p><em>Converting the AJAX call from callbacks to promises was utterly, completely useless.</em></p><p>It’s true. We could do the same just as easily with callback methods. Instead of attaching methods to the promise using then, we could just pass two methods into myAjaxCall and it would work just as well. It would perhaps be <em>easier</em> to do this AJAX call without involving a promise object.</p><p>So what really is the point of promises?</p><h3>Promise chaining and avoiding the callback hell</h3><p>The true power of promises comes from the ability to <em>chain</em> promises. This is possible due to the fact that the function then itself returns a Promise.</p><p>If you’re returning a promise from the handler you attached through then, the promise then returns will resolve when your returned promise is resolved. If you return a simple value from the handler you attached using then, then the promise returned by then will be in a resolved state with the returned value as the promise value. I know this sounds complicated, so let’s dive into an example:</p><pre>//this function returns a promise that resolves in msec milliseconds<br>function wait(msec) {<br>  return new Promise(function (resolve) {<br>    setTimeout(resolve, msec);<br>  });<br>}</pre><p>The function call wait(3000) will return a promise that resolves in 3 seconds. The call wait(6000) will return a promise that resolves in 6 seconds. Now take a look at the following:</p><pre><strong>wait(3000)</strong>.then(function () {<br>  <strong>console.log(&#39;Waited 3 seconds!&#39;);</strong><br>  <strong>return wait(6000);</strong><br>  //notice that we&#39;re returning a promise<br>}).then(function () {<br>  //The previous handler returned a promise<br>  //This means that we will now wait for that promise to resolve<br>  //When it&#39;s resolved, this handler executes<br>  <strong>console.log(&#39;Waited 6 more seconds!&#39;);</strong><br>  <strong>return 5;</strong><br>}).then(function (val) {<br>  //the last handler returned a number<br>  //this handler will be called immediately, as the promise<br>  //returned by the last .then() call was resolve immediately<br>  <strong>console.log(&#39;This will be called immediately&#39;);<br>  console.log(&#39;The value passed is: &#39; + val);</strong><br>});</pre><p>I know the above may be a little hard to understand. I would encourage you to play around with it if it’s unclear as it’s very important that you understand exactly what’s happening in the code above before proceeding.</p><h4>An example of better code through promises</h4><p>Imagine that you have to send an AJAX call, launch two animations together after the ajax call returns, launch a third animation when the two animations finish and put data on the screen after the animations end. That’s four asynchronous operations. This is what it could look like with callbacks:</p><pre>var oneAnimationComplete = false;</pre><pre>doAjax(function (data) {<br>  doAnimation1(function () {<br>    onAnimationComplete(data);<br>  });<br>  doAnimation2(function () {<br>    onAnimationComplete(data);<br>  });<br>});</pre><pre>function onAnimationComplete(data) {<br>  if (oneAnimationComplete) {<br>    doFinalAnimation(function () {<br>      renderData(data);<br>    });<br>  } <br>  else oneAnimationComplete = true;<br>}</pre><p>You can see that the code is not very intuitive. It’s not easy to see the <em>sequence</em> of the different operations because the different functions we’re passing around are scattered all over the place. Notice the clumsy way of ensuring that the last animation is called after <em>both</em> animation1 and animation2 are complete. A little more code like this and you’re deep into callback hell territory wishing you’d picked basket-weaving instead of programming.</p><p>With promises, and with special thanks to promise chaining, you can write it like this:</p><pre>let data = {};<br><strong>doAjax()</strong>.then(function (d) {<br>  data = d;<br>  <strong>return Promise.all(doAnimation1(), doAnimation2());<br>  </strong>//Promise.all<strong> </strong>returns a new promise that is resolved <br>  //when all promises passed to it are resolved<br>}).then(function () {<br>  <strong>return finalAnimation();</strong><br>}).then(function () {<br>  <strong>renderData(data);<br></strong>});</pre><p>You can see the big difference. These operations are expected to execute one after the other, and promises allow code to cleanly capture that flow. We don’t need to have messy nested callbacks anymore, we can now have lines of code one after the other just like we would in synchronous code. Do the ajax call, then do <em>both</em> animation1 and animation2, then do the final animation and then render the data. The code is readable and captures the actual flow of operations.</p><p>Notice the use of Promise.all — it returns a new promise that is resolved when all promises passed to it are resolved. Promise.all is one of the many bells and whistles that come with promises.</p><p>Here is an excellent article that reinforces the <a href="https://gist.github.com/domenic/3889970">idea of promises allowing us to mimic synchronous code</a>. Finally, don’t forget the ultimate resource: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">The Mozilla Developer Network section on promises</a>.</p><p>With Aura Component APIs returning promises for asynchronous operations and the advent of JavaScript-focused Lightning Web Components, it is especially imperative for us Salesforce developers to arm ourselves with a proper understanding of promises. Promises have a lot to offer but can be difficult to get started with and I hope my article was a help here, but do remember to keep exploring.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78f5f19539e0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/the-easy-guide-to-understanding-js-promises-78f5f19539e0">The easy guide to understanding JS Promises</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What every Salesforce developer should know about Dates and Times in Apex]]></title>
            <link>https://medium.com/salesforce-zolo/what-every-salesforce-developer-should-know-about-dates-and-times-in-apex-d49bc0a116d4?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49bc0a116d4</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[apex]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Sat, 16 Feb 2019 04:43:53 GMT</pubDate>
            <atom:updated>2019-07-07T18:47:39.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PrNqjmpkPMEVJMhhLaUNCQ.jpeg" /></figure><p>Dates, times and computers have never been the best of friends. Just look at the list of famous bugs caused by miscalculations in Dates and Times: <a href="https://en.wikipedia.org/wiki/Year_2000_problem">the famous y2k bugs which cost over $300 billion worldwide to address</a>, the Deep Impact spacecraft which was <a href="https://en.wikipedia.org/wiki/Deep_Impact_(spacecraft)#Contact_lost_and_end_of_mission">lost because the time was stored in too small a variable</a>, or the deadly Patriot Missile Failure <a href="http://www-users.math.umn.edu/~arnold/disasters/patriot.html">which resulted in 28 deaths because the calculation was off by a small fraction of a second</a>. It’s not just huge disasters, simple miscalculations can cause bugs like the ones <a href="https://www.theverge.com/2018/10/8/17950300/apple-watch-series-4-reboot-crash-dst-bug">reported recently in the Apple Watch</a> causing crashes and reboots when Daylight Saving Time came into effect.</p><p>While Salesforce developers like you and me are unlikely to be faced with intercepting missiles or keeping track of spacecraft, we <em>are</em> likely to face angry users if we don’t handle dates and times properly. In this article, we’re going to list principles and practices when dealing with Dates, Times and DateTimes in Apex.</p><h3>Rule 1: Know your time zones</h3><p>Time zones aren’t fun. They’re even less fun when Daylight Saving Time (DST) is involved. Just ask <a href="https://www.chronicle.com/article/Ohio-U-Students-Riot-to/101471">the students in Ohio U. who went rioting after losing an hour of drinking time to DST</a>. One of those Ohio U. students may be your Director of Sales today, so it’s best you have your time zones sorted out.</p><h4>The two kinds of time zones</h4><p>Time zones come in two varieties — region-based and offset-based. When you set your org’s default time zone to America/Chicago, for example, you’re referring to the time zone of a region. The time in this region would either be GMT-06:00 or GMT-05:00 depending on whether DST is in effect or not.</p><p>Then we have the offset varieties, such as Central Standard Time (GMT-06:00) and Central Daylight Time (GMT-05:00). These kind of time zones represent an offset from the Greenwich Mean Time, but don’t necessarily represent any particular region. The America/Chicago (or Central) region, for example, follows CST or CDT depending on the time of the year.</p><p>As you might guess, region-based time zones come with a problem. On November 3, 2019 at 02:00 AM America/Chicago, clocks “fall back” one hour. This means that November 3, 2019 at 01:30 AM in the America/Chicago region comes <em>twice</em>. Also, March 10, 2019 at 02:00 AM, the clocks are to “spring forward” one hour. This means that in the America/Chicago time zone, March 10, 2019 02:30 AM simply doesn’t exist.</p><h4>Time zones in Salesforce</h4><p>In Salesforce, we see region-based time zones very often. When you create a user, for example, you get to pick a region-based timezone for the user. You set your org’s default timezone to a region-based timezone as well. The timezone in my personal org, for example, is America/Los_Angeles. This is better than setting an offset-based time zone because Salesforce takes care of displaying the correct date and time to me whether Daylight Saving Time is in effect or not.</p><p>But we do still see offset-based time zones. If I build a DateTime object and call the format() method on it and specifically ask it to display the time zone, I would see an offset-based time zone. For example, if I run the following code in the console:</p><pre>DateTime dt = DateTime.newInstance(2019, 01, 17, 5, 0, 0);<br>System.debug(dt.format(&#39;MM/dd/yyyy hh:mm zz&#39;));</pre><p>I would see 01/17/2019 05:00 PST in the debug logs.</p><p>Using an offset-based time zone for display makes sense because it removes the ambiguity associated with region-based time zones. November 3, 2019 at 01:30 AM appears twice in America/Los_Angeles but when displaying the two instances, adding PST or PDT can resolve that ambiguity.</p><p>And using a region-based time zone when setting a user or org’s time zone or when constructing an instance of DateTime makes sense because DST gets handled internally.</p><h4>What time zones are available in Salesforce?</h4><p>If you go to your Company Information page on setup, you would see a list of time zones. America/Chicago and America/Los_Angeles are examples of time zones available. The list of region-based time zones available in Apex, however, is far greater.</p><p>The official documentation says that Apex supports all time zones returned by <a href="http://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html#getAvailableIDs()">TimeZone.getAvailableIDs</a> method in Java. Where does Java get this list from? Currently, Java gets this from the <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">tz database</a> which is an ICANN-backed collabarative effort to maintain a list of all time zones. Since governments can redefine time zones any time, the database is constantly updated.</p><h3>Rule 2: GMT is the model, everything else is a representation</h3><p>Imagine you have an object that represents distance and stores distances as millimeters. You can create a new Distance instance by perhaps calling Distance.newInstance(2000) which creates a distance object representing a distance of 2000 millimeters, or 2 meters. When you call the getDistance() method on the distance record, it returns 2000. If you call format() on the distance record, while your locale is somewhere in the UK, it prints out 2m. If you call format() while your locale is somewhere in the US, it prints out 6 ft, 6.7402 in. What’s important to remember here is that millimeters is the <em>model</em> we have chosen, and 2m and 6 ft, 6.7402 in are <em>representations</em>.</p><p>What do you say when someone comes to you and says that they wanted the distance object to represent distance in meters instead of millimeters? and so they just did Distance.newInstance(2)? Now, when they call getDistance(), it returns 2 which is what they wanted.</p><p>You would rightfully be flabbergasted. That’s not how it works. The Distance objects uses millimeters as the model and if you’re working with meters, be sure to multiply it by 1000 before constructing the object. Or maybe add a newInstanceMeters(Integer meters) function to your Distance class that multiplies the passed meters by 1000 and returns a Distance object representing 2 meters as 2000 millimeters.</p><h4>The GMT Model</h4><p>With DateTime objects, the logic is the same. GMT is the <em>model</em>, and dates in all other time zones are <em>representations. </em>Apex actually makes this pretty easy for us — all DateTime objects we create are GMT DateTimes, but provide us a way to display it in <em>any</em> time zone. Just like our Distance class above which stores distance in millimeters, but can display it in any many different units.</p><p>Let’s do an experiment. My user in the org I’m using right now has a time zone of America/Los_Angeles, which is 8 hours behind GMT. What happens if I construct a date for February 10, 2019 12:00 PM? I’ll put the following code in my anonymous apex window:</p><pre>DateTime dt = DateTime.newInstance(2019, 02, 10, 12, 0, 0);<br>System.debug(dt);</pre><p>The DateTime instance we constructed represents a moment in time. The moment in time when it’s February 10, 2019 12:00 PM in Los Angeles, California; February 10, 2019 02:00 PM in Chicago, Illinois and February 10, 2019 08:00 PM in the GMT time zone.</p><p>When we construct this date, Salesforce assumes that we’re talking about a moment in time in the current user’s selected time zone, which in our case is America/Los_Angeles. What do we see in the console when we print out the date using System.debug?</p><pre>2019-02-10 20:00:00</pre><p><em>08:00 pm.</em></p><p>Let me add some more emphasis to that: <strong>EIGHT PEE EM.</strong></p><p>Even though we constructed a DateTime for 12:00 PM.</p><p>What is the reason for this? Internally, Apex uses GMT as a model to store the date and time. Similar to how it doesn’t matter when we stored our distance as millimeters when we wanted to work with meters, it doesn’t matter that we store our DateTime as GMT, because all we want is to store a specific moment in time. It’s actually <em>better</em> that we use a consistent model to store our DateTime records.</p><p>And we can represent this moment in time in multiple ways, just like we could represent our distance as meters or feet and inches. Let’s run the following code:</p><pre>DateTime dt = DateTime.newInstance(2019, 02, 10, 12, 0, 0);</pre><pre>System.debug(&#39;Pacific Time: &#39; + dt.format(&#39;MM/dd/yyyy hh:mm a zz&#39;, &#39;America/Los_Angeles&#39;));</pre><pre>System.debug(&#39;Central Time: &#39; + dt.format(&#39;MM/dd/yyyy hh:mm a zz&#39;, &#39;America/Chicago&#39;));</pre><pre>System.debug(&#39;GMT: &#39; + dt.format(&#39;MM/dd/yyyy hh:mm a zz&#39;, &#39;Etc/GMT&#39;));</pre><p>This is the result in the debug log:</p><pre>Pacific Time: 02/10/2019 12:00 PM PST<br>Central Time: 02/10/2019 02:00 PM CST<br>GMT: 02/10/2019 08:00 PM GMT</pre><p>Additionally, do remember that the result would have been different if my user’s selected time zone was America/Central, because February 10, 12PM in Central Standard Time would translate to 6PM in GMT:</p><pre>Pacific Time: 02/10/2019 10:00 PM PST<br>Central Time: 02/10/2019 12:00 PM CST<br>GMT: 02/10/2019 06:00 PM GMT</pre><h3>Rule 3: Always capture the correct moment in time</h3><p>This rules is implied by the previous rule, but it’s so easy to get this wrong that I feel it deserves a special mention.</p><p>The Salesforce world is filled with people asking how they can construct a DateTime in their local time zone. Most people who ask this question end up adjusting the DateTime object to look like their local time. This is a piece of code I picked up from the developer forums — and it’s not uncommon to see something like this in the dev forums or on stack overflow:</p><pre>Datetime gmt = DateTime.newInstance(2019, 02, 10, 12, 0, 0);<br>Integer offset = UserInfo.getTimezone().getOffset(gmt);<br>Datetime local = gmt.addSeconds(offset/1000);</pre><pre>System.Debug(&#39;GMT Time: &#39; + gmt);<br>System.Debug(&#39;Local Time: &#39; + local);</pre><p>The following is the result of this code:</p><pre>GMT Time: 2019-02-10 20:00:00<br>Local Time: 2019-02-10 12:00:00</pre><p>The intent was to create a DateTime object that represents February 10, 2019 12:00 PM as a local DateTime. Do you see the problem? <em>local does not represent the correct moment in time</em>.<em> </em>Sure, local evaluates to February 10, 2019 12:00 PM, and that is what we intended to construct, but it represents 12PM <em>GMT,</em> not 12PM PST. This is the same mistake is doing Distance.newInstance(2) because you wanted to capture a distance of 2 meters.</p><p>So what is the right answer to the question of constructing a DateTime in your local time zone? The answer is that you can’t. And in most cases, you don’t need to anyway. What you need from DateTime is to capture a moment in time, and every moment can be captured in GMT. Make sure that your DateTimes represent the correct moment in time, and you can always display it in any time zone.</p><h3>Rule 4: Store Date as Date, and Time as Time</h3><p>It is a good rule of thumb to <em>never</em> use DateTime if you only need to represent a particular time or a particular date.</p><p>Let’s take an example. What happens when you, a user in the America/Chicago time zone, try to save Feb 10, 2019 in a DateTime field instead of a Date field? Maybe you’d save Feb 10, 2019 00:00 as a DateTime. Which gets saved as Feb 10, 2019 06:00 GMT. Which is all good. And what happens when your boss, who is in the America/Pacific Time Zone, loads up your custom page which displays this very important date to him? He sees February 9, 2019. Because Feb 10, 2019 06:00 GMT is February 9, 2019 22:00 PST. What happens next? Your boss, who graduated from Ohio U., goes rioting.</p><p>Because DateTime is translated to the user’s time zone and stored as GMT, it’s never a good idea to use it to only store only a Date or a Time. Always be sure to use the Date and Time types in Apex and the Date and Time fields on sObjects if you only need to store a date or a time.</p><p>Another case where you would want to use separate Date and Time objects or fields is when representing an event that takes place at a certain local time in more than one place. For example, if you want to store a deadline to submit documentation on February 1, 2019 at 5:00 PM no matter where you are (your team in New York submits at 5:00 PM Eastern Time and you team in Los Angeles submits at 5:00 PM Pacific Time), you would want to use separate date and time fields.</p><p>Remember, DateTime represents a <em>specific moment in time </em>that is automatically adjusted across different time zones. To store values that don’t adjust based on time zone, use separate Date and Time fields.</p><h3>Rule 5: Be prepared if time zones are redefined</h3><p>In 2005, the US <a href="https://en.wikipedia.org/wiki/Energy_Policy_Act_of_2005#Change_to_daylight_saving_time">passed a bill which would extend daylight saving time by one hour effective 2007</a>. Instead of the first Sunday of April, DST would start coming into effect on the second Sunday of March. And <a href="https://www.nytimes.com/2007/03/05/technology/05daylight.html">it wasn’t pretty for us programmers</a>.</p><p>Do you see why that’s a problem for us? This is a case where the GMT model doesn’t work. Suppose that before the 2005 announcement was made, maybe some time in 2004, you had constructed a DateTime representing March 20, 2008 09:00 AM in America/Chicago and saved it in a field. It would have been saved as March 20, 2008 03:00 PM GMT.</p><p>But in 2005, the US announces that DST in 2007 would begin on March 11 instead of April 1. Suddenly, March 20, 2008 03:00 PM GMT, which is the GMT date you have saved, doesn’t translate to March 20, 2008 09:00 AM in America/Chicago anymore.</p><p>A good solution to deal with situations like these would be to <a href="http://www.creativedeletion.com/2015/03/19/persisting_future_datetimes.html">persist future DateTimes representing a particular local time in the local time zone</a>, but unfortunately Salesforce only allows us to save DateTimes in GMT. We could talk about saving a local DateTime as a Date, Time and a String Timezone field, but the added complication and the lack of ability in Apex to directly construct a DateTime from data in any given timezone (I intend to write a blog on how to do this later), it might not be worth it.</p><p>Depending on the situation, what we can do is keep an eye out for changes in time zone rules and be ready to either inform users or update the saved dates in case the rules do change.</p><h3>Conclusion</h3><p>Almost everything discussed above becomes obvious if we follow just one principle: DateTime always has GMT as the model. You can construct a DateTime based on the local time zone (the time zone of the user) but it’s always saved as GMT. Another important fact to remember is that time zones are region-based and adjust automatically for DST. Just keep these basics in mind and you won’t go wrong working across time zones.</p><p>Are there any other rules or practices you use when dealing with dates and times in Apex? I would be happy to hear your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49bc0a116d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/what-every-salesforce-developer-should-know-about-dates-and-times-in-apex-d49bc0a116d4">What every Salesforce developer should know about Dates and Times in Apex</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Call Apex or SOQL with just one line of code from your Lightning Aura Components]]></title>
            <link>https://medium.com/salesforce-zolo/call-apex-or-soql-with-just-one-line-of-code-from-your-lightning-aura-components-3b4b4fe70417?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b4b4fe70417</guid>
            <category><![CDATA[lightning-components]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Mon, 04 Feb 2019 16:19:38 GMT</pubDate>
            <atom:updated>2019-02-04T17:47:51.758Z</atom:updated>
            <content:encoded><![CDATA[<h3>Call Apex or SOQL in just one line from your Lightning Aura Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FcZmW_iR_I8bqkVmEo35Lg.jpeg" /></figure><p>Are you tired of writing lines and lines of boilerplate every time you need to run a SOQL query or call an Apex method from your lightning component? I am. Do you miss the ability to execute Apex or SOQL with just one line of code in JavaScript? I do.</p><p>In the old times when the world was still filled with just Visualforce pages, you could call an Apex method from JavaScript using the following line:</p><p>sforce.apex.execute(&quot;MyClass&quot;, &quot;getAccounts&quot;, {searchStr: &quot;Tech&quot;});</p><p>And you could execute some SOQL directly from JavaScript using the following:</p><pre>var q = &quot;SELECT Id, Name FROM Account WHERE Name LIKE &#39;%Tech%&#39;&quot;;<br>var accounts = sforce.connection.query(q);</pre><p>But the world of Lightning Aura Components got rid of all that nonsense. Any time we need to call some Apex or execute some SOQL in our JavaScript code, we now need to do something like the following:</p><pre>var action = cmp.get(&quot;c.getAccounts&quot;);<br>action.setParams(params);<br>action.setCallback(this, function(response) {<br>  var state = response.getState();<br>  if (state === &quot;SUCCESS&quot;) {<br>    var result = response.getReturnValue();<br>    //do something with the result<br>  }<br>  else if (state === &quot;INCOMPLETE&quot;) {<br>    // wait, what?<br>  }<br>  else if (state === &quot;ERROR&quot;) {<br>    var errors = response.getError();<br>    //do something about the errors<br>  }<br>});<br>$A.enqueueAction(action);</pre><p>Are you unimpressed with the latest-and-greatest, modern and streamlined approach to calling Apex in Lightning Components? You’re not alone.</p><p>Luckily, there’s a way to remedy all of that. Just by adding a utility base component to our code, we can create a way to call Apex or run some SOQL with just one line of code.</p><h3>A better way of calling Apex and SOQL</h3><p>With the help of a new “utility” component we’re going to build, our goal is to be able to call Apex using the following lines of code:</p><pre>helper.apex(component, &quot;getAccounts&quot;, { searchstr : searchTerm})<br>.then(function (result) {<br>  //do something with the result<br>})</pre><p>Here, we’re calling the function getAccounts defined on the Apex controller which takes in one parameter called searchStr. The most significant difference between the new approach and the original approach, as the keen reader might notice, is that the new approach is <em>not</em> 15 lines of boilerplate.</p><p>We also want to be able to <em>directly</em> execute some SOQL using the following lines of code:</p><pre>helper.soql(component, &quot;SELECT Id, Name, AnnualRevenue, Industry<br>   FROM Account WHERE Name LIKE &#39;%&quot; + searchTerm + &quot;%&#39;&quot;)<br>.then(function (accounts) {<br>  //do something about the accounts<br>})</pre><p>Easier to read? Yes. Faster to write? Yes. Let’s move on to the next section and find out how we can do all of this.</p><h3>Creating the ApexHelper utility component</h3><p>The above can be accomplished by creating a small utility component that defines the apex and soql functions.</p><p>First we’ll create a new Lightning Component and name it ApexHelper. This component will contain a component body and also contain some code in the helper JavaScript file. Additionally, we will also create an Apex Controller for this component called ApexHelperController. I created a Gist showing all of the code we need to put together along with a sample of how to use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/530675a4c7142940a1c0cf01263dd3d4/href">https://medium.com/media/530675a4c7142940a1c0cf01263dd3d4/href</a></iframe><p>Once you’ve created this utility component along with the associated Apex controller, you can start using the helper.apex and helper.soql functions in any component you have, provided that your components inherit from the new utility component. If you already have a base component in your org, you can either have the base component extend the new component or add this code directly into your base component.</p><p>In order to have your components inherit from our new utility component, you just need to add the extends=&quot;c.ApexHelper&quot; attribute to the aura:component tag:</p><pre>&lt;aura:component extends=&quot;c:ApexHelper&quot;&gt;</pre><p>Finally, here’s a gist showing in detail how we can use these utility methods in our components:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13c264d4f9f568043c1d57b4b8249d3a/href">https://medium.com/media/13c264d4f9f568043c1d57b4b8249d3a/href</a></iframe><p>One note when trying to use these utility methods inside of a helper: we use helper.apexwhen calling the utility functions from a JavaScript controller, but we would need to use this.apex and this.soql if we want to call these utility functions inside of a helper.</p><p>Do you think this is something that would make it easier to call Apex or SOQL from your lightning components? Please let me know your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b4b4fe70417" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/call-apex-or-soql-with-just-one-line-of-code-from-your-lightning-aura-components-3b4b4fe70417">Call Apex or SOQL with just one line of code from your Lightning Aura Components</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying Application and Component Events in the Lightning Component Framework]]></title>
            <link>https://medium.com/salesforce-zolo/demystifying-application-and-component-events-in-the-lightning-component-framework-fd3f090036cb?source=rss-c5ced674e8c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3f090036cb</guid>
            <category><![CDATA[salesforce-lightning]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <dc:creator><![CDATA[Mehdi Maujood]]></dc:creator>
            <pubDate>Fri, 25 Jan 2019 15:31:00 GMT</pubDate>
            <atom:updated>2019-02-01T18:15:41.633Z</atom:updated>
            <content:encoded><![CDATA[<p>Lightning components and applications communicate with each other primarily through an event-based model powered by Component Events and Application Events. However, reading the <a href="https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_and_actions.htm">official developer documentation</a> for the first time left me with some unanswered questions. I had to build out a few applications and test them out myself to learn exactly how these events function.</p><p>In this post, we’re going to do just that — build lightning components and see in detail how events function, which components can receive what events, the order in which they are received by other components and explore options such as bubble, capture and stopPropagation(). Last, we’ll also have a look at component methods as a means of inter-component communication.</p><h3><strong>Application Events</strong></h3><p>Custom lightning applications are generally structured as a parent application containing a hierarchy of lightning components. The defining characteristic of Application Events is that if <em>any</em> component in the hierarchy (or even the application) fires the event, <em>every</em> other component (or the application) will get a chance to handle the event. Think of them as “broadcast” style events — one component can broadcast a message to anyone who’s willing to listen.</p><p>Before discussing how Application Events work, let’s do a quick review of how to create them.</p><h4>Create the Event</h4><p>Create the Application Event by selecting File &gt; New &gt; Lightning Event in the Developer Console and add the following code:</p><pre>&lt;aura:event <strong>type=&quot;APPLICATION&quot;</strong> description=&quot;Event template&quot;&gt;<br>  <strong>&lt;aura:attribute name=&quot;message&quot; type=&quot;String&quot; /&gt;</strong><br>&lt;/aura:event&gt;</pre><p>Save it as LightningSimpleEvent. Notice the &lt;attribute&gt; tag — lightning events can not only notify receivers, they can also carry data. You can add multiple attributes here.</p><h4>Fire the Event</h4><p>In the component that needs to fire the event, add the following lines as part of the markup:</p><pre>&lt;aura:registerEvent name=&quot;appEvent&quot; <strong>type=&quot;c:LightningSimpleEvent&quot;</strong>/&gt;</pre><p>Notice the type attribute — it should contain the name you saved your event with. Next, in the controller:</p><pre>var appEvent = <strong>$A.get(&quot;e.c:LightningSimpleEvent&quot;);</strong><br>appEvent.<strong>setParams</strong>({ &quot;message&quot; : &quot;Special Message&quot; });<br>appEvent.<strong>fire()</strong>;</pre><p>Notice that when using $A.get to obtain the event, we don’t use appEvent which is the name we used when registering the event. Instead, we use the name that we saved the event file with. The name property on the registerEvent tag doesn’t really have much use for us — it’s the type property that matters.</p><h4>Handle the Event</h4><p>For the component handling the event, we need to add the following to the component markup:</p><pre>&lt;aura:handler <strong>event=&quot;c:LightningSimpleEvent&quot;</strong> action=&quot;{!c.handleApplicationEvent}&quot;/&gt;</pre><p>And we also add a method called handleApplicationEvent in the controller:</p><pre>handleApplicationEvent : function (component, event, helper) {<br>  var message = event.getParam(&quot;message&quot;);<br>  component.set(&quot;v.receivedMessage&quot;, message);<br>}</pre><h4>Application Events in Default Phase</h4><p>I created a small application to observe how Application Events work. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvHAXrNHSAzSQX4epDk9uA.png" /></figure><p>We have an application that contains two components. The two components, in turn, contain two more components to a create a total six components inside an application. Each component (as well as the application) has the ability to <em>fire</em> the application event we defined above (LightningSimpleEvent) through a button click, and each component also handles the same event and logs to the console when the event is handled.</p><p>What happens when we click the Send Event button on Application 1:0? We see the following in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*e9xJRdkt-CJ8-CT2djV1Fw.png" /></figure><p>As you can see, the two innermost components 43:0 and 70:0 got to handle the event first and then their parent 22:0. Next, the innermost components 124:0 and 151:0 followed by their parent 103:0. Finally the top level application gets to handle the event.</p><p>What happens if I click one of the innermost buttons?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*c4EJfh5ZAf49CfUAFG-Khg.png" /></figure><p>Exactly the same. It doesn’t matter where the event came from in the hierarchy. All components will get a chance to handle it.</p><p>The official documentation says that default application events are handled in a <em>non-deterministic order</em>, which just means we should not rely on the order in which the handlers receive the event. That does make sense because if you look at the order, it doesn’t look like something that you would want to rely on. If you have some background in data structures and algorithms, you might notice that the order is in fact a post-order traversal of the component hierarchy, but that very well might be an implementation detail that could change in the future.</p><h4>Application Events in Bubble Phase</h4><p>The example we saw above was handling events in “default” phase. When placing a handler, you have the option to handle the event in the “bubble” phase:</p><pre>&lt;aura:handler event=&quot;c:LightningSimpleEvent&quot; action=&quot;{!c.handleApplicationEvent}&quot; <strong>phase=&quot;bubble&quot;</strong>/&gt;</pre><p>Before discussing what the bubble phase is, let’s change all the handlers in our example application to have phase=&quot;bubble&quot;. When I click 70:0 while all the handlers are handling in the bubble phase, I see the following in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TfiJ28PdgZoL3IUSKnqFXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*E8EnFQKycFPkOXRr_JtMRw.png" /></figure><p>As you can see, in the bubble phase the event was first handled by the innermost component, the one that was clicked. Next, the parent got to handle the event and then the parent’s parent.</p><p>Clicking 22:0 does something similar — firing component handles first and then we go all the way up to the root:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sewJPrUy45k1wfiWOhvxNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*uUPxm6NhXYs32rHpAUzoyg.png" /></figure><p>The workings of the bubble phase in application events should be clear from these experiments. The element that fires an event gets a chance to handle it first, its parent element second, grandparent third and so on until the application root gets to handle the event.</p><h4>Application Events in Capture Phase</h4><p>We’ll start by doing exactly what we’ve been doing so far: code an example. For the next experiment, I changed all my event handlers to have phase=&quot;capture&quot; instead of phase=&quot;bubble&quot;. Let’s observe what happens when we send an event from 70:0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmmPefFzu9fgmtnXb209_A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/414/1*4xtPkwz2pxH05HdVklqbDg.png" /></figure><p>As you can see, when the components were handling the event in the “capture” phase, the application root got to handle the event first, and then the event traveled down to the component that actually fired it. The component that fired the event got to handle it <em>last</em>.</p><p>If the event was fired by 22:0, the application root would get to handle it in the capture phase first, 22:0 would get to handle it second, and no other components would be able to handle the event during the capture phase:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*vJE6XdlektfUT6ajectHvw.png" /></figure><h4>Application Events Lifecycle</h4><p>Now that we have a good grasp of what the three different phases look like, let’s go over a summary of the flow that application events follow:</p><ul><li>Whenever an application event is fired, the <em>capture </em>phase is the first to begin.</li><li>The event is first “captured” by the outermost component, the application root. If the application root has a phase=&quot;capture&quot; handler attached to it, it will be able to handle the event.</li><li>Once the application root has handled the event, the event will continue travelling down to the component that fired it and will be handled the next component in line — the child of the application root that leads to the target component. If the child has a phase=&quot;capture&quot; handler, it will be able to handle the event.</li><li>The event continues to flow down until it reaches the component that fired the event. Since the event has now reached the target, the “capture” phase is complete.</li><li>The <em>bubble</em> phase begins right after capture is complete. In the bubble phase, the event is first received by the component that fired it. If the component has a handler for the event with phase=&quot;bubble&quot;, it will get a chance to handle it.</li><li>Next, the event “bubbles” to the parent. If the parent has a phase=&quot;bubble&quot; handler, the parent gets to handle it.</li><li>The “bubbling” continues until the event has bubbled to the application root where the event can be handled with a phase=&quot;bubble&quot; handler. You can probably see by now why this phase is called “bubble” — the event is rising up just like a bubble in water rises to the top.</li><li>Once the bubble and capture phases are complete, the third phase is the default phase. In this phase, like we saw earlier, <em>all </em>components as well as the root get a chance to handle the event.</li></ul><p>The above lifecycle is broken if we use stopPropagation() somewhere in the capture or bubble phases, but we will examine that later. For our next experiment, we’ll look at component events.</p><h3>Component Events</h3><p>The defining characteristic of component events is that they only support <em>capture</em> and <em>bubble</em> phases. There is no <em>default</em> phase. What this implies is that if a component event is fired by a component, <em>only components in the containment hierarchy </em>will be able to handle the event, i.e. only parents, grandparents and the application root will be able to handle a component event.</p><p>You might wonder then, and rightfully so, why use component events at all? Application events can evidently do more. Application events fired by a component can be handled by the containment hierarchy if we want, but we have the additional option of having children and other sub-trees handle the event too.</p><p>There are two very good reasons to use component events whenever possible. The first reason is that component events are more efficient. The second (and the more compelling) reason is that component events facilitate better design by encouraging the <a href="https://en.wikipedia.org/wiki/Law_of_Demeter">principle of least knowledge</a>. In an ideal world, a component should only talk to components that it has a <em>direct</em> relationship with, such as its children or its parent. If you find yourself in a position where you need to communicate with a component in another sub-tree, consider if sending a component event to the parent and having the parent communicate with the child in question is a better design choice. Application events should only be reserved for cases where the event truly needs to be an application-level event.</p><p>You might also wonder, and again rightfully so, that if component events can only be handled by the containment hierarchy and application events are to be avoided unless necessary, how does a component send a message to a child? There are ways to do that, but the recommended approach is not through events. We will get back to this once we’re done with events.</p><h4>Creating Component Events</h4><p>Just like application events, component events need to be defined in an event file that looks like this:</p><pre>&lt;aura:event <strong>type=&quot;COMPONENT&quot;</strong> description=&quot;Event template&quot;&gt;<br>  &lt;aura:attribute name=&quot;message&quot; type=&quot;String&quot; /&gt;<br>&lt;/aura:event&gt;</pre><p>The only difference from an application event definition, highlighted in bold, is the type attribute which now has a value &quot;COMPONENT&quot;.</p><h4>Firing Component Events</h4><p>Just like application events, a component event needs to be registered in the component markup:</p><pre>&lt;aura:registerEvent <strong>name=&quot;compEvent&quot; type=&quot;c:LightningComponentEvent&quot;</strong>&gt;&lt;/aura:registerEvent&gt;</pre><p>This is exactly how application events are registered too. Remember when we talked about application events, we discussed that the name property is not useful for us? In case of component events, the name property is pretty important.</p><p>The firing component also needs the following code to fire the event:</p><pre>var evt = <strong>component.getEvent(&#39;compEvent&#39;)</strong>;<br>evt.<strong>fire()</strong>;</pre><p>You can see that instead of using the event file name (c:LightningComponentEvent) we’re using the value we had set in the name attribute. Also, we’re using component.get instead of $A.get.</p><h4>Handling Component Events</h4><p>Just like application event handlers, a component that handles a component event must define a handler in the markup and an associated function in the controller:</p><pre>&lt;aura:handler <strong>name=&quot;compEvent&quot;</strong> <strong>event=&quot;c:LightningComponentEvent&quot;</strong> action=&quot;{!c.handleEvent}&quot;&gt;&lt;/aura:handler&gt;</pre><p>Notice the one thing that wasn’t there in our application event handler — the name attribute. In case of component events, a name attribute needs to be present and it <em>must</em> match the name attribute on the aura:registerEvent tag for the event that needs to be handled. In our example, both the aura:registerEvent and aura:handler tags have name=&quot;compEvent&quot;.</p><p>The phase attribute is optional — the framework will handle events in the bubble phase by default. To handle component events propagating in the capture phase, phase=&quot;capture&quot; needs to added to the aura:handler.</p><h4>Capture and Bubble Phases in Component Events</h4><p>Like we discussed, capture and bubble phases in component events work just like they work in application events. We don’t need to go over the experiments again, but just for the sake of seeing how they work and for setting the stage for understanding the next topic, we’re going to do a little experiment. I wrote a similar application to the one we used last time, but this time using component events. For this experiment, I added <em>two</em> handlers to each component. One handling the event in the bubble phase, and one in the capture phase:</p><pre>&lt;aura:handler name=&quot;compEvent&quot; event=&quot;c:LightningComponentEvent&quot; action=&quot;{!c.handleEventCapture}&quot; phase=&quot;capture&quot;&gt;&lt;/aura:handler&gt;</pre><pre>&lt;aura:handler name=&quot;compEvent&quot; event=&quot;c:LightningComponentEvent&quot; action=&quot;{!c.handleEventBubble}&quot; phase=&quot;bubble&quot;&gt;&lt;/aura:handler&gt;</pre><p>Let’s see what happens when we click one of the innermost components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slj4SBo0WSeJeTs43d3y2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*nqomnynQvTuRB0hQDi7nYA.png" /></figure><p>You can see very clearly how the event was captured by the component and how it bubbled back to application root. If we click 22:0:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhP-u4LXuc_SFq4OLgp0rA.png" /></figure><p>We see the following in the console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*jpYb2ZvlpptTwAqD_I6htA.png" /></figure><p>As expected, the parents all get the event in both phases, but there is no way for either the children or other sub-trees to handle the event.</p><h3>stopPropagation()</h3><p>Stop propagation has a very simple job: Stop the capture and bubble process wherever it is. For an experiment, I used the following event handler in the component 22:0</p><pre>&lt;aura:handler name=&quot;compEvent&quot; event=&quot;c:LightningComponentEvent&quot; action=&quot;{!c.handleEventBubble}&quot; phase=&quot;bubble&quot;&gt;&lt;/aura:handler&gt;</pre><p>I modified the action associated with this handler to stop the propagation of events:</p><pre>handleEventBubble: function (component, event, helper) {<br>  console.log(&#39;event in bubble phase received by outer controller: &#39;<br>    + component.getGlobalId());<br>  event.stopPropagation();<br>}</pre><p>Whenever component 22:0 handles compEvent in the bubble phase, the propagation would stop and no other components will receive the event. Let’s send the event from component 70:0 and see what happens:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slj4SBo0WSeJeTs43d3y2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*Cq1xBIg9VavMvLI78-tlog.png" /></figure><p>As you can see, the capture phase was completed successfully, but the bubble phase was interrupted and the event never bubbled to the application root.</p><p>What happens if we call event.stopPropagation() in the capture handler in component 22:0? Let’s have a look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*slj4SBo0WSeJeTs43d3y2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*rb2xXgOHnh6_PgML0IkXqg.png" /></figure><p>The capture phase began with the application root handling the event, continued with the component 22:0 handling the event but the cycle was stopped because the handler in component 22:0 called the stopPropagation() method. The capture phase was never completed and the bubble phase never started.</p><h4>stopPropagation() in Application Events</h4><p>Application Events here require a special mention because of two reasons.</p><p>First, stopPropagation() does nothing if it is called in the default phase. The first component to handle the event in the default phase could call stopPropagation() and all other components would still get a chance to handle the event.</p><p>Second, if stopPropagation() is called during the bubble or capture phases of an application event, the propagation stops just as expected. <em>However</em>, the default phase still executes — with one big difference: the component that called stopPropagation() will now be treated as the root for the default phase and only that component along with all its descendants will get to handle the event.</p><h3>Communicating with Child Components</h3><p>Although this article is about events, it’s important to talk about how parent components communicate with child components as events are all about communicating between components. We’ve learned so far that component events are the method of choice for sending events that should be handled in the containment hierarchy. We’ve also learned that application events should be avoided unless the event is genuinely an application-level event that all components might need to hear about. So how does a parent component send a message to a child component?</p><h4>Sending Data through Attributes</h4><p>The simplest method is to pass data to child components through attributes. Suppose you have a child component that looks like this:</p><pre>&lt;aura:component&gt;<br>   &lt;aura:attribute name=&quot;fullName&quot; type=&quot;String&quot;/&gt; <br>&lt;/aura:component&gt;</pre><p>The component or application that includes this component can control the value of the attribute in the following way:</p><pre>&lt;aura:application&gt;<br>   &lt;aura:attribute name=&quot;selectedName&quot; type=&quot;String&quot;/&gt; <br>   &lt;c:ChildComponent <strong>fullName=&quot;{!v.selectedName}&quot;</strong>/&gt;<br>&lt;/aura:application&gt;</pre><p>Notice how the attribute in the child is set to the value of an attribute on the parent. This value is bound to the child attribute <em>by reference</em>, which means that any time the parent sets a new value in the selectedName attribute, the fullName attribute in the child component is updated too. Conversely, any time the child updates the value of fullName, the value in the parent is updated as well.</p><h4>Defining methods on child components</h4><p>The more powerful way of having parents communicate with child components is through defining methods on the child that can accessed by the parent. A method in a child component is defined using something like the following:</p><pre>&lt;aura:method <strong>name=&quot;renderAccounts&quot;</strong> action=&quot;{!c.renderAccounts}&quot;<br>    description=&quot;Take a list of accounts and render them&quot;&gt;<br>  &lt;aura:attribute name=&quot;accounts&quot; type=&quot;Account[]&quot;/&gt;<br>  &lt;aura:attribute name=&quot;searchTerm&quot; type=&quot;String&quot; /&gt;<br>&lt;/aura:method&gt;</pre><p>As you might guess, the method will require an associated renderAccounts function in the controller.</p><p>The parent component, in order to call this method, will have to first obtain a reference to the child component and then call the method on it using something like the following:</p><pre>var childCmp = component.find(&#39;cmpResults&#39;);<br><strong>childCmp.renderAccounts</strong>(accounts, searchTerm);</pre><p>You can use aura:methods to create something of an API that allows parents to communicate with the child.</p><p>Component events, application events and component methods provide us with a comprehensive framework for creating reusable and decoupled lightning components.</p><h3>Summary</h3><p>Component events together with methods provide a great way for closely-related components to interact with each other and should be the methods of choice for communication between components. Application events give us a way to create “broadcast” style events which should be used to create events that any component in the application might need access to.</p><p>For further reading, check out the <a href="https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_intro.htm">official developer documentation for events</a> and the <a href="https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cmp_methods.htm">docs for creating methods in components</a>. Also, here’s another <a href="https://developer.salesforce.com/blogs/developer-relations/2017/04/lightning-inter-component-communication-patterns.html">great article about communication patterns in lightning applications</a>.</p><p>Thank you for reading, and if you enjoyed it please do let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3f090036cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/salesforce-zolo/demystifying-application-and-component-events-in-the-lightning-component-framework-fd3f090036cb">Demystifying Application and Component Events in the Lightning Component Framework</a> was originally published in <a href="https://medium.com/salesforce-zolo">Salesforce Zolo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>