<?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 Hrishikesh Wagh on Medium]]></title>
        <description><![CDATA[Stories by Hrishikesh Wagh on Medium]]></description>
        <link>https://medium.com/@hrishikeshwagh2001?source=rss-fa7160d22626------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BZYaHE6oFez2jhDA</url>
            <title>Stories by Hrishikesh Wagh on Medium</title>
            <link>https://medium.com/@hrishikeshwagh2001?source=rss-fa7160d22626------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 04:32:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hrishikeshwagh2001/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[You Can’t Deploy That Callout Without Testing It — Here’s How to Do It Right]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/you-cant-deploy-that-callout-without-testing-it-here-s-how-to-do-it-right-20cf02218bc8?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/20cf02218bc8</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[callout]]></category>
            <category><![CDATA[test-class]]></category>
            <category><![CDATA[apex]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 09:10:32 GMT</pubDate>
            <atom:updated>2026-06-22T09:10:32.864Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4fci_sJdtextanZr0OPEw.png" /></figure><p><em>A practical guide to mocking HTTP callouts in Salesforce Apex, with real code, real scenarios, and zero production surprises.</em></p><p>Imagine this: you’ve spent two days building a slick Apex integration that calls an external REST API — maybe it’s syncing contacts to a marketing platform, or pulling invoice data from an ERP. Everything works beautifully in your scratch org. You hit <strong>Run All Tests</strong> before pushing to production and…</p><pre>System.CalloutException: You have uncommitted work pending. <br>Please commit or rollback before calling out.</pre><p>Or worse — all your tests just skip the callout logic entirely because you never mocked it.</p><p>If you’ve been in Salesforce development for more than a few months, you’ve met this wall. And the solution isn’t to wrap your callout in a try-catch and hope for the best. The solution is <strong>mock testing</strong> — and once you understand it, you’ll never fear deploying an integration again.</p><p>Let’s dig in.</p><h3>Why You Can’t Just “Test” a Callout Normally</h3><p>Salesforce has a hard rule: <strong>Apex tests cannot make real HTTP callouts</strong>. Period.</p><p>This is actually a good thing. Think about it — if your test suite fired real API calls every time someone ran tests, you’d be:</p><ul><li>Hitting rate limits on external APIs</li><li>Polluting production data in third-party systems</li><li>Making your test suite dependent on external uptime</li><li>Potentially racking up API costs</li></ul><p>So Salesforce forces you to simulate the HTTP response. You tell the test environment: <em>“When this code tries to make an HTTP call, return THIS fake response instead.”</em></p><p>That’s mocking. And Salesforce gives you two clean ways to do it.</p><h3>The Foundation: HttpCalloutMock Interface</h3><p>Before we look at the two approaches, let’s understand the backbone of everything — the HttpCalloutMock interface.</p><p>apex</p><pre>public interface HttpCalloutMock {<br>    HTTPResponse respond(HTTPRequest req);<br>}</pre><p>Any class that implements this interface becomes a <strong>mock responder</strong>. When you register it using Test.setMock(), Salesforce intercepts every outgoing HTTP request during that test and routes it through your respond() method instead of actually hitting the internet.</p><p>Think of it like this — your callout class asks the internet a question, but your mock intercepts the question and hands back a pre-written answer. The calling code has no idea anything unusual happened.</p><h3>Approach 1: Implementing HttpCalloutMock Directly in Apex</h3><p>This is the most common and flexible approach. You write a dedicated Apex class that implements HttpCalloutMock and returns a crafted HttpResponse.</p><h3>Real-World Scenario</h3><p>Let’s say you’re integrating with a weather API to fetch temperature data based on a city name, and you store the result on a custom object Weather_Report__c.</p><h3>Step 1: Your Callout Service Class</h3><p>apex</p><pre>public class WeatherService {<br>public static String getWeatherData(String city) {<br>        HttpRequest req = new HttpRequest();<br>        req.setEndpoint(&#39;https://api.weatherprovider.com/v1/current?city=&#39; + city);<br>        req.setMethod(&#39;GET&#39;);<br>        req.setHeader(&#39;Authorization&#39;, &#39;Bearer &#39; + getApiKey());<br>        req.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>        req.setTimeout(10000);<br>        Http http = new Http();<br>        HttpResponse res = http.send(req);<br>        if (res.getStatusCode() == 200) {<br>            return res.getBody();<br>        } else {<br>            throw new WeatherServiceException(<br>                &#39;API call failed with status: &#39; + res.getStatusCode()<br>            );<br>        }<br>    }<br>    private static String getApiKey() {<br>        // Fetch from Custom Metadata or Named Credential<br>        return &#39;your-api-key-here&#39;;<br>    }<br>    public class WeatherServiceException extends Exception {}<br>}</pre><h3>Step 2: Create the Mock Class</h3><p>apex</p><pre>@isTest<br>public class WeatherServiceMock implements HttpCalloutMock {<br>private Integer statusCode;<br>    private String body;<br>    // Constructor to control what the mock returns<br>    public WeatherServiceMock(Integer statusCode, String body) {<br>        this.statusCode = statusCode;<br>        this.body = body;<br>    }<br>    public HTTPResponse respond(HTTPRequest req) {<br>        // You can validate the request here too!<br>        System.assertEquals(<br>            &#39;GET&#39;, <br>            req.getMethod(), <br>            &#39;Expected a GET request&#39;<br>        );<br>        System.assert(<br>            req.getEndpoint().contains(&#39;weatherprovider.com&#39;), <br>            &#39;Unexpected endpoint called&#39;<br>        );<br>        HttpResponse res = new HttpResponse();<br>        res.setStatusCode(this.statusCode);<br>        res.setBody(this.body);<br>        res.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>        return res;<br>    }<br>}</pre><h3>Step 3: Write the Test Class</h3><p>apex</p><pre>@isTest<br>private class WeatherServiceTest {<br>static String successBody = JSON.serialize(new Map&lt;String, Object&gt;{<br>        &#39;city&#39; =&gt; &#39;Pune&#39;,<br>        &#39;temperature&#39; =&gt; 32,<br>        &#39;unit&#39; =&gt; &#39;Celsius&#39;,<br>        &#39;condition&#39; =&gt; &#39;Partly Cloudy&#39;<br>    });<br>    @isTest<br>    static void testGetWeatherData_Success() {<br>        // Arrange: Set up the mock<br>        WeatherServiceMock mock = new WeatherServiceMock(200, successBody);<br>        Test.setMock(HttpCalloutMock.class, mock);<br>        // Act: Call the method<br>        Test.startTest();<br>        String result = WeatherService.getWeatherData(&#39;Pune&#39;);<br>        Test.stopTest();<br>        // Assert: Verify response<br>        System.assertNotEquals(null, result, &#39;Response body should not be null&#39;);<br>        <br>        Map&lt;String, Object&gt; parsed = <br>            (Map&lt;String, Object&gt;) JSON.deserializeUntyped(result);<br>        System.assertEquals(&#39;Pune&#39;, parsed.get(&#39;city&#39;));<br>        System.assertEquals(32, (Integer) parsed.get(&#39;temperature&#39;));<br>    }<br>    @isTest<br>    static void testGetWeatherData_APIError() {<br>        // Arrange: Simulate a 500 error<br>        WeatherServiceMock mock = new WeatherServiceMock(<br>            500, <br>            &#39;{&quot;error&quot;: &quot;Internal Server Error&quot;}&#39;<br>        );<br>        Test.setMock(HttpCalloutMock.class, mock);<br>        // Act &amp; Assert: Expect exception<br>        Test.startTest();<br>        try {<br>            WeatherService.getWeatherData(&#39;Pune&#39;);<br>            System.assert(false, &#39;Should have thrown an exception&#39;);<br>        } catch (WeatherService.WeatherServiceException e) {<br>            System.assert(<br>                e.getMessage().contains(&#39;500&#39;), <br>                &#39;Exception message should include status code&#39;<br>            );<br>        }<br>        Test.stopTest();<br>    }<br>}</pre><p>Notice a few things:</p><ul><li><strong>Test.setMock(HttpCalloutMock.class, mock)</strong> — this is the critical registration step. Without this line, your callout will fail at runtime in the test.</li><li><strong>Test.startTest() / </strong><strong>Test.stopTest()</strong> — always wrap your callout call here. This resets governor limits and ensures async operations complete.</li><li><strong>You’re testing both the happy path AND the error path</strong> — that’s non-negotiable in good test coverage.</li></ul><h3>Approach 2: Using a Static Resource File</h3><p>Sometimes the JSON response from an API is massive — hundreds of fields, nested arrays, complex structures. Embedding that in an Apex string is a maintenance nightmare. That’s where <strong>Static Resources</strong> shine.</p><h3>When to Use This Approach</h3><ul><li>Large, complex JSON or XML response bodies</li><li>You want to version-control API response samples separately</li><li>Your QA team or API documentation provides sample response files</li><li>You’re testing response parsing logic heavily</li></ul><h3>Step 1: Create the Static Resource</h3><ol><li>Go to <strong>Setup → Static Resources → New</strong></li><li>Name it something meaningful: WeatherApiResponse</li><li>Set <strong>Cache Control</strong> to Public</li><li>Upload a .json file (or .txt file with JSON content):</li></ol><p>json</p><pre>{<br>    &quot;city&quot;: &quot;Pune&quot;,<br>    &quot;temperature&quot;: 32,<br>    &quot;unit&quot;: &quot;Celsius&quot;,<br>    &quot;condition&quot;: &quot;Partly Cloudy&quot;,<br>    &quot;humidity&quot;: 68,<br>    &quot;wind_speed&quot;: 14,<br>    &quot;forecast&quot;: [<br>        { &quot;day&quot;: &quot;Monday&quot;, &quot;high&quot;: 34, &quot;low&quot;: 26 },<br>        { &quot;day&quot;: &quot;Tuesday&quot;, &quot;high&quot;: 33, &quot;low&quot;: 25 },<br>        { &quot;day&quot;: &quot;Wednesday&quot;, &quot;high&quot;: 31, &quot;low&quot;: 24 }<br>    ]<br>}</pre><h3>Step 2: Create the Static Resource Mock</h3><p>apex</p><pre>@isTest<br>public class StaticResourceMock implements HttpCalloutMock {<br>private String staticResourceName;<br>    private Integer statusCode;<br>    public StaticResourceMock(String staticResourceName, Integer statusCode) {<br>        this.staticResourceName = staticResourceName;<br>        this.statusCode = statusCode;<br>    }<br>    public HTTPResponse respond(HTTPRequest req) {<br>        // Load the body from Static Resource<br>        StaticResource sr = [<br>            SELECT Body <br>            FROM StaticResource <br>            WHERE Name = :staticResourceName <br>            LIMIT 1<br>        ];<br>        HttpResponse res = new HttpResponse();<br>        res.setStatusCode(this.statusCode);<br>        res.setBody(sr.Body.toString());<br>        res.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);<br>        return res;<br>    }<br>}</pre><h3>Step 3: Test Using the Static Resource Mock</h3><p>apex</p><pre>@isTest<br>private class WeatherServiceStaticResourceTest {<br>@isTest<br>    static void testGetWeatherData_WithStaticResource() {<br>        // Arrange<br>        StaticResourceMock mock = new StaticResourceMock(&#39;WeatherApiResponse&#39;, 200);<br>        Test.setMock(HttpCalloutMock.class, mock);<br>        // Act<br>        Test.startTest();<br>        String result = WeatherService.getWeatherData(&#39;Pune&#39;);<br>        Test.stopTest();<br>        // Assert: Parse and verify the rich response<br>        Map&lt;String, Object&gt; parsed = <br>            (Map&lt;String, Object&gt;) JSON.deserializeUntyped(result);<br>        System.assertEquals(&#39;Pune&#39;, parsed.get(&#39;city&#39;));<br>        System.assertEquals(32, (Integer) parsed.get(&#39;temperature&#39;));<br>        <br>        List&lt;Object&gt; forecast = (List&lt;Object&gt;) parsed.get(&#39;forecast&#39;);<br>        System.assertEquals(3, forecast.size(), &#39;Should have 3 forecast days&#39;);<br>    }<br>}</pre><p>The advantage here is obvious — your test stays lean and readable, while the actual response data lives in a properly structured file that can be updated independently.</p><h3>Salesforce’s Built-In: MultiStaticResourceCalloutMock and StaticResourceCalloutMock</h3><p>Salesforce also ships two out-of-the-box utility classes that you can use without writing your own mock class.</p><h3>StaticResourceCalloutMock</h3><p>apex</p><pre>@isTest<br>static void testWithBuiltInStaticMock() {<br>    StaticResourceCalloutMock mock = new StaticResourceCalloutMock();<br>    mock.setStaticResource(&#39;WeatherApiResponse&#39;);<br>    mock.setStatusCode(200);<br>    mock.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);</pre><pre>    Test.setMock(HttpCalloutMock.class, mock);</pre><pre>    Test.startTest();<br>    String result = WeatherService.getWeatherData(&#39;Pune&#39;);<br>    Test.stopTest();</pre><pre>    System.assertNotEquals(null, result);<br>}</pre><h3>MultiStaticResourceCalloutMock</h3><p>When your code makes <strong>multiple callouts to different endpoints</strong> in a single transaction, you need this class. It lets you map specific endpoints to specific static resources.</p><p>apex</p><pre>@isTest<br>static void testMultipleCallouts() {<br>    MultiStaticResourceCalloutMock multiMock = new MultiStaticResourceCalloutMock();<br>    <br>    // Map each endpoint URL to a different static resource<br>    multiMock.setStaticResource(<br>        &#39;https://api.weatherprovider.com/v1/current?city=Pune&#39;, <br>        &#39;WeatherApiResponse&#39;<br>    );<br>    multiMock.setStaticResource(<br>        &#39;https://api.weatherprovider.com/v1/forecast?city=Pune&#39;, <br>        &#39;WeatherForecastResponse&#39;<br>    );<br>    multiMock.setStatusCode(200);<br>    multiMock.setHeader(&#39;Content-Type&#39;, &#39;application/json&#39;);</pre><pre>    Test.setMock(HttpCalloutMock.class, multiMock);</pre><pre>    Test.startTest();<br>    // Call code that internally hits both endpoints<br>    WeatherService.getFullWeatherReport(&#39;Pune&#39;);<br>    Test.stopTest();</pre><pre>    // Your assertions here<br>}</pre><p>This is incredibly useful for orchestration services that fan out to multiple third-party endpoints in one Apex transaction.</p><h3>Quick Comparison: Which Approach to Use When?</h3><p>ScenarioRecommended ApproachSimple JSON response (under ~30 fields)Custom HttpCalloutMock classLarge or complex response payloadStaticResourceCalloutMock + Static Resource fileMultiple endpoints in one transactionMultiStaticResourceCalloutMockNeed to validate request parameters in the mockCustom HttpCalloutMock classResponse changes frequently or maintained by non-developersStatic Resource fileTesting both success and error pathsCustom HttpCalloutMock with constructor params</p><h3>Common Mistakes That’ll Cost You Time</h3><p><strong>1. Forgetting </strong><strong>Test.setMock() entirely</strong></p><p>Your test will throw System.CalloutException: You have uncommitted work pending or simply fail with a callout attempt error. Always register your mock before the callout.</p><p><strong>2. Calling the method outside </strong><strong>Test.startTest() / </strong><strong>Test.stopTest()</strong></p><p>Technically it works, but governor limits aren’t reset and async flows won’t complete correctly. Make it a habit to always wrap callout calls between these.</p><p><strong>3. Testing only the 200 path</strong></p><p>Real-world APIs fail. They return 400s, 401s, 429s, and 503s. Your code needs to handle them, and your tests need to verify that handling. Write a test for each failure scenario your code branches on.</p><p><strong>4. Hardcoding JSON in the mock but not updating it when the API changes</strong></p><p>This is a silent killer. The API schema evolves, your hardcoded JSON doesn’t, your tests still pass, but your production integration is broken. If the API is under active development, prefer Static Resources — they’re easier to update.</p><p><strong>5. Not asserting anything about the request inside the mock</strong></p><p>Your respond() method receives the HTTPRequest object. Use it! Validate that the endpoint, method, headers, and body are exactly what you expect. This turns your mock into a contract validator.</p><h3>The Real Importance of Testing Callouts</h3><p>Here’s the honest truth — skipping callout testing doesn’t just affect your code quality. It affects:</p><p><strong>Deployability</strong>: Salesforce requires 75% code coverage to deploy to production. If your callout methods aren’t covered by tests, you’re blocked.</p><p><strong>Reliability</strong>: An untested integration is a liability. When the production incident happens at 2 AM, you want tests that tell you exactly which edge case broke.</p><p><strong>Collaboration</strong>: When another developer touches your integration code, proper tests communicate intent. The mock response <em>is</em> the documentation of what the API returns.</p><p><strong>Refactoring confidence</strong>: Need to change how you parse the response? If the test is thorough, you’ll know immediately if your refactor breaks something.</p><p><strong>CI/CD readiness</strong>: Automated pipelines (Bitbucket Pipelines, GitHub Actions with SFDX) run your full test suite on every push. If callout tests are missing or flaky, your pipeline becomes untrustworthy.</p><h3>Wrapping Up</h3><p>Testing Apex callouts isn’t optional — it’s the professional standard. Once you internalize the pattern (implement HttpCalloutMock, register with Test.setMock(), wrap in Test.startTest()/stopTest()), it becomes second nature.</p><p>To recap what we covered:</p><ul><li><strong>Custom </strong><strong>HttpCalloutMock</strong> class gives you full control and is ideal for validating request details and simulating varied responses</li><li><strong>Static Resource files</strong> keep your test classes clean when payloads are large or frequently updated</li><li><strong>StaticResourceCalloutMock</strong> and <strong>MultiStaticResourceCalloutMock</strong> are Salesforce&#39;s built-in utilities for common scenarios</li><li>Always test both success and failure paths</li><li>Use the mock’s respond() method to validate requests, not just return responses</li></ul><p>The next time you’re building an integration, write your mock class alongside your service class — not after. Future you (and your teammates) will be grateful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20cf02218bc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Maps and Bulkification in Apex Triggers: A Practical Guide for Salesforce Developers]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/mastering-maps-and-bulkification-in-apex-triggers-a-practical-guide-for-salesforce-developers-e10c6d8fe38b?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/e10c6d8fe38b</guid>
            <category><![CDATA[governor-limit]]></category>
            <category><![CDATA[salesforce-apex]]></category>
            <category><![CDATA[trigger]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Fri, 22 May 2026 13:10:18 GMT</pubDate>
            <atom:updated>2026-05-22T13:10:18.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9XvcdpVWqYuVjRj6vw_VA.png" /></figure><p>Salesforce triggers are one of the most powerful parts of Apex development, but they are also one of the most common reasons behind governor limit exceptions and performance issues.</p><p>A major difference between beginner and experienced Salesforce developers is the ability to write:</p><ul><li>Bulkified triggers</li><li>Efficient SOQL queries</li><li>Optimized Map-based logic</li><li>Scalable trigger architectures</li></ul><p>In this blog, we will understand:</p><ol><li>Why bulkification matters</li><li>Why Maps are essential in triggers</li><li>Common mistakes developers make</li><li>Real-world trigger patterns</li><li>Trigger best practices used in enterprise projects</li></ol><h3>Understanding Bulkification</h3><p>In Salesforce, a trigger does not execute for a single record only.</p><p>A single trigger execution may process:</p><ul><li>1 record</li><li>10 records</li><li>200 records</li><li>Thousands of records through batches or integrations</li></ul><p>For example:</p><ul><li>Data Loader</li><li>API integrations</li><li>Flow updates</li><li>Batch Apex</li><li>Mass inline edits</li></ul><p>All can invoke triggers in bulk.</p><p>This is why Salesforce imposes governor limits.</p><p>Some important limits are:</p><p>LimitValueSOQL Queries100DML Statements150CPU TimeLimitedHeap SizeLimited</p><p>If your trigger is not bulkified, it will fail in production.</p><h3>The Most Common Beginner Mistake</h3><h3>SOQL Inside a Loop</h3><pre>trigger BadTrigger on Contact(after insert){<br>for(Contact con : Trigger.new){<br>        Account acc = [<br>            SELECT Id, Name<br>            FROM Account<br>            WHERE Id = :con.AccountId<br>        ];<br>        acc.Description = &#39;Updated&#39;;<br>        update acc;<br>    }<br>}</pre><h3>Why This Is Bad</h3><p>If 200 Contacts are inserted:</p><ul><li>200 SOQL queries executed</li><li>200 DML statements executed</li></ul><p>This immediately hits governor limits.</p><h3>The Correct Bulkified Approach</h3><p>The proper approach is:</p><ol><li>Collect IDs</li><li>Query once</li><li>Store records in a Map</li><li>Process records</li><li>Perform one DML operation</li></ol><h3>Why Maps Are So Important</h3><p>A Map stores data as key-value pairs.</p><pre>Map&lt;Id, Account&gt; accMap;</pre><p>KeyValueAccount IdAccount Record</p><p>Maps provide extremely fast lookup access.</p><p>Instead of looping through records repeatedly, we can directly retrieve records using .get().</p><h3>Real-World Bulkified Example</h3><h3>Scenario</h3><p>Whenever a Contact is inserted, update the parent Account Description.</p><h3>Optimized Solution</h3><pre>trigger ContactTrigger on Contact(after insert){<br>Set&lt;Id&gt; accountIds = new Set&lt;Id&gt;();<br>    for(Contact con : Trigger.new){<br>        if(con.AccountId != null){<br>            accountIds.add(con.AccountId);<br>        }<br>    }<br>    Map&lt;Id, Account&gt; accMap = new Map&lt;Id, Account&gt;(<br>        [SELECT Id, Description<br>         FROM Account<br>         WHERE Id IN :accountIds]<br>    );<br>    for(Contact con : Trigger.new){<br>        Account acc = accMap.get(con.AccountId);<br>        if(acc != null){<br>            acc.Description = &#39;Contact Added&#39;;<br>        }<br>    }<br>    update accMap.values();<br>}</pre><h3>Understanding the Flow</h3><h3>Step 1 — Collect IDs</h3><pre>Set&lt;Id&gt; accountIds = new Set&lt;Id&gt;();</pre><p>We gather all Account IDs first.</p><h3>Step 2 — Query Once</h3><pre>Map&lt;Id, Account&gt; accMap</pre><p>We query all Accounts in a single SOQL query.</p><h3>Step 3 — Fast Retrieval Using Map</h3><pre>Account acc = accMap.get(con.AccountId);</pre><p>This is the most important line.</p><p>Instead of looping through Accounts repeatedly, the Map gives direct access.</p><h3>Trigger.oldMap and Trigger.newMap</h3><p>Salesforce automatically provides maps during update and delete operations.</p><p>These are heavily used in enterprise projects.</p><h3>Detecting Field Changes</h3><h3>Scenario</h3><p>Create a Task only when Opportunity stage changes to Closed Won.</p><pre>for(Opportunity opp : Trigger.new){<br>Opportunity oldOpp = Trigger.oldMap.get(opp.Id);<br>    if(opp.StageName == &#39;Closed Won&#39; &amp;&amp;<br>       oldOpp.StageName != &#39;Closed Won&#39;){<br>        // logic here<br>    }<br>}</pre><h3>Why Trigger.oldMap Is Powerful</h3><p>Without oldMap, you cannot compare previous and current values efficiently.</p><p>This pattern is extremely common in interviews.</p><h3>Composite Key Pattern</h3><p>One of the most useful advanced Map patterns is the composite key.</p><h3>Scenario</h3><p>Prevent duplicate Contacts with same Email under the same Account.</p><h3>Example</h3><pre>String key = con.AccountId + &#39;-&#39; + con.Email;</pre><p>Store it inside:</p><pre>Map&lt;String, Contact&gt;</pre><p>This allows uniqueness checks across multiple fields.</p><h3>Aggregate Result with Maps</h3><h3>Scenario</h3><p>Update Account with total Opportunity Amount.</p><pre>Map&lt;Id, Decimal&gt; totalAmountMap = new Map&lt;Id, Decimal&gt;();<br>for(AggregateResult ar : [<br>    SELECT AccountId accId,<br>           SUM(Amount) total<br>    FROM Opportunity<br>    GROUP BY AccountId<br>]){<br>    totalAmountMap.put(<br>        (Id) ar.get(&#39;accId&#39;),<br>        (Decimal) ar.get(&#39;total&#39;)<br>    );<br>}</pre><p>This is one of the most frequently used enterprise trigger patterns.</p><h3>Trigger Best Practices</h3><h3>1. One Trigger Per Object</h3><p>Avoid multiple triggers on the same object.</p><p>Good:</p><pre>AccountTrigger</pre><p>Bad:</p><pre>AccountTrigger1<br>AccountValidationTrigger<br>AccountUpdateTrigger</pre><h3>2. Keep Logic Out of Trigger</h3><p>Triggers should delegate logic to handler classes.</p><p>Good trigger:</p><pre>trigger AccountTrigger on Account(before insert, before update){<br>AccountTriggerHandler.handle(Trigger.new);<br>}</pre><h3>3. Never Use SOQL Inside Loops</h3><p>Bad:</p><pre>for(Account acc : Trigger.new){<br>[SELECT Id FROM Contact];<br>}</pre><h3>4. Never Use DML Inside Loops</h3><p>Bad:</p><pre>for(Account acc : accounts){<br>    update acc;<br>}</pre><p>Good:</p><pre>update accounts;</pre><h3>5. Use Sets for Unique IDs</h3><pre>Set&lt;Id&gt; accountIds = new Set&lt;Id&gt;();</pre><p>Sets automatically prevent duplicates.</p><h3>6. Use Maps for Fast Lookup</h3><pre>Map&lt;Id, Account&gt; accMap</pre><p>This is fundamental for scalable trigger development.</p><h3>7. Handle Null Values Properly</h3><p>Always check for nulls.</p><pre>if(con.AccountId != null)</pre><h3>8. Avoid Recursive Trigger Execution</h3><p>Use static variables when needed.</p><pre>public static Boolean isRunning = false;</pre><h3>Enterprise Trigger Pattern</h3><p>Most enterprise projects follow this structure:</p><pre>Trigger<br>   ↓<br>Handler Class<br>   ↓<br>Service Class<br>   ↓<br>Utility Class</pre><p>This improves:</p><ul><li>Maintainability</li><li>Testability</li><li>Scalability</li><li>Reusability</li></ul><h3>Mental Framework for Trigger Questions</h3><p>Whenever you see a trigger scenario, think in this order:</p><h3>Step 1</h3><p>Which IDs do I need?</p><h3>Step 2</h3><p>Can I collect them into a Set?</p><h3>Step 3</h3><p>Can I query all records at once?</p><h3>Step 4</h3><p>Should I store them in a Map?</p><h3>Step 5</h3><p>Can I perform one DML instead of many?</p><p>If you follow this framework consistently, most trigger questions become manageable.</p><h3>Final Thoughts</h3><p>Maps and bulkification are not advanced Apex concepts anymore — they are mandatory skills for Salesforce developers.</p><p>Most trigger failures in production happen because developers:</p><ul><li>Use SOQL inside loops</li><li>Use DML inside loops</li><li>Ignore bulk operations</li><li>Avoid Maps due to confusion</li></ul><p>The moment you become comfortable with Maps, your trigger logic becomes:</p><ul><li>Cleaner</li><li>Faster</li><li>More scalable</li><li>More interview-ready</li></ul><p>For Salesforce interviews, mastering Maps is one of the highest ROI skills you can develop.</p><p>Because ultimately, Apex trigger development is less about syntax and more about data handling patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e10c6d8fe38b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a Custom LWC Component Inside a Salesforce Screen Flow]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/using-a-custom-lwc-component-inside-a-salesforce-screen-flow-cd3a69dc7e7c?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd3a69dc7e7c</guid>
            <category><![CDATA[screenflow]]></category>
            <category><![CDATA[flow]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[lwc]]></category>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Fri, 08 May 2026 08:24:43 GMT</pubDate>
            <atom:updated>2026-05-08T08:37:09.911Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*59emDUztLeE7dpFrRZTFQg.png" /></figure><p>Salesforce Screen Flows provide a powerful way to create guided user experiences with minimal code. However, there are scenarios where standard Flow components are not enough — especially when you need advanced UI behavior, reusable functionality, or dynamic field handling.</p><p>One of the most effective approaches is embedding a custom Lightning Web Component (LWC) directly inside a Screen Flow.</p><p>In this article, we will walk through how to create and use a reusable custom LWC inside a Screen Flow using a configurable Dual Listbox component as an example.</p><h3>Why Use an LWC in Screen Flow?</h3><p>Standard Flow components work well for basic use cases, but custom LWCs help when you need:</p><ul><li>Dynamic field rendering</li><li>Advanced validations</li><li>Better UI/UX</li><li>Reusable business logic</li><li>Real-time interactivity</li><li>Integration with Apex logic</li></ul><p>Using LWCs inside Flow also helps reduce duplicate Flow logic and keeps the implementation scalable.</p><h3>Use Case Example</h3><p>Suppose your organization has a multi-select picklist field such as:</p><ul><li>Skills</li><li>Certifications</li><li>Interests</li><li>Member Categories</li></ul><p>Instead of creating separate Flow logic for every field, you can build a reusable Dual Listbox component that:</p><ul><li>Dynamically loads picklist values</li><li>Accepts object and field API names from Flow</li><li>Pre-populates existing values</li><li>Returns selected values back to Flow</li><li>Supports validation and help text</li></ul><h3>Step 1: Create the Lightning Web Component</h3><p>The component consists of:</p><ul><li>HTML template</li><li>JavaScript controller</li><li>XML configuration file</li></ul><p>The component communicates with Flow using @api properties.</p><h3>Sample HTML Structure</h3><p>The UI contains:</p><ul><li>Loading spinner</li><li>Error handling section</li><li>Lightning Dual Listbox</li></ul><pre>&lt;template&gt;<br>    &lt;template if:true={isLoading}&gt;<br>        &lt;lightning-spinner&gt;&lt;/lightning-spinner&gt;<br>    &lt;/template&gt;<br>    &lt;template if:true={hasError}&gt;<br>        &lt;div class=&quot;error-message&quot;&gt;<br>            {errorMessage}<br>        &lt;/div&gt;<br>    &lt;/template&gt;<br>    &lt;lightning-dual-listbox<br>        name=&quot;dynamicDualListbox&quot;<br>        label={resolvedLabel}<br>        options={options}<br>        value={selectedItems}<br>        onchange={handleChange}&gt;<br>    &lt;/lightning-dual-listbox&gt;<br>&lt;/template&gt;</pre><h3>Step 2: Expose the Component to Flow</h3><p>To make an LWC available inside Screen Flow, the component must be exposed using the XML configuration file.</p><p>Example configuration:</p><pre>&lt;targets&gt;<br>    &lt;target&gt;lightning__FlowScreen&lt;/target&gt;<br>&lt;/targets&gt;</pre><p>This tells Salesforce that the component can be used inside Flow Screens.</p><p>You can also define configurable Flow properties such as:</p><ul><li>Object API Name</li><li>Field API Name</li><li>Current Values</li><li>Output Values</li><li>Help Text</li><li>Required Flag</li></ul><p>These properties become configurable directly from the Flow Builder UI.</p><h3>Step 3: Add Configurable Flow Properties</h3><p>A reusable component should never hardcode object or field names.</p><p>Instead, expose configurable properties like:</p><pre>&lt;property<br>    name=&quot;objectApiName&quot;<br>    type=&quot;String&quot;<br>    label=&quot;Object API Name&quot;<br>/&gt;<br>&lt;property<br>    name=&quot;fieldApiName&quot;<br>    type=&quot;String&quot;<br>    label=&quot;Field API Name&quot;<br>/&gt;</pre><p>This makes the component reusable across multiple objects and flows.</p><h3>Step 4: Load Picklist Values Dynamically</h3><p>The component can call an Apex method to fetch picklist values dynamically based on:</p><ul><li>Object API Name</li><li>Field API Name</li></ul><p>This keeps the solution generic and scalable.</p><p>The JavaScript controller handles:</p><ul><li>Data loading</li><li>Error handling</li><li>Pre-populating selected values</li><li>Flow output updates</li></ul><h3>Step 5: Handle Flow Validation</h3><p>Custom Flow components can also implement Flow validation.</p><p>Example:</p><pre>@api<br>validate() {<br>    if (this.required &amp;&amp; this.selectedItems.length === 0) {<br>        return {<br>            isValid: false,<br>            errorMessage: &#39;Please select at least one value.&#39;<br>        };<br>    }<br>return { isValid: true };<br>}</pre><p>This prevents users from moving to the next Flow screen without making a required selection.</p><h3>Step 6: Add the Component to Screen Flow</h3><p>After deployment, the custom component becomes available inside the <strong>Custom Components</strong> section of the Screen Flow Builder.</p><p>The highlighted section below shows where custom LWCs appear inside the Flow Screen editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5l_5tv-rN7NQxVef" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*3k9KDtZC7bFd5N1C" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*xqJC7O0yUVTjwABp" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IufouHOPo-6wzF2U" /></figure><h3>Steps to Add the Component</h3><ol><li>Open the Flow Builder</li><li>Add a <strong>Screen</strong> element</li><li>Navigate to the <strong>Custom Components</strong> section</li><li>Drag and drop your custom LWC onto the screen</li><li>Configure the input/output properties</li><li>Connect Flow variables as needed</li></ol><h3>Recommended Best Practices</h3><h3>1. Make Components Reusable</h3><p>Avoid hardcoded logic. Use configurable properties wherever possible.</p><h3>2. Add Proper Error Handling</h3><p>Always display meaningful error messages to Flow users.</p><h3>3. Support Pre-Population</h3><p>If the Flow is editing existing records, pre-load current field values.</p><h3>4. Keep UI Responsive</h3><p>Use loading indicators while data is being fetched.</p><h3>5. Validate Before Navigation</h3><p>Use Flow validation methods to enforce business rules.</p><h3>Advantages of Using LWC in Screen Flows</h3><p>FeatureBenefitReusabilityOne component can work across multiple flowsBetter UIMore interactive experienceDynamic DataFetch values at runtimeValidation SupportPrevent invalid submissionsScalabilityEasier maintenance</p><h3>Final Thoughts</h3><p>Combining Lightning Web Components with Salesforce Screen Flows is one of the best ways to build modern, scalable, and user-friendly experiences on the Salesforce Platform.</p><p>Instead of relying solely on standard Flow components, custom LWCs allow developers to introduce:</p><ul><li>Advanced interactivity</li><li>Dynamic behavior</li><li>Reusable UI patterns</li><li>Cleaner Flow design</li></ul><p>For organizations working with complex business processes, this approach significantly improves maintainability and user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd3a69dc7e7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making Salesforce Flows More Reliable with Fault Paths (Real Use Case)]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/making-salesforce-flows-more-reliable-with-fault-paths-real-use-case-aa7ad3c9006d?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa7ad3c9006d</guid>
            <category><![CDATA[custom-errror]]></category>
            <category><![CDATA[fault-path]]></category>
            <category><![CDATA[salesforce-flow]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Mon, 13 Apr 2026 09:51:49 GMT</pubDate>
            <atom:updated>2026-04-13T09:51:49.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*InJHy_7qOFcaYkOAY_fnyg.png" /><figcaption>Cover Image</figcaption></figure><h3>Why I Started Using Fault Paths</h3><p>I’ll be honest — earlier, I used to build flows that worked perfectly… <em>until something went wrong</em>.</p><p>And when it did, users would see that classic:</p><blockquote>“An unhandled fault has occurred”</blockquote><p>Not helpful. Not user-friendly. And definitely not something you want in production.</p><p>So in one of my recent implementations, I decided to handle errors properly using <strong>Fault Paths</strong> — and it made a big difference.</p><h3>The Use Case (Simplified)</h3><p>Whenever a record is created or updated in a custom object (let’s call it <strong>Application Object</strong>), I had to:</p><ul><li>Check if a related <strong>Engagement</strong> record exists</li><li>If yes → update it</li><li>If no → create a new one</li></ul><p>Pretty standard automation.</p><h3>What Could Go Wrong?</h3><p>Even though the logic was simple, a lot could still fail:</p><ul><li>A validation rule blocks the update</li><li>A required field is missing</li><li>Some unexpected data issue</li><li>Or even a query fails</li></ul><p>Earlier, any of these would just break the flow and show a generic error.</p><h3>What I Changed</h3><p>This time, I added <strong>Fault Paths</strong> to every critical element:</p><ul><li>Get Records</li><li>Update Records</li><li>Create Records</li></ul><p>And instead of letting the flow crash, I used a <strong>Custom Error Element</strong> to show proper messages directly on the record page.</p><h3>The Game Changer: Custom Error Element</h3><p>This was the most important part.</p><p>Instead of:</p><ul><li>Breaking the flow</li><li>Showing technical logs</li></ul><p>We now:</p><ul><li>Show clean messages</li><li>Display them directly on the UI</li><li>Help users understand what went wrong</li></ul><p>And honestly, this reduced confusion <em>a lot</em>.</p><h3>How I Implemented It</h3><h3>1. Handling “Get Records” Failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/579/1*owtUoj6AD3ut2DP0427Igw.png" /><figcaption>fault path and custom error</figcaption></figure><p>If fetching the Engagement record fails, I redirect the fault path to a custom error.</p><p>Instead of a technical error, the user sees something like:</p><blockquote><em>“We couldn’t retrieve related data. Please try again or contact support.”</em></blockquote><h3>2. Handling “Update Records” Failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*0W1vDia3WA4IyJJsEeVfNg.png" /><figcaption>fault path and custom error</figcaption></figure><p>If the update fails (which usually happens due to validation rules), the user sees:</p><blockquote><em>“There was an issue updating the related record. Please check your inputs.”</em></blockquote><h3>3. Handling “Create Records” Failure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*1MWDaeGMD1_KxK_RBh1ZKA.png" /></figure><p>If record creation fails:</p><blockquote><em>“Unable to create the related record. Please try again later.”</em></blockquote><h3>The Small Change That Made a Big Difference</h3><p>Initially, I was just showing static messages like:</p><blockquote><em>“Something went wrong. Contact admin.”</em></blockquote><p>But that didn’t really help anyone. Then I started using this:</p><p><strong>$Flow.FaultMessage</strong></p><h3>Why $Flow.FaultMessage is Actually Useful</h3><p>It gives you the <strong>real error message</strong> that Salesforce throws. So instead of guessing the issue, you actually see it.</p><h3>Example</h3><p>In the Custom Error element, I used:</p><pre>Error while updating engagement: {!$Flow.FaultMessage}</pre><p>Now the user sees something like:</p><blockquote><em>“Error while updating engagement: Required fields are missing: Status”</em></blockquote><h3>What I Noticed After This</h3><ul><li>Users started understanding what went wrong</li><li>Many issues got resolved without coming to dev team</li><li>Debugging became much faster</li><li>Support tickets reduced (which is always a win 😄)</li></ul><h3>What I Learned</h3><p>A few things became very clear after this:</p><ul><li>Flows don’t just need to <strong>work</strong>, they need to <strong>fail gracefully</strong></li><li>Users just want clarity about things getting failed, the technical and non-technical details.</li><li>Adding fault paths takes a few extra minutes, but saves hours of debugging</li></ul><h3>Best Practices I Now Follow</h3><p>I <strong>always</strong> add fault paths for:</p><ul><li>Get Records</li><li>Create Records</li><li>Update Records</li></ul><p>I keep error messages:</p><ul><li>Simple</li><li>Non-technical/ Technical using Flow.FaultMessage</li><li>Actionable</li></ul><h3>Final Thought</h3><p>If you’re building flows and not using fault paths yet, you’re basically leaving error handling to chance.</p><p>Think of Fault Paths like a <strong>try-catch block in Apex</strong> — once you start using them properly, you won’t go back.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa7ad3c9006d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce OAuth Just Got an Upgrade: External Client App (Full Implementation Guide)]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/salesforce-oauth-just-got-an-upgrade-external-client-app-full-implementation-guide-8da2fae9b961?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/8da2fae9b961</guid>
            <category><![CDATA[external-client-app]]></category>
            <category><![CDATA[inbound-integration]]></category>
            <category><![CDATA[salesforce-integration]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[connected-apps]]></category>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 05:52:26 GMT</pubDate>
            <atom:updated>2026-03-31T05:54:43.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IU_EoaqYTBzzS-H9J7-0Ag.png" /></figure><p>If you’ve worked with Salesforce integrations before, chances are you’ve used <strong>Connected Apps</strong>.</p><p>Well… not anymore.</p><p>Salesforce has officially shifted towards <strong>External Client Apps</strong>, and if you’re building modern integrations in 2025, this is the way forward.</p><p>I recently implemented a <strong>Client Credentials OAuth flow</strong> using External Client Apps — and in this blog, I’ll walk you through the entire journey:</p><ul><li>Setting up the External Client App</li><li>Configuring OAuth (the right way)</li><li>Generating access tokens</li><li>Hitting Salesforce APIs</li><li>Testing everything using Postman</li></ul><p>Let’s get into it 👇</p><h3>Step 1: Creating the External Client App</h3><p>Head over to:</p><p>👉 <strong>Setup → App Manager → New External Client App</strong></p><p>This is your new “Connected App”.</p><h3>OAuth Configuration (This is where things matter)</h3><p>Once you enable OAuth, you’ll need to define scopes.</p><p>Here’s what I used (and why):</p><ul><li>api → To access Salesforce REST APIs</li><li>refresh_token → Future-proofing (even though not used in this flow)</li><li>openid → 🔥 Important — gives access to a <strong>unique user identifier</strong></li></ul><p>That openid scope is often skipped, but it’s becoming increasingly important in identity-aware integrations.</p><h3>Callback URL</h3><p>Even though we’re using <strong>Client Credentials Flow</strong>, Salesforce still asks for this.</p><p>I just used:</p><pre>https://localhost/callback</pre><h3>Step 2: OAuth Policies &amp; Flow Enablement</h3><p>This is where External Client Apps feel more structured (and slightly stricter).</p><h3>Enable Client Credentials Flow</h3><p>In the <strong>OAuth Flow settings</strong>, make sure you:</p><p>✔ Enable <strong>Client Credentials Flow</strong></p><p>Then define:</p><p>👉 <strong>Run As User</strong></p><p>Example:</p><pre>test.user@abc.com</pre><p>This is super important.</p><p>💡 Your entire API execution will run under this user’s permissions.</p><p>So if something fails later… this is the first place to check.</p><h3>Security Settings</h3><p>Here’s what I configured:</p><ul><li>✅ <strong>Enable Refresh Token Rotation</strong></li><li>✅ Relax IP restrictions</li><li>✅ Refresh token expiry → 365 days</li></ul><p>Even though refresh tokens aren’t used in this flow, enabling rotation is a <strong>good security practice</strong>.</p><h3>Step 3: Get Client ID &amp; Secret</h3><p>Once saved, Salesforce gives you:</p><ul><li>Client ID</li><li>Client Secret</li></ul><p>Keep these safe — this is basically your app’s identity.</p><h3>Step 4: Fetching the Access Token</h3><p>Now the fun part.</p><p>We hit Salesforce’s token endpoint:</p><pre>https://login.salesforce.com/services/oauth2/token</pre><p>(Use test.salesforce.com for sandbox) or add your Org Domain</p><h3>🧾 Request Details</h3><p><strong>Method:</strong> POST<br> <strong>Content-Type:</strong> application/x-www-form-urlencoded</p><p><strong>Body:</strong></p><pre>grant_type=client_credentials<br>client_id=YOUR_CLIENT_ID<br>client_secret=YOUR_CLIENT_SECRET</pre><h3>✅ Response</h3><p>You’ll get something like:</p><pre>{<br>  &quot;access_token&quot;: &quot;00Dxx0000001gPFEAY!...&quot;,<br>  &quot;instance_url&quot;: &quot;https://yourInstance.salesforce.com&quot;,<br>  &quot;token_type&quot;: &quot;Bearer&quot;<br>}</pre><p>And just like that — you’re authenticated 🎯</p><h3>Step 5: Setting It Up in Postman</h3><p>This is how I tested everything end-to-end.</p><h3>🔹 Token Request</h3><p>Create a POST request with:</p><ul><li>URL → /services/oauth2/token</li><li>Body → x-www-form-urlencoded</li></ul><p>Then add this script in the <strong>Tests tab</strong>:</p><pre>let res = pm.response.json();<br>pm.environment.set(&quot;access_token&quot;, res.access_token);<br>pm.environment.set(&quot;instance_url&quot;, res.instance_url);</pre><p>Now your token is stored automatically 🙌</p><h3>Step 6: Creating a Record via API</h3><p>Let’s create an Account.</p><h3>Endpoint</h3><pre>{{instance_url}}/services/data/v60.0/sobjects/Account/</pre><h3>Headers</h3><pre>Authorization: Bearer {{access_token}}<br>Content-Type: application/json</pre><h3>Body</h3><pre>{<br>  &quot;Name&quot;: &quot;Test Account from External Client App&quot;,<br>  &quot;Industry&quot;: &quot;Technology&quot;<br>}</pre><h3>✅ Response</h3><pre>{<br>  &quot;id&quot;: &quot;001xx000003DGbYAAW&quot;,<br>  &quot;success&quot;: true,<br>  &quot;errors&quot;: []<br>}</pre><p>Boom. Record created 🚀</p><h3>⚠️ Things That Might Trip You Up</h3><p>Let me save you a few hours of debugging:</p><h3>1. “Why am I getting insufficient access?”</h3><p>👉 Check the <strong>Run As User</strong></p><ul><li>Does the user have object permissions?</li><li>Field-level access?</li></ul><h3>2. “Where is my refresh token?”</h3><p>You won’t get one.</p><p>👉 Client Credentials Flow <strong>does not return refresh tokens, </strong>Just request a new access token when needed.</p><h3>3. “invalid_client error?”</h3><p>Usually means:</p><ul><li>Wrong client ID/secret</li><li>Flow not enabled</li></ul><h3>🧠 Final Flow (Simplified)</h3><pre>External Client App<br>      ↓<br>Client ID + Secret<br>      ↓<br>Token Request<br>      ↓<br>Access Token<br>      ↓<br>Salesforce API<br>      ↓<br>Data Created</pre><h3>🎯 Final Thoughts</h3><p>External Client Apps feel like Salesforce finally catching up with modern OAuth practices. Cleaner. More secure. More structured. And honestly — once you set it up once, it’s pretty smooth.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8da2fae9b961" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preserving Order While Synchronizing a Multi-Select Picklist with a Text Field in Salesforce]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/preserving-order-while-synchronizing-a-multi-select-picklist-with-a-text-field-in-salesforce-9ebd3bb17d4a?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ebd3bb17d4a</guid>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 11:54:16 GMT</pubDate>
            <atom:updated>2026-02-18T11:54:16.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Problem</h3><p>In a recent Salesforce implementation, we encountered an interesting data consistency issue involving two related fields on a standard object:</p><ul><li><strong>Field A</strong> → Multi-Select Picklist (source of truth)</li><li><strong>Field B</strong> → Text Area (formatted display version used for downstream processes like badge printing)</li></ul><p>The expectation was simple:</p><blockquote><em>Whenever Field A changes, Field B should reflect the same values in a user-friendly, formatted way.</em></blockquote><p>However, over time, inconsistencies started appearing:</p><ul><li>Field A populated but Field B was null</li><li>Field B populated but Field A was null</li><li>Values mismatching between both fields</li><li>Correct values but wrong order</li><li>Inconsistent behavior across user-created and system-updated records</li></ul><p>The issue became critical because Field B was used in an external-facing process.</p><h3>Initial Implementation</h3><p>Originally, the synchronization logic looked something like this:</p><pre>record.FieldB__c = <br>    String.isBlank(inputValue)<br>    ? null<br>    : inputValue.replace(&#39;;&#39;, &#39;, &#39;);</pre><h3>How It Worked</h3><ul><li>Salesforce stores multi-select picklists as semicolon-separated values: Value1;Value2;Value3</li><li>The logic simply replaced ; with , for display: Value1, Value2, Value3</li></ul><p>At first glance, this seemed correct.</p><h3>Why Issues Started Appearing</h3><p>After investigation, we identified several architectural gaps:</p><h3>Synchronization Was Not Centralized</h3><p>The logic only executed in specific Apex flows.<br> If records were updated through:</p><ul><li>Data imports</li><li>Admin edits</li><li>Background jobs</li><li>Automation</li><li>Integrations</li></ul><p>The synchronization logic did not always execute.</p><p>This caused stale or mismatched data.</p><h3>Entire Field Was Being Rebuilt</h3><p>The original logic completely overwrote Field B whenever Field A changed.</p><p>This introduced a more subtle problem:</p><ul><li>Any manually set ordering was lost</li><li>Custom formatting was overwritten</li><li>Existing sequence was rearranged</li></ul><p>For processes like badge printing, <strong>order matters</strong>.</p><h3>Multi-Select Picklists Do Not Guarantee Order</h3><p>Salesforce multi-select picklists:</p><ul><li>Store values as strings</li><li>Do not reliably preserve user selection order</li><li>May return values alphabetically depending on context</li></ul><p>This meant that simply regenerating Field B from Field A was insufficient when order had business meaning.</p><h3>Investigation Approach</h3><p>The investigation involved:</p><ol><li>Reviewing all user entry points</li><li>Checking Apex classes and automation</li><li>Verifying whether Field B was referenced anywhere else</li><li>Analyzing how updates were happening across different channels</li></ol><p>Key finding:</p><blockquote><em>Field B was only being assigned inside selective Apex logic and was not globally enforced.</em></blockquote><p>This explained the inconsistencies.</p><h3>The Solution</h3><p>Instead of rebuilding the text field entirely, we redesigned the synchronization logic with <strong>order preservation</strong> in mind.</p><h3>New Requirements</h3><p>When Field A changes:</p><ul><li>❌ Do NOT overwrite existing order</li><li>❌ Do NOT rebuild the entire string</li><li>✅ Remove only values removed from Field A</li><li>✅ Append newly added values at the end</li><li>✅ Preserve existing order</li><li>✅ Respect manual edits</li></ul><h3>Updated Trigger Approach</h3><p>The improved logic works as follows:</p><ol><li>Convert Field A (semicolon-separated) into a Set.</li><li>Convert existing Field B (comma-separated) into a List.</li><li>Remove only values no longer present in Field A.</li><li>Append newly added values to the end.</li><li>Reconstruct the string.</li></ol><p>Simplified version:</p><pre>trigger RecordSync on ObjectName (before insert, before update) {</pre><pre>for (ObjectName rec : Trigger.new) {</pre><pre>        if (Trigger.isUpdate &amp;&amp;<br>            rec.FieldA__c == Trigger.oldMap.get(rec.Id).FieldA__c) {<br>            continue;<br>        }</pre><pre>        Set&lt;String&gt; newValues = new Set&lt;String&gt;();<br>        if (!String.isBlank(rec.FieldA__c)) {<br>            newValues.addAll(rec.FieldA__c.split(&#39;;&#39;));<br>        }</pre><pre>        List&lt;String&gt; existingOrder = new List&lt;String&gt;();<br>        if (!String.isBlank(rec.FieldB__c)) {<br>            for (String val : rec.FieldB__c.split(&#39;,&#39;)) {<br>                existingOrder.add(val.trim());<br>            }<br>        }</pre><pre>        List&lt;String&gt; updatedOrder = new List&lt;String&gt;();</pre><pre>        // Preserve existing order<br>        for (String val : existingOrder) {<br>            if (newValues.contains(val)) {<br>                updatedOrder.add(val);<br>                newValues.remove(val);<br>            }<br>        }</pre><pre>        // Append newly added values<br>        for (String val : newValues) {<br>            updatedOrder.add(val);<br>        }</pre><pre>        rec.FieldB__c =<br>            updatedOrder.isEmpty()<br>            ? null<br>            : String.join(updatedOrder, &#39;, &#39;);<br>    }<br>}</pre><h3>Why This Works Better</h3><p>This implementation:</p><ul><li>Preserves user-defined order</li><li>Prevents destructive overwrites</li><li>Handles delta changes instead of rebuilding everything</li><li>Works regardless of update source (UI, import, automation)</li><li>Ensures long-term data integrity</li></ul><h3>Testing Strategy</h3><p>The test class validates:</p><ul><li>Insert behavior</li><li>Order preservation</li><li>Removal of deleted values only</li><li>Appending of newly added values</li><li>Clearing when source field is cleared</li></ul><p>This ensures stable behavior across future changes.</p><h3>Key Takeaways</h3><h4>Never blindly mirror a multi-select picklist into a text field</h4><p>Order and formatting can matter more than expected.</p><h4>Avoid destructive rebuilds</h4><p>Delta-based synchronization is safer than full overwrite logic.</p><h4>Centralize enforcement</h4><p>Triggers (or before-save flows) are better than page-specific logic.</p><h4>Consider order preservation early</h4><p>If order has business meaning (badges, display names, exports), design accordingly from the start.</p><h3>Final Thought</h3><p>Sometimes the issue is not a “bug” it’s a design assumption that doesn’t scale across real-world update paths.</p><p>Thoughtful synchronization logic can turn fragile behavior into a stable, predictable system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ebd3bb17d4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce Deployment Using Bitbucket CI/CD Pipeline: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@hrishikeshwagh2001/salesforce-deployment-using-bitbucket-ci-cd-pipeline-a-step-by-step-guide-324bb1646486?source=rss-fa7160d22626------2</link>
            <guid isPermaLink="false">https://medium.com/p/324bb1646486</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[deployment-pipelines]]></category>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[salesforce-lightning]]></category>
            <dc:creator><![CDATA[Hrishikesh Wagh]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 12:14:31 GMT</pubDate>
            <atom:updated>2024-09-09T12:14:31.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Introduction</h3><p>This guide details the process of setting up a Continuous Integration/Continuous Deployment (CI/CD) pipeline for Salesforce using Bitbucket. The pipeline will be triggered whenever code is merged into the main branch or directly pushed to it. Upon successful execution, the pipeline will deploy the changes to the production Salesforce org.</p><h3>2. Prerequisites</h3><p>- Salesforce CLI installed on your machine.<br> — Visual Studio Code (VSCode) with Salesforce Extensions.<br> — Access to a Salesforce sandbox environment.<br> — Bitbucket account and basic understanding of Git.<br> — OpenSSL installed on your system.</p><h3>3. Setting Up the Salesforce Project</h3><h4>Create a Salesforce Project with Manifest in VSCode:</h4><p>1. Open VSCode and use the Command Palette (Ctrl + Shift + P) to create a new Salesforce project with manifest.<br> 2. Choose a project name and directory.</p><h4>Authorize the Sandbox (Dev Org):</h4><p>1. In VSCode, open the terminal and run the following command to authorize your sandbox org:</p><pre>   sfdx force:auth:web:login --setalias DevOrg --instanceurl https://test.salesforce.com --setdefaultusername</pre><p>2. Log in to your Salesforce sandbox when prompted.</p><h3>4. Initializing the Git Repository and Pushing to Bitbucket</h3><h4>Create a Project in Bitbucket:</h4><p>1. Log in to your Bitbucket account and create a new project.<br> 2. Within the project, create a new repository.</p><h4>Initialize Git in Your Salesforce Project:</h4><p>1. In the VSCode terminal, navigate to your project directory and initialize a Git repository:</p><pre>git init</pre><p>2. Add all project files to the Git repository:</p><pre> git add .</pre><p>3. Commit the changes:</p><pre> git commit -m &quot;Initial commit of Salesforce project template&quot;</pre><p>4. Add the Bitbucket repository as the remote origin and push the changes to the main branch:</p><pre> git remote add origin &lt;bitbucket-repo-url&gt;<br> git push -u origin main</pre><h3>5. Generating Server Key and Certificate Using OpenSSL</h3><h4>Generate the server.key and Certificate:</h4><p>1. Open a terminal and run the following commands to generate a private key (server.key) and a self-signed certificate (server.crt):</p><pre>openssl genrsa -out server.key 2048<br>openssl req -new -x509 -key server.key -out server.crt -days 365 -subj &quot;/C=US/ST=CA/L=SF/O=YourCompany/OU=IT/CN=yourdomain.com&quot;</pre><p>2. Store the generated server.key securely, as it will be used for JWT authentication.</p><h3>6. Creating a Connected App in Salesforce</h3><h4>Log in to Salesforce and Create a Connected App:</h4><p>1. Navigate to Setup &gt; App Manager &gt; New Connected App.<br> 2. Enter the required details (Name, Contact Email, etc.).</p><h4>Enable OAuth Settings:</h4><p>1. Check the Enable OAuth Settings box.<br> 2. Set the Callback URL (e.g., <a href="https://login.salesforce.com/services/oauth2/callback).">https://login.salesforce.com/services/oauth2/callback).</a><br> 3. Select the following OAuth scopes:<br> — Manage user data via APIs (api)<br> — Manage user data via Web browsers (web)<br> — Full access (full)<br> — Perform requests at any time (refresh_token, offline_access)</p><h4>Enable Digital Certificate:</h4><p>1. Check the Use Digital Signatures box.<br> 2. Upload the certificate (server.crt) generated by OpenSSL.</p><h4>Configure Additional Settings:</h4><p>1. Permitted Users: Admin approved users are pre-authorized.<br> 2. IP Relaxation: Relax IP restrictions.</p><h4>Save the Connected App:</h4><p>1. Note down the Consumer Key (Client ID), which will be used later.</p><h3>7. Configuring Bitbucket Pipelines</h3><h4>Enable Pipelines in Bitbucket:</h4><p>1. Navigate to your Bitbucket repository and go to Settings &gt; Pipelines.<br> 2. Enable Pipelines.</p><h4>Create pipeline-bitbucket.yml File:</h4><p>1. In your Salesforce project, create a new file named bitbucket-pipelines.yml and add the following code:</p><pre>image:<br>  name: salesforce/salesforcedx:7.75.1-slim<br><br>pipelines:<br>  default:<br>    - step:<br>        script:<br>          - echo &quot;Committed changes to a branch that does not match the listed branches in bitbucket-pipelines.yml.&quot;<br>          - echo &quot;You can skip running the pipeline by adding [skip ci] or [ci skip] (with []) to the git commit message.&quot;<br>          - sfdx --version<br>          - sfdx plugins --core<br><br>  branches:<br>    main:<br>     - step:<br>         script:<br>           - sfdx --version<br>           - sfdx force:auth:jwt:grant -f assets/server.key -i $SF_PROD_CLIENT_ID -u $SF_PROD_USERNAME -d -s -r https://login.salesforce.com<br>           - sfdx force:source:deploy -x manifest/package.xml</pre><h4>Add Necessary Repository Variables:</h4><p>1. In Bitbucket, navigate to Repository Settings &gt; Repository variables.<br> 2. Add the following variables:<br> — SF_PROD_CLIENT_ID: The Consumer Key from your Salesforce Connected App.<br> — SF_PROD_USERNAME: The username of the Salesforce Production Org.<br> — SF_PROD_LOGIN_URL: The login URL for your production environment (e.g., <a href="https://login.salesforce.com)./">https://login.salesforce.com).</a></p><h4>Add server.key to Your Project:</h4><p>1. Create a folder named assets in your project directory.<br> 2. Move the server.key file into the assets folder.</p><h4>Commit and Push Changes:</h4><p>1. Commit the bitbucket-pipelines.yml file and any other changes to your Bitbucket repository:</p><pre>git add .<br>git commit -m &quot;Added Bitbucket pipeline configuration&quot;<br>git push origin main</pre><h3>8. Conclusion</h3><p>You have successfully set up a CI/CD pipeline for Salesforce using Bitbucket. This pipeline automatically deploys changes to the production org when code is pushed to or merged into the main branch. Follow these steps to ensure a seamless deployment process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=324bb1646486" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>