<?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 SelfCodedMindset on Medium]]></title>
        <description><![CDATA[Stories by SelfCodedMindset on Medium]]></description>
        <link>https://medium.com/@selfcodedmindset?source=rss-18d7350cbfcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ay_NdPGg-_8KlEsV</url>
            <title>Stories by SelfCodedMindset on Medium</title>
            <link>https://medium.com/@selfcodedmindset?source=rss-18d7350cbfcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:21:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@selfcodedmindset/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[Implementing Custom Pagination in SFCC Order History]]></title>
            <link>https://medium.com/@selfcodedmindset/implementing-custom-pagination-in-sfcc-order-history-8b724893e454?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b724893e454</guid>
            <category><![CDATA[salesforce-commerce-cloud]]></category>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[isml]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 02:12:10 GMT</pubDate>
            <atom:updated>2025-08-26T02:12:10.869Z</atom:updated>
            <content:encoded><![CDATA[<p>When working with Salesforce Commerce Cloud (SFCC), the default order history view can feel limiting — especially when you’re dealing with a large number of orders. Instead of overwhelming users with a long, unbroken list, a more user-friendly approach is to add <strong>pagination</strong>.</p><p>In this post, we’ll walk through how to implement pagination for the order history page using SFCC’s PagingModel, ISML templates, and some controller logic.</p><h3>Why Pagination Matters</h3><p>Pagination improves both <strong>performance</strong> and <strong>user experience</strong>. Instead of fetching and rendering dozens (or hundreds) of orders at once, you can display a subset while still giving customers an easy way to navigate through their full history.</p><p>This not only makes the UI cleaner but also ensures that your backend isn’t overloading itself trying to process large datasets in one go.</p><h3>Controller Setup</h3><p>First, let’s override the Order-History controller endpoint to introduce paging logic. We’ll use SFCC’s PagingModel to manage page slicing.</p><pre>&#39;use strict&#39;;<br>var base = module.superModule;<br>var consentTracking = require(&#39;*/cartridge/scripts/middleware/consentTracking&#39;);<br>var userLoggedIn = require(&#39;*/cartridge/scripts/middleware/userLoggedIn&#39;);<br>var Resource = require(&#39;dw/web/Resource&#39;);<br>var URLUtils = require(&#39;dw/web/URLUtils&#39;);<br>var server = require(&#39;server&#39;);<br>var ArrayList = require(&#39;dw/util/ArrayList&#39;);<br>var PagingModel = require(&quot;dw/web/PagingModel&quot;);<br><br>server.extend(base);<br>//consentTracking.consent,<br>server.replace(<br>    &#39;History&#39;,<br>    <br>    server.middleware.https,<br>    userLoggedIn.validateLoggedIn,<br>    function (req, res, next) {<br>        var OrderHelpers = require(&#39;*/cartridge/scripts/order/orderHelpers&#39;);<br><br>        var ordersResult = OrderHelpers.getOrders(<br>            req.currentCustomer,<br>            req.querystring,<br>            req.locale.id<br>        );<br>        var orders = ordersResult.orders;<br>        var filterValues = ordersResult.filterValues;<br>        var breadcrumbs = [<br>            {<br>                htmlValue: Resource.msg(&#39;global.home&#39;, &#39;common&#39;, null),<br>                url: URLUtils.home().toString()<br>            },<br>            {<br>                htmlValue: Resource.msg(&#39;page.title.myaccount&#39;, &#39;account&#39;, null),<br>                url: URLUtils.url(https://medium.com/&#39;Account-Show&#39;).toString()<br>            }<br>        ];<br>        var pageSize = 1;<br>        var currentPage = req.querystring.page || 0;<br>        var ordersCollection = new ArrayList(orders);<br>        var page = new PagingModel(ordersCollection.iterator(), ordersCollection.size());<br>        page.setPageSize(pageSize);<br>        <br>        page.setStart(currentPage * pageSize);<br><br>        // page.setPage(1);<br><br><br>        res.render(&quot;account/order/history&quot;, {<br>            orders: orders,<br>            pagedOrders: page,<br>            filterValues: filterValues,<br>            orderFilter: req.querystring.orderFilter,<br>            accountlanding: false,<br>            breadcrumbs: breadcrumbs,<br>        });<br>        next();<br>    }<br>);<br><br>module.exports = server.exports();</pre><p>Here, the PagingModel does all the heavy lifting:</p><ul><li>setPageSize() defines how many orders appear per page.</li><li>setStart() calculates the offset (based on the current page).</li></ul><h3>Rendering in ISML</h3><p>On the ISML side, you’ll want to loop through only the <strong>paged orders</strong> instead of the entire collection.</p><pre>&lt;isloop items=&quot;${pdict.pagedOrders.pageElements}&quot; var=&quot;order&quot;&gt;<br>    &lt;div class=&quot;row&quot;&gt;<br>        &lt;div class=&quot;col-xs-12 col-sm-8 offset-sm-2&quot;&gt;<br>            &lt;isinclude template=&quot;account/order/orderHistoryCard&quot; /&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/isloop&gt;</pre><p>This ensures that the page only displays the current set of orders instead of the full list.</p><h3>Building the Pagination UI</h3><p>The next step is to give users clickable controls to move between pages. Using ISML, we can dynamically generate page numbers, along with “previous” and “next” arrows.</p><pre>&lt;ul class=&quot;pagination&quot;&gt;<br><br>        &lt;iscomment&gt;<br>            previous button or arrow<br>        &lt;/iscomment&gt;<br>        &lt;li class=&quot;page-item ${pdict.pagedOrders.currentPage &gt; 0 ? &#39;&#39; : &#39;disabled&#39;}&quot;&gt;&lt;a class=&quot;page-link&quot;<br>                href=&quot;${URLUtils.url(https://medium.com/&#39;Order-History&#39;,%20&#39;page&#39;,%20pdict.pagedOrders.currentPage%20-%201,&#39;mode&#39;,&#39;previous&#39;)}&quot;&gt;&lt;span<br>                    aria-hidden=&quot;true&quot;&gt;&amp;laquo;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;<br>        &lt;isif condition=&quot;${pdict.pagedOrders.maxPage &lt;= 4}&quot;&gt;<br><br><br>            &lt;isloop begin=&quot;0&quot; end=&quot;${pdict.pagedOrders.maxPage}&quot; var=&quot;pageNum&quot; step=&quot;1&quot; status=&quot;loopstate&quot;&gt;<br><br>                &lt;li class=&quot;page-item ${loopstate.index === pdict.pagedOrders.currentPage ? &#39;active&#39; : &#39;&#39;}&quot;&gt;<br>                    &lt;isif condition=&quot;${loopstate.index === pdict.pagedOrders.currentPage}&quot;&gt;<br>                        &lt;span class=&quot;page-link&quot;&gt;${loopstate.count}&lt;/span&gt;<br>                    &lt;iselse/&gt;<br>                        &lt;a class=&quot;page-link&quot; href=&quot;${URLUtils.url(https://medium.com/&#39;Order-History&#39;,%20&#39;page&#39;,%20loopstate.index)}&quot;&gt;<br>                            ${loopstate.count}<br>                        &lt;/a&gt;<br>                    &lt;/isif&gt;<br>                &lt;/li&gt;<br>            &lt;/isloop&gt;<br>        &lt;iselse/&gt;<br><br>            &lt;isif condition=&quot;${pdict.pagedOrders.currentPage &gt; 2}&quot;&gt;<br><br>                &lt;li class=&quot;page-item&quot;&gt;<br>                    &lt;span class=&quot;page-link&quot;&gt;...&lt;/span&gt;<br>                &lt;/li&gt;<br> <br>            &lt;/isif&gt;<br><br><br><br>            &lt;isif condition=&quot;${request.httpParameterMap.frombutton.value}&quot;&gt;<br>            &lt;iscomment&gt; al&lt;ISPRINT value=&quot;${request.httpParameterMap.frombutton.value}&quot;&gt;la &lt;/iscomment&gt;<br>                &lt;isscript&gt;<br>                    var beginPage = Number(request.httpParameterMap.frombutton.value);<br>                    var endPage = Math.min(pdict.pagedOrders.currentPage , pdict.pagedOrders.maxPage);<br>                    if(pdict.pagedOrders.maxPage-beginPage &lt; 4) { endPage=pdict.pagedOrders.maxPage; }<br>                &lt;/isscript&gt;<br>            &lt;iselse/&gt;<br>             &lt;iscomment&gt; ba${request.httpParameterMap.frombutton.value}ab &lt;/iscomment&gt;<br>             <br>                &lt;isscript&gt;<br>                    var beginPage = request.httpParameterMap.value?Math.max(pdict.pagedOrders.currentPage-1,0): pdict.pagedOrders.currentPage;<br>                    var endPage = Math.min(beginPage + 1, pdict.pagedOrders.maxPage);<br>                    if(pdict.pagedOrders.maxPage-beginPage &lt; 4) {<br>                        endPage =  pdict.pagedOrders.maxPage;<br>                    }<br>                &lt;/isscript&gt;<br>            &lt;/isif&gt;<br><br>            &lt;isloop begin=&quot;${beginPage}&quot; end=&quot;${endPage}&quot; var=&quot;pageNum&quot; step=&quot;1&quot; status=&quot;loopstate&quot;&gt;<br>                <br>                &lt;li class=&quot;page-item ${loopstate.index === pdict.pagedOrders.currentPage ? &#39;active&#39; : &#39;&#39;}&quot;&gt;<br>                    &lt;isif condition=&quot;${loopstate.index === pdict.pagedOrders.currentPage}&quot;&gt;<br>                        &lt;span class=&quot;page-link&quot;&gt;${(loopstate.index+1).toFixed()}&lt;/span&gt;<br>                    &lt;iselse/&gt;<br>                        &lt;a class=&quot;page-link&quot; href=&quot;${URLUtils.url(https://medium.com/&#39;Order-History&#39;,%20&#39;page&#39;,%20loopstate.index,&#39;frombutton&#39;,pdict.pagedOrders.currentPage)}&quot;&gt;<br>                            ${(loopstate.index+1).toFixed()}<br>                        &lt;/a&gt;<br>                    &lt;/isif&gt;<br>                &lt;/li&gt;<br>                <br>            &lt;/isloop&gt;<br>            <br>            &lt;iscomment&gt; &lt;isif condition=&quot;${pdict.pagedOrders.currentPage  &lt; pdict.pagedOrders.maxPage-4}&quot;&gt; &lt;/iscomment&gt;<br>            &lt;isif condition=&quot;${endPage  !=pdict.pagedOrders.maxPage}&quot;&gt;<br>            &lt;li class=&quot;page-item ${loopstate.index === pdict.pagedOrders.currentPage ? &#39;active&#39; : &#39;&#39;}&quot;&gt;<br>                &lt;span class=&quot;page-link&quot;&gt;...&lt;/span&gt;<br>            &lt;/li&gt;<br>            &lt;/isif&gt;<br><br>        &lt;/isif&gt;<br><br><br><br>        &lt;li class=&quot;page-item ${pdict.pagedOrders.currentPage &gt;= pdict.pagedOrders.maxPage ? &#39;disabled&#39; : &#39;&#39;}&quot;&gt;&lt;a<br>                class=&quot;page-link&quot;<br>                href=&quot;${URLUtils.url(https://medium.com/&#39;Order-History&#39;,%20&#39;page&#39;,%20pdict.pagedOrders.currentPage%20+%201)}&quot;&gt;&lt;span<br>                    aria-hidden=&quot;true&quot;&gt;&amp;raquo;&lt;/span&gt;&lt;/a&gt;&lt;/li&gt;<br><br>    &lt;/ul&gt;</pre><p>Here’s what’s happening:</p><ul><li><strong>Left arrow («)</strong> is disabled when you’re on the first page.</li><li><strong>Right arrow (»)</strong> is disabled when you’re on the last page.</li><li>The loop dynamically renders the total number of pages.</li></ul><h3>Final Thoughts</h3><p>With just a few lines of controller logic and some ISML tweaks, you can implement a fully functional <strong>pagination system</strong> for SFCC’s order history page. This makes browsing more intuitive for customers and improves site performance.</p><p>If you want to get fancy, you can also add <strong>ellipses (</strong><strong>...)</strong> when page numbers exceed a certain threshold, or integrate AJAX for seamless page loading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b724893e454" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exporting Orders to XML and Emailing the File in Salesforce Commerce Cloud (SFCC) Jobs]]></title>
            <link>https://medium.com/@selfcodedmindset/exporting-orders-to-xml-and-emailing-the-file-in-salesforce-commerce-cloud-sfcc-jobs-7ffa5f343e81?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ffa5f343e81</guid>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 17:55:37 GMT</pubDate>
            <atom:updated>2025-08-25T17:55:37.849Z</atom:updated>
            <content:encoded><![CDATA[<p>When business teams ask for a daily export of orders that match a specific product, you don’t need a third-party tool. SFCC’s job framework, order APIs, and file utilities make it straightforward to assemble XML, save it in IMPEX, and notify stakeholders via email.</p><p>In this post, we’ll build a job that:</p><ol><li>Finds all non-failed orders</li><li>Filters orders that contain a product ID stored in a site preference</li><li>Aggregates each order’s XML into one document</li><li>Writes the XML to the IMPEX directory</li><li>Emails the output (and optionally provides a download link)</li></ol><pre>&#39;use strict&#39;;<br><br>function execute(){<br>    var OrderMgr = require(&#39;dw/order/OrderMgr&#39;);<br>    var Template = require(&#39;dw/util/Template&#39;);<br>    var template = new Template(&#39;OrderExport&#39;)<br>    var SitePreferences = require(&#39;dw/system/SitePreferences&#39;);<br>    var HashMap = require(&#39;dw/util/HashMap&#39;);<br>    var content = new HashMap();<br>    var akshayProductIdPref =<br>        dw.system.Site.current.preferences.custom.akshayProductIdPref;<br>    var orders = OrderMgr.searchOrders(<br>        &quot;status != {0}&quot;,<br>        null,<br>        dw.order.Order.ORDER_STATUS_FAILED,<br>    );<br>    var outputXML = &#39;&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;&lt;orders&gt;\n&#39;;<br>    while (orders.hasNext()) {<br>        var order = orders.next();<br>        var productLineItems = order.getProductLineItems();<br>        var productLineItemsIter = productLineItems.iterator();<br>        while (productLineItemsIter.hasNext()) {<br>            var product = productLineItemsIter.next();<br>            if(product.productID === akshayProductIdPref){<br>                var prodXMLString = order.getOrderExportXML();<br>                var prodXML = new XML(prodXMLString);<br><br>                XML.prettyPrinting=true;<br>                XML.prettyIndent = 4;<br>                outputXML+=&#39;\n&#39;;<br>                // outputXML += template.render(content);<br>                outputXML += prodXML.toString();<br>                break;<br>            }<br>        }<br>    }<br>    outputXML+=&#39;\n&lt;/orders&gt;&#39;<br>    content.order = outputXML;<br>    // outputXML = template.render(content).text;<br>    // outputXML += &#39;&lt;style&gt;order{display:block;margin:1em;}&lt;/style&gt;&#39;;<br>    <br>        <br>        var FileWriter = require(&quot;dw/io/FileWriter&quot;);<br>        var File = require(&quot;dw/io/File&quot;);<br>        var Calendar = require(&quot;dw/util/Calendar&quot;);<br>        var StringUtils = require(&quot;dw/util/StringUtils&quot;);<br>        // var fileName =&#39;exported_orders_&#39; +  + new Date().getTime() + &#39;.xml&#39;;<br>        var fileName = &#39;exported_orders.xml&#39;;<br><br>        var file = new File(File.IMPEX + &quot;/&quot; + fileName);<br>        var fileWriter = new FileWriter(file, &quot;UTF-8&quot;);<br>        fileWriter.write(outputXML);<br>        fileWriter.close();<br><br><br>        var Mail = require(&#39;dw/net/Mail&#39;);<br>        var email = new Mail();<br>        email.addTo(<br>            dw.system.Site.current.getCustomPreferenceValue(<br>                &quot;akshayCustomerEmailPref&quot;,<br>            ),<br>        );<br>        email.setFrom(&#39;no-reply@salesforce.com&#39;);<br>        email.setSubject(&#39;Exported Orders&#39;);<br>        // Set email content<br><br>        email.setContent(outputXML, &quot;text/plain&quot;, &quot;UTF-8&quot;);<br>        var fileUrl =<br>            &quot;https://zydf-001.dx.commercecloud.salesforce.com/on/demandware.servlet/webdav/Sites/IMPEX/&quot; + fileName;<br>        // email.setContent(<br>        //     &quot;Download exported orders: &quot; + fileUrl,<br>        //     &quot;text/plain&quot;,<br>        //     &quot;UTF-8&quot;,<br>        // );<br>        email.send();<br><br>        // Add the XML file as an attachment<br>        // email.addAttachment(file);<br><br>        email.send();<br><br><br>    var Logger = require(&#39;dw/system/Logger&#39;);<br><br>    Logger.info(&#39;Order Exporter Job started&#39;);<br>}<br><br>module.exports = {<br>    execute: execute<br>};</pre><h3>Production hardening tips</h3><ul><li>Limit the search: Add a date window (e.g., last 24 hours) to searchOrders to avoid scanning all history.</li><li>Close iterators: If you use additional iterators, close them after use to free resources.</li><li>MIME type and attachments: Prefer text/xml for email content, or attach the XML file (uncomment addAttachment and remove the duplicate email.send).</li><li>Unique filenames: Use a timestamp in the file name (e.g., exported_orders_YYYYMMDDHHmm.xml) so each run generates a new file.</li><li>Error handling: Wrap file I/O, email sending, and search in try/catch; return proper job status codes and log details.</li><li>Performance: If the order volume is high, consider chunking, or exporting only order IDs first, then resolving details in batches.</li><li>Security: If you email links, ensure appropriate WebDAV permissions and avoid exposing sensitive data.</li></ul><h3>Why this approach is useful</h3><ul><li>No extra infrastructure: Everything runs inside SFCC’s job framework.</li><li>Business-friendly: Product filter and recipient email live in site prefs.</li><li>Lightweight XML assembly: Leverages SFCC’s built-in getOrderExportXML.</li><li>Easy distribution: Store in IMPEX for integrations, email for humans.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ffa5f343e81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calling External APIs in Salesforce Commerce Cloud (SFCC) with LocalServiceRegistry]]></title>
            <link>https://medium.com/@selfcodedmindset/calling-external-apis-in-salesforce-commerce-cloud-sfcc-with-localserviceregistry-2073e512e946?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/2073e512e946</guid>
            <category><![CDATA[sfcc]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[salesforce-commerce-cloud]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 16:28:47 GMT</pubDate>
            <atom:updated>2025-08-25T16:28:47.071Z</atom:updated>
            <content:encoded><![CDATA[<p>Salesforce Commerce Cloud provides dw/svc/LocalServiceRegistry to connect with external REST or SOAP services easily. You can define the service in <strong>BM → Administration → Operations → Services</strong>, and then implement it in your code.</p><p>Let’s walk through two real-world examples:</p><ol><li>Fetching a random joke from an external API</li><li>Sending SMS messages via Twilio</li></ol><h3>Step 1: Define Service in Business Manager</h3><ul><li>Go to <strong>Administration → Operations → Services</strong></li><li>Create a new service profile with an <strong>ID</strong> like akshay.joke.Service or akshay.message.service</li><li>Set the target URL (e.g., Joke API URL or Twilio endpoint)</li><li>Configure credentials if required</li></ul><h3>Step 2: Create Service Definition in Code</h3><p><strong>Example: Joke Service</strong></p><pre>&#39;use strict&#39;;<br>var LocalServiceRegistry = require(&#39;dw/svc/LocalServiceRegistry&#39;);<br>var JokeService = LocalServiceRegistry.createService(&#39;akshay.joke.Service&#39;, {<br>  createRequest: function (svc, args) {<br>    svc.setRequestMethod(&#39;GET&#39;);<br>    svc.addHeader(&#39;Accept&#39;, &#39;application/json&#39;);<br>    return args;<br>  },<br>  parseResponse: function (svc, response) {<br>    var result;<br>    try {<br>    result = JSON.parse(response.text);<br>    } catch (e) {<br>    result = response.text;<br>    }<br>  return result;<br>  }<br>});<br>module.exports = {<br>  JokeService: JokeService<br>};</pre><h3>Step 3: Use the Service in a Controller</h3><pre>server.get(&#39;Joke&#39;, function (req, res, next) {<br>  var jokeService = require(&#39;*/cartridge/services/jokeservice&#39;);<br>  var joke = jokeService.JokeService.call();<br>  if (joke.status === &#39;OK&#39;) {<br>  res.print(JSON.stringify(joke.object));<br>  res.print(joke.object.joke);<br>}<br>next();<br>});</pre><p>👉 When you hit /on/demandware.store/Sites-Site/default/Controller-JokeIt calls the external Joke API and prints the response.</p><h3>Step 4: Example — Sending SMS with Twilio</h3><pre>&#39;use strict&#39;;<br>var LocalServiceRegistry = require(&#39;dw/svc/LocalServiceRegistry&#39;);<br>var TwilioService = LocalServiceRegistry.createService(&#39;akshay.message.service&#39;, {<br>  createRequest: function (svc, args) {<br>    svc.setRequestMethod(&#39;POST&#39;);<br>    var formFields = [<br>    &quot;To=&quot; + encodeURIComponent(args.To),<br>    &quot;From=&quot; + encodeURIComponent(&quot;+1234567890&quot;),<br>    &quot;Body=&quot; + encodeURIComponent(args.Body)<br>    ];<br>    var requestBody = formFields.join(&#39;&amp;&#39;);<br>    svc.addHeader(&#39;Content-Type&#39;, &#39;application/x-www-form-urlencoded&#39;);<br>    return requestBody;<br>  },<br>  parseResponse: function (svc, response) {<br>    var result;<br>    try {<br>    result = JSON.parse(response.text);<br>    } catch (e) {<br>    result = response.text;<br>    }<br>    return result;<br>  }<br>});<br>module.exports = {TwilioService: TwilioService};</pre><p>With this, you can send SMS like this inside a controller:</p><pre>var smsService = require(&#39;*/cartridge/services/twilioservice&#39;);<br>smsService.TwilioService.call({<br>To: &#39;+919876543210&#39;,<br>Body: &#39;Hello from SFCC!&#39;<br>});</pre><h3>Best Practices</h3><ul><li>Use service IDs with namespaces (e.g., projectname.apiName.Service)</li><li>Always handle errors gracefully (status === &#39;ERROR&#39;)</li><li>Keep credentials in BM, not in code</li><li>Log request/response for debugging (use svc.setLogger())</li></ul><h3>Final Thoughts</h3><p>Using LocalServiceRegistry in SFCC makes external API integration simple and maintainable. Whether you’re fetching data (like jokes) or sending outbound requests (like SMS), the service layer ensures everything is centralized and easy to configure in Business Manager.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2073e512e946" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Custom Objects in Salesforce Commerce Cloud (SFCC)]]></title>
            <link>https://medium.com/@selfcodedmindset/working-with-custom-objects-in-salesforce-commerce-cloud-sfcc-e6a0f257abe8?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6a0f257abe8</guid>
            <category><![CDATA[custom-object]]></category>
            <category><![CDATA[sfcc]]></category>
            <category><![CDATA[salesforce-commerce-cloud]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 14:57:36 GMT</pubDate>
            <atom:updated>2025-08-23T14:57:36.246Z</atom:updated>
            <content:encoded><![CDATA[<p>Custom Objects in Salesforce Commerce Cloud (SFCC) are a powerful way to store and manage data that doesn’t naturally belong to products, customers, or orders. Think of them as your flexible storage layer for business-specific requirements.</p><p>For example:</p><ul><li>Storing user preferences</li><li>Managing third-party integration keys</li><li>Saving custom configurations</li></ul><p>In this article, we’ll explore how to fetch, query, and iterate over custom objects using the CustomObjectMgr API.</p><h3>Importing CustomObjectMgr</h3><p>The first step is always requiring the module:</p><pre>var CustomObjectMgr = require(&#39;dw/object/CustomObjectMgr&#39;);</pre><h3>1. Fetching a Single Custom Object by Key</h3><p>If you know the unique key of your custom object, you can directly fetch it.</p><pre>var customObjectTypeId = &#39;MyCustomObject&#39;;<br> var customObjectKey = &#39;myUniqueKey&#39;;<br>var customObject = CustomObjectMgr.getCustomObject(customObjectTypeId, customObjectKey);<br>if (customObject) {<br> var attributeValue = customObject.custom.myAttribute;<br> // Process the custom object<br> }</pre><p>This is useful when you need to retrieve one specific object (like a configuration entry).</p><h3>2. Fetching All Custom Objects of a Type</h3><p>Sometimes you need to iterate through every object of a given type.</p><pre>var customObjectsIterator = CustomObjectMgr.getAllCustomObjects(customObjectTypeId);<br>while (customObjectsIterator.hasNext()) {<br> var obj = customObjectsIterator.next();<br> var attributeValue = obj.custom.myAttribute;<br> // Process each object<br> }</pre><p>This approach is handy for batch jobs or background processes that loop over all records.</p><h3>3. Querying Custom Objects by Attribute</h3><p>If you’ve defined a custom attribute as searchable, you can query custom objects by attribute values.</p><pre>var queryAttribute = &#39;mySearchableAttribute&#39;;<br> var queryValue = &#39;someValue&#39;;<br>var queriedObjectsIterator = CustomObjectMgr.queryCustomObjects(<br> customObjectTypeId,<br> queryAttribute + &#39; = {0}&#39;,<br> null, // Sorting expression<br> queryValue<br> );<br>while (queriedObjectsIterator.hasNext()) {<br> var obj = queriedObjectsIterator.next();<br> var attributeValue = obj.custom.myAttribute;<br> // Process each matching object<br> }</pre><p>This is powerful when you need to filter objects dynamically instead of fetching them all.</p><h3>Best Practices</h3><ul><li>Always close iterators after use to free resources (customObjectsIterator.close()).</li><li>Mark attributes as searchable only when really needed — searchable fields increase index size.</li><li>Use unique keys meaningfully (e.g., storeConfig_us, integrationKey_x).</li><li>Consider using transactions when creating or updating objects.</li></ul><h3>Final Thoughts</h3><p>Custom Objects are one of the most flexible features of SFCC. With just a few lines of code, you can store and query almost any custom data your project needs. Whether it’s user preferences, temporary storage, or integration metadata — CustomObjectMgr makes it easy to work with them at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6a0f257abe8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating and Sending PDFs with Apex in Salesforce]]></title>
            <link>https://medium.com/@selfcodedmindset/generating-and-sending-pdfs-with-apex-in-salesforce-fe36e198ae0c?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe36e198ae0c</guid>
            <category><![CDATA[salesforce-development]]></category>
            <category><![CDATA[salesforce-files]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-apex]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 14:30:59 GMT</pubDate>
            <atom:updated>2025-08-23T14:30:59.819Z</atom:updated>
            <content:encoded><![CDATA[<p>In Salesforce, there are many scenarios where we need to generate PDF files dynamically. For example:</p><ul><li>Sending reports as PDF attachments in emails.</li><li>Storing PDF files in Salesforce Files and linking them to specific records.</li><li>Automating document generation for invoices, contracts, or summaries.</li></ul><p>With Apex, this becomes very straightforward using the <strong>Blob.toPdf()</strong> method and Salesforce’s built-in messaging and file management APIs.</p><p>In this article, we’ll explore two common use cases:</p><ol><li>Sending a dynamically generated PDF as an email attachment.</li><li>Creating a PDF, saving it in Salesforce Files, and linking it to a record.</li></ol><h3>1. Sending a PDF as an Email Attachment</h3><p>In this example, we generate a PDF from HTML content and send it as an attachment in an email.</p><pre>String emailHTMLBody= &#39;&lt;h1&gt;Hello, PDF!&lt;/h1&gt;&#39;;<br>Blob htmlBody = Blob.valueOf(emailHTMLBody);<br>Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();<br>Blob pdfData = Blob.toPdf(emailHTMLBody);<br>attachment.setFileName(&#39;limits_report.pdf&#39;);<br>attachment.setBody(pdfData);<br>List&lt;Messaging.EmailFileAttachment&gt; attachments = new List&lt;Messaging.EmailFileAttachment&gt;();<br>attachments.add(attachment);<br>email.setFileAttachments(attachments);<br>for (String emailAddress : emailAddresses) {<br>  email.setToAddresses(new String[] { emailAddress });<br>  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });<br>}</pre><h3>What’s happening here?</h3><ul><li>Convert HTML into a Blob using Blob.toPdf().</li><li>Create an EmailFileAttachment and assign the Blob data to it.</li><li>Attach it to the email and send to recipients.</li></ul><p>This is especially useful when you want to automatically generate <strong>reports, invoices, or dashboards</strong> and send them via email.</p><h3>2. Saving PDF in Salesforce Files (ContentVersion)</h3><p>Instead of just emailing a PDF, you may want to store it in Salesforce Files and associate it with a record (like an Account or Opportunity).</p><p>Here’s how:</p><pre>String pdfContent = &#39;&lt;h1&gt;Hello, PDF!&lt;/h1&gt;&#39;;<br> Blob pdfBlob = Blob.toPdf(pdfContent);<br>ContentVersion cv = new ContentVersion(<br> Title = &#39;My PDF Document&#39;,<br> VersionData = pdfBlob,<br> PathOnClient = &#39;MyPDF.pdf&#39;,<br> IsMajorVersion = true<br> );<br> insert cv;<br>ContentVersion latestCv = [SELECT ContentDocumentId FROM ContentVersion WHERE Id = :cv.Id];<br>ContentDocumentLink cdl = new ContentDocumentLink(<br> ContentDocumentId = latestCv.ContentDocumentId,<br> LinkedEntityId = &#39;001gK00000FcHFMQA3&#39;, // e.g., Account Id or other record Id<br> ShareType = &#39;V&#39;<br> );<br> insert cdl;<br> system.debug(cdl);</pre><p>ContentVersion Object takes these arguments</p><ul><li>Title: The title of a document</li><li>VersionData: The content or body of the note, which can include properly formatted HTML or plain text. When a document is uploaded or downloaded via the API, it should be base64 encoded (for upload) or decoded (for download). Any special characters within plain text in the Content field must be escaped. You can escape special characters by calling content.escapeHtml4().</li><li>PathOnClient: The complete path of the document. One of the fields that determines the FileType.</li><li>IsMajorVersion: true if the document is a major version; false if the document is a minor version. Major versions can’t be replaced.</li></ul><p>Read more about ContentVersion <a href="https://developer.salesforce.com/docs/atlas.en-us.object_reference.meta/object_reference/sforce_api_objects_contentversion.htm">here</a>.</p><h3>What’s happening here?</h3><ul><li>Create a simple HTML string and convert it into a PDF Blob.</li><li>Insert a new ContentVersion record, which stores the file in Salesforce Files.</li><li>Fetch the ContentDocumentId contents of the inserted file.</li><li>Create a ContentDocumentLink link to the file to a Salesforce record.</li></ul><p>This is very handy for scenarios where you want documents stored <strong>against records automatically</strong> — for example, generating an invoice when an Opportunity is closed.</p><h3>Key Takeaways</h3><ul><li><strong>Blob.toPdf()</strong> lets you convert HTML strings into PDF files directly in Apex.</li><li>You can either <strong>send the PDF via email</strong> or <strong>save it into Salesforce Files</strong>.</li><li>Using <strong>ContentVersion + ContentDocumentLink</strong>, you can link generated files to any Salesforce record.</li></ul><p>This approach eliminates the need for third-party tools in many cases and allows you to build lightweight document automation features natively in Salesforce.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe36e198ae0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Child Relationship Class in apex]]></title>
            <link>https://medium.com/@selfcodedmindset/child-relationship-class-in-apex-f660366fac0b?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/f660366fac0b</guid>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 13:15:51 GMT</pubDate>
            <atom:updated>2025-08-23T13:15:51.117Z</atom:updated>
            <content:encoded><![CDATA[<p>This Apex class, Feb2023Controller, is designed to retrieve child object records related to a specific parent record in Salesforce. Here&#39;s a breakdown of what it does:</p><ol><li><strong>getChildObjects Method</strong>:</li></ol><ul><li><strong>Input Parameters</strong>: The method takes two parameters: objectName (the name of the parent object) and recordId (the ID of the parent record).</li><li><strong>Field Definitions</strong>: It queries the FieldDefinition object to get the name field for each child object that is related to the given parent object.</li><li><strong>Child Relationships</strong>: It uses Salesforce’s Schema.getGlobalDescribe() to get the child relationships of the specified parent object.</li><li><strong>Querying Child Records</strong>: For each child relationship, it constructs a dynamic SOQL query to retrieve the Id and name field values from the child object, filtering by the parent record&#39;s ID</li><li><strong>Return Value</strong>: It returns a list of maps containing the child object data, including the relationship name, name field, child object name, and the related child records.</li></ul><ol><li><strong>Error Handling</strong>: It includes basic error handling (try-catch block) to handle any exceptions that may occur when executing the SOQL query.</li><li><strong>Caching</strong>: The method is annotated with @AuraEnabled(cacheable=true), meaning it can be used in Lightning components with caching enabled to optimize performance.</li></ol><p>In summary, this code dynamically retrieves child object records based on the specified parent record, making it useful in scenarios where you need to fetch related data from various child objects in Salesforce.</p><pre>public static Map&lt;String, List&lt;Map&lt;string,string&gt;&gt;&gt; getChildObjects(string objectName){<br>    List&lt;Schema.ChildRelationship&gt; childs = Schema.getGlobalDescribe().get(objectName).getDescribe().getChildRelationships();<br>    Map&lt;String, List&lt;Map&lt;string,string&gt;&gt;&gt; childObjects = new Map&lt;String, List&lt;Map&lt;string,string&gt;&gt;&gt;();<br>    <br>    <br>    // 4. Iterate and Describe Fields (optional, for detailed info)<br>    <br>    for(Schema.ChildRelationship cr : childs){<br>        String childObjectName = cr.getChildSObject().toString();<br>        Map&lt;String, Schema.SObjectField&gt; fieldMap = Schema.getGlobalDescribe().get(childObjectName).getDescribe().fields.getMap();<br>        List&lt;Map&lt;String,String&gt;&gt; combinedData = new List&lt;Map&lt;String,String&gt;&gt;();<br>        for (String fieldName : fieldMap.keySet()) {<br>            Schema.DescribeFieldResult fieldDescribe = fieldMap.get(fieldName).getDescribe();<br>            Map&lt;string,string&gt; data = new Map&lt;String,String&gt;();<br>            data.put(&#39;value&#39;, fieldDescribe.getName());<br>            data.put(&#39;label&#39;, fieldDescribe.getLabel());<br>            data.put(&#39;Type&#39;, fieldDescribe.getType().toString());<br>            combinedData.add(data);<br>        }<br>        <br>        childObjects.put(childObjectName,combinedData);<br>    }<br>    return childObjects;</pre><pre>public with sharing class Feb2023Controller {<br>    @AuraEnabled(cacheable=true)<br>    public static List&lt;Map&lt;String, object&gt;&gt; getChildObjects(string objectName, String recordId) {<br>        List&lt;FieldDefinition&gt; fieldDefinitions = [SELECT EntityDefinition.QualifiedApiName , QualifiedApiName FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName!=null and IsNameField = TRUE];<br>        Map&lt;String,String&gt; objectMap = new Map&lt;String,String&gt;();<br>        for(FieldDefinition fieldDef : fieldDefinitions) {<br>            objectMap.put(fieldDef.EntityDefinition.QualifiedApiName, fieldDef.QualifiedApiName);<br>        }<br>        <br>        List&lt;Map&lt;String, Object&gt;&gt; childObjects = new List&lt;Map&lt;String, object&gt;&gt;();<br>        List&lt;Schema.ChildRelationship&gt; childRelationships = Schema.getGlobalDescribe().get(objectName).getDescribe().getChildRelationships();<br>        <br>        for(Schema.ChildRelationship childRel : childRelationships) {<br>            if(childRel.getRelationshipName() != null) {<br>                string nameField = objectMap.get(childRel.getChildSObject().getDescribe().getName());<br>                string childObjectName = childRel.getChildSObject().getDescribe().getName();<br>                string relnName = childRel.getRelationshipName();<br>                System.debug(&#39;childRel.getField(): &#39; + childRel.getField());<br>                Map&lt;String, Object&gt; childObject = new Map&lt;String, Object&gt;();<br>                childObject.put(&#39;Name&#39;, relnName);<br>                childObject.put(&#39;NameField&#39;, nameField);<br>                childObject.put(&#39;ChildObjectName&#39;, childObjectName);<br>                if(nameField != null) {<br>                    <br>                    string query=&#39;SELECT Id,&#39; + nameField + &#39; FROM &#39; + childObjectName + &#39; WHERE &#39; + childRel.getField() + &#39; = \&#39;&#39; + recordId + &#39;\&#39;&#39;;<br>                    System.debug(&#39;Query: &#39; + query);<br>                    try{<br>                        List&lt;Sobject&gt; childRecords = Database.query(query);<br>                        <br>                        if(!childRecords.isEmpty()) {<br>                            childObject.put(&#39;Records&#39;, childRecords);<br>                            childObjects.add(childObject);<br>                        }<br>                    }<br>                    catch(Exception e) {<br>                        System.debug(&#39;Error executing query: &#39; + e.getMessage());<br>                        // Handle the exception as needed<br>                    }<br>                }<br>            }<br>        }<br>        return childObjects;<br>        <br>        <br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f660366fac0b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding a Custom Popup for Cart Attributes in Salesforce Commerce Cloud (SFRA)]]></title>
            <link>https://medium.com/@selfcodedmindset/document-in-mail-a87fa4e3c452?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a87fa4e3c452</guid>
            <category><![CDATA[sfcc]]></category>
            <category><![CDATA[apex]]></category>
            <category><![CDATA[salesforce-apex]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[salesforce-commerce-cloud]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 18:11:10 GMT</pubDate>
            <atom:updated>2025-08-23T14:50:42.079Z</atom:updated>
            <content:encoded><![CDATA[<p>In Salesforce Commerce Cloud (SFCC) with the <strong>SFRA architecture</strong>, there are scenarios where business teams want to capture extra input from customers during the shopping experience.</p><p>For example, let’s say we want to capture a custom attribute weekAttributeAk when a shopper clicks the <strong>Add to Cart</strong> button. Instead of directly adding the product to the cart, we’ll display a pop-up, let the customer choose a value (like 2 Weeks, 3 Weeks, etc.), and then store this data with the order once checkout completes.</p><p>In this article, I’ll walk you through the full implementation</p><h3>Step 1: Extending the Add to Cart Templates</h3><p>We need to inject a popup component into both the <strong>product add to cart button</strong> and the <strong>global add to cart button</strong>.</p><p>First, extend the addToCartProduct.isml template. This includes loading a custom JS file and adding a reference to the popup template.</p><pre>#!templates\default\product\components\addToCartProduct.isml<br>&lt;isscript&gt;<br>    var assets = require(&#39;*/cartridge/scripts/assets&#39;);<br>    assets.addJs(&#39;js/cartClick.js&#39;);<br>&lt;/isscript&gt;<br><br>&lt;isinclude template=&quot;product/components/customPopup&quot; /&gt;<br>&lt;div class=&quot;row cart-and-ipay&quot;&gt;<br>    &lt;div class=&quot;col-sm-12&quot;&gt;<br>        &lt;input type=&quot;hidden&quot; class=&quot;add-to-cart-url&quot; value=&quot;${pdict.addToCartUrl}&quot;&gt;<br>        &lt;button class=&quot;add-to-cart btn btn-primary&quot;<br>                data-toggle=&quot;modal&quot; data-target=&quot;#chooseBonusProductModal&quot;<br>                data-pid=&quot;${product.id}&quot;<br>                id=&quot;addToCartButton&quot;<br>                ${!product.readyToOrder || !product.available ? &quot;disabled&quot; : &quot;&quot;}&gt;<br>            &lt;i class=&quot;fa fa-shopping-bag&quot;&gt;&lt;/i&gt;<br>            ${Resource.msg(&#39;button.addtocart&#39;, &#39;common&#39;, null)}<br>        &lt;/button&gt;<br><br>        &lt;isinclude template=&quot;product/components/addToCartButtonExtension&quot;/&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Then, extend the addToCartGlobal.isml template in a similar way.</p><pre>#!templates\default\product\components\addToCartGlobal.isml<br>&lt;isscript&gt;<br>    var assets = require(&#39;*/cartridge/scripts/assets&#39;);<br>    assets.addJs(&#39;js/cartClick.js&#39;);<br>&lt;/isscript&gt;<br>&lt;isinclude template=&quot;product/components/customPopup&quot; /&gt;<br>&lt;div class=&quot;row cart-and-ipay&quot;&gt;<br>    &lt;div class=&quot;col-sm-12&quot;&gt;<br>        &lt;input type=&quot;hidden&quot; class=&quot;add-to-cart-url&quot; value=&quot;${pdict.addToCartUrl}&quot;&gt;<br>        &lt;button class=&quot;add-to-cart-global btn btn-primary&quot; data-pid=&quot;${product.id}&quot; <br>            id=&quot;addToCartButton&quot;<br>                ${!product.readyToOrder || !product.available ? &quot;disabled&quot; : &quot;&quot;}&gt;<br>            &lt;i class=&quot;fa fa-shopping-bag&quot;&gt;&lt;/i&gt;<br>            &lt;isif condition=&quot;${product.productType === &#39;set&#39; || product.productType === &#39;bundle&#39;}&quot;&gt;<br>                ${Resource.msg(&#39;button.addalltocart&#39;, &#39;common&#39;, null)}<br>            &lt;iselse&gt;<br>                ${Resource.msg(&#39;button.addtocart&#39;, &#39;common&#39;, null)}<br>            &lt;/isif&gt;<br>        &lt;/button&gt;<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Both templates include the <strong>custom popup template</strong>.</p><h3>Step 2: Creating the Custom Popup Template</h3><p>Next, create the popup UI where the shopper can select the number of weeks. This template also exposes a route (Cart-StoreWeek) that will be used to store the chosen value in the session.</p><pre>#!templates\default\product\components\customPopup.isml<br>&lt;script&gt;<br>var routes = {<br>&#39;StoreWeek&#39;: &#39;${URLUtils.url(https://medium.com/&quot;Cart-StoreWeek&quot;)}&#39;<br>};<br>&lt;/script&gt;<br>&lt;isscript&gt;<br>    var assets = require(&#39;*/cartridge/scripts/assets&#39;);<br>    assets.addCss(&#39;css/customPopup.css&#39;);<br>   <br>&lt;/isscript&gt;<br><br>&lt;div class=&quot;weekPopup&quot;&gt;<br>    &lt;select id=&quot;weekInput&quot;&gt;<br>        &lt;option value=&quot;2 Weeks&quot;&gt;2 Weeks&lt;/option&gt;<br>        &lt;option value=&quot;3 Weeks&quot;&gt;3 Weeks&lt;/option&gt;<br>        &lt;option value=&quot;4 Weeks&quot;&gt;4 Weeks&lt;/option&gt;<br>    &lt;/select&gt;<br>    &lt;button class=&quot;submitWeekDetail&quot;&gt;Submit&lt;/button&gt;<br>&lt;/div&gt;</pre><h3>Step 3: JavaScript Handler for Cart Click</h3><p>Now we need client-side logic to:</p><ol><li>Intercept the add-to-cart click.</li><li>Show the popup.</li><li>Capture the value and store it via AJAX.</li><li>Re-trigger the original add-to-cart event after storing the value.</li></ol><pre>#!client\default\js\cartClick.js<br>&#39;use strict&#39;;<br> var originalHandlers = {};<br><br> function turnOffAndStore(selector, eventType) {<br>     // Get all event handlers for the element<br>     var element = $(selector);<br>     var events = $._data(element[0], &quot;events&quot;);<br><br>     if (events &amp;&amp; events[eventType]) {<br>         // Store the original handlers<br>         originalHandlers[selector + &quot;_&quot; + eventType] =<br>             events[eventType].slice();<br><br>         // Turn off the event<br>         element.off(eventType);<br>     }<br> }<br><br> function turnBackOn(selector, eventType) {<br>     var element = $(selector);<br>     var key = selector + &quot;_&quot; + eventType;<br><br>     if (originalHandlers[key]) {<br>         // Re-attach all original handlers<br>         originalHandlers[key].forEach(function (handler) {<br>             element.on(<br>                 eventType,<br>                 handler.selector,<br>                 handler.data,<br>                 handler.handler,<br>             );<br>         });<br>     }<br> }<br>$(&quot;#addToCartButton&quot;).on(&quot;click&quot;, function (event) {<br>    event.stopPropagation();<br>    event.preventDefault();<br>    $(&quot;.weekPopup&quot;).addClass(&quot;show&quot;);<br>});<br><br>$(&#39;.submitWeekDetail&#39;).on(&#39;click&#39;, function(event) {<br>    // $(&#39;body&#39;).off(&#39;click&#39;, &#39;#addToCartButton&#39;);<br><br>    turnOffAndStore(&quot;#addToCartButton&quot;, &quot;click&quot;);<br>    <br>    $(&#39;.weekPopup&#39;).removeClass(&#39;show&#39;);<br>    $.ajax({<br>        url: routes.StoreWeek,<br>        type: &quot;POST&quot;,<br>        data: { week: $(&quot;#weekInput&quot;).val() },<br>        success: function (response) {<br>            // Handle success response if needed<br>            console.log(&quot;Week stored successfully:&quot;, response);<br>        },<br>        error: function (error) {<br>            // Handle error response if needed<br>            console.error(&quot;Error storing week:&quot;, error);<br>        },<br>    });<br>    $(&quot;button.add-to-cart, button.add-to-cart-global&quot;).trigger(&quot;click&quot;);<br>    turnBackOn(&quot;#addToCartButton&quot;, &quot;click&quot;);<br>});<br><br></pre><p>The logic here ensures the default add-to-cart action is delayed until after the shopper’s selection is captured.</p><h3>Step 4: Extending the Cart Controller</h3><p>On the server side, extend the Cart.js controller with a new route (Cart-StoreWeek). This route receives the selected week value via AJAX and stores it in the <strong>session custom object</strong>.</p><pre>#!controllers\Cart.js<br>&#39;use strict&#39;;<br>var server = require(&#39;server&#39;);<br><br>var base = module.superModule;<br><br>server.extend(base);<br>server.post(&#39;StoreWeek&#39;, function (req, res, next) {<br><br>    var customSession = request.getSession().custom;<br>   <br>   var week = req.form.week;<br>   <br>   customSession.week = week;<br>   res.json({<br>         success: true,<br>         week: customSession.week<br>    });<br>   next();<br>});<br><br>module.exports = server.exports();<br><br><br><br></pre><h3>Step 5: Extending the Checkout Process</h3><p>Finally, extend the CheckoutServices.js controller to carry the session value into the final order. When the order is placed, the custom attribute weekAttributeAk is written to the order record.</p><pre>#!controllers\CheckoutServices.js<br>&#39;use strict&#39;;<br>var server = require(&#39;server&#39;);<br>var base = module.superModule;<br>server.extend(base);<br><br>server.replace(&#39;PlaceOrder&#39;, server.middleware.https, function (req, res, next) {<br>    //... existing code<br><br>    // Creates a new order.<br>    var order = COHelpers.createOrder(currentBasket);<br>    if (!order) {<br>        res.json({<br>            error: true,<br>            errorMessage: Resource.msg(&#39;error.technical&#39;, &#39;checkout&#39;, null)<br>        });<br>        return next();<br>    }<br>    var currentSession  = request.getSession().custom;<br>    <br>    Transaction.wrap(function () {<br>        order.custom.weekAttributeAk = currentSession.week;<br>    });<br><br><br>    // rest of code...<br><br>    return next();<br>});<br><br>module.exports = server.exports();</pre><h3>How It Works</h3><ol><li>Shopper clicks “Add to Cart.”</li><li>Instead of immediately adding, a popup appears asking for the week selection.</li><li>The selection is saved in the shopper’s session (customSession.week).</li><li>The add-to-cart action proceeds as usual.</li><li>At checkout, the order is created, and the session value is written into the order’s custom attribute weekAttributeAk.</li></ol><h3>Why This Approach Works</h3><ul><li><strong>Decoupled logic</strong>: We don’t modify the core add-to-cart behavior, but instead extend it.</li><li><strong>Session storage</strong>: Capturing values in the session makes it easy to persist across the flow.</li><li><strong>Order customization</strong>: The final order carries the custom value without major changes to checkout logic.</li></ul><p>This pattern is reusable whenever you need to prompt for <strong>extra attributes at add-to-cart time</strong> (like engraving text, delivery preferences, or subscription options).</p><h3>Final Thoughts</h3><p>With a little frontend and backend extension, SFCC SFRA gives you the flexibility to capture custom attributes during shopping flows. This popup-based approach is lightweight, user-friendly, and integrates seamlessly into the checkout lifecycle.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a87fa4e3c452" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Interactive Donut Charts in Salesforce LWC Using Chart.js]]></title>
            <link>https://medium.com/@selfcodedmindset/building-interactive-donut-charts-in-salesforce-lwc-using-chart-js-d52e2dc0475a?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/d52e2dc0475a</guid>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[lwc-development]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 18:07:55 GMT</pubDate>
            <atom:updated>2025-08-20T18:07:55.138Z</atom:updated>
            <content:encoded><![CDATA[<p>Data visualization is a powerful way to make Salesforce applications more interactive and insightful. Instead of presenting users with plain numbers, charts and graphs can highlight trends and insights at a glance.</p><p>One popular option for creating charts in Lightning Web Components (LWC) is <strong>Chart.js</strong>, a lightweight and flexible JavaScript charting library. In this tutorial, we’ll walk through how to integrate Chart.js into an LWC and render a <strong>dynamic donut chart</strong>.</p><h3>Step 1: Load Chart.js into LWC</h3><p>First, upload the <strong>Chart.js library</strong> as a <strong>static resource</strong> in Salesforce. Once uploaded, import it into your component using the loadScript function from lightning/platformResourceLoader.</p><pre>import {loadScript} from ‘lightning/platformResourceLoader’;<br> import chartjs from ‘@salesforce/resourceUrl/chartjs’; //your static resource</pre><h3>Step 2: Define the Chart Data and Configuration</h3><p>Next, prepare the data and configuration for your donut chart. This includes labels, datasets, colors, and chart options such as legends and animations.</p><pre>data = {<br> labels: [<br> ‘Invested Amount’,<br> ‘Ext. Returns’<br> ],<br> datasets: [{<br> label: ‘My First Dataset’,<br> data: [0,0],<br> backgroundColor: [<br> ‘rgb(185, 173, 176)’,<br> ‘rgb(54, 162, 235)’,<br> ],<br> hoverOffset: 4,<br> borderWidth: 0<br> }]<br> };<br>config = {<br> type: &#39;doughnut&#39;,<br> data: this.data,<br> options: {<br> responsive: true,<br> plugins: {<br> legend: {<br> position: &#39;right&#39;<br> }<br> },<br> animation: {<br> animateScale: true,<br> animateRotate: true<br> }<br> }<br> };</pre><h3>Step 3: Render the Chart</h3><p>In the renderedCallback lifecycle hook, load the Chart.js library and initialize the chart once the component has been rendered.</p><pre>renderedCallback() {<br> if (this.isChartJsInitialized) {<br> return;<br> }<br> this.isChartJsInitialized = true;<br> Promise.all([<br> loadScript(this, chartjs)<br> ])<br> .then(() =&gt; {<br> console.log(‘script loaded:’, chartjs);<br> const ctx = this.template.querySelector(‘canvas.donut’)<br> .getContext(‘2d’);<br> this.chart = new window.Chart(ctx, this.config);<br> this.handleChange();<br> })<br> .catch(error =&gt; {<br> console.log(‘Error loading Chart.js’);<br> console.log(JSON.stringify(error));<br> });<br> }</pre><h3>Step 4: Update the Chart with Dynamic Data</h3><p>Once your chart is rendered, you can update it dynamically based on your application logic. For example, update the chart with investment data:</p><pre>this.data.datasets[0].data = [totalInvestment, expectedReturns];<br>this.chart.update();</pre><p>This ensures that whenever your underlying data changes, the donut chart refreshes automatically.</p><h3>Step 5: Add the HTML Template</h3><p>Finally, add the canvas element to your component’s HTML file.</p><pre>&lt;canvas id=”donut” class=”donut” width=”400&quot; height=”400&quot; lwc:dom=”manual”<br> style=”max-width: 400px; max-height: 400px;”&gt;<br> &lt;/canvas&gt;</pre><p>By combining <strong>LWC’s reactivity</strong> with <strong>Chart.js’s visual capabilities</strong>, you can build dashboards that transform raw Salesforce data into <strong>meaningful insights for end users</strong>.</p><h3>Final Thoughts</h3><p>This example demonstrates how simple it is to integrate <strong>Chart.js</strong> with <strong>LWC</strong>. Whether you are building dashboards, analytics pages, or financial summaries, this approach helps bring your Salesforce apps to life with interactive and real-time visuals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d52e2dc0475a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Real-Time Updates in Salesforce with LWC and Platform Events]]></title>
            <link>https://medium.com/@selfcodedmindset/real-time-updates-in-salesforce-with-lwc-and-platform-events-509995fc412b?source=rss-18d7350cbfcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/509995fc412b</guid>
            <category><![CDATA[lwc]]></category>
            <category><![CDATA[salesforce]]></category>
            <dc:creator><![CDATA[SelfCodedMindset]]></dc:creator>
            <pubDate>Wed, 20 Aug 2025 17:58:45 GMT</pubDate>
            <atom:updated>2025-08-20T18:03:21.349Z</atom:updated>
            <content:encoded><![CDATA[<p>🚀 Real-Time Updates in Salesforce with LWC and Platform Events</p><p>In modern Salesforce applications, real-time communication is crucial for keeping users updated without forcing them to refresh their screens. This is where Platform Events and Lightning Web Components (LWC) come into play. By leveraging the empApi module, developers can subscribe to Salesforce events and react to them instantly in the UI.</p><p>In this post, we’ll walk through an example of publishing and subscribing to a custom platform event (ConAndOpp__e) in Salesforce using LWC.</p><h3>Publishing a Platform Event</h3><p>To kick things off, a platform event is published from Apex. This could be triggered from your business logic whenever a condition is met — say, when a contact or opportunity record changes.</p><pre>EventBus.publish(new ConAndOpp__e());</pre><p>Here, we are publishing a new instance of the custom platform event ConAndOpp__e. This event will then be available to any subscriber (LWC, Flow, or even external systems via CometD).</p><h3>Subscribing to Events in LWC</h3><p>On the LWC side, we use the EMP API (lightning/empApi) to listen to the event stream.</p><pre>import { subscribe, unsubscribe, onError } from &#39;lightning/empApi&#39;;<br> channelName = &#39;/event/ConAndOpp__e&#39;; // Replace with your event name<br> subscription = {};</pre><p>The channelName corresponds to your event. Notice that platform events are always prefixed with /event/ followed by the API name.</p><h3>Setting Up the Subscription</h3><p>The real magic happens in the subscription function:</p><pre>subscribeToEvent() {<br> const messageCallback = (response) =&gt; {<br> this.eventData = response.data.payload;<br> console.log(‘Received event: ‘, JSON.stringify(this.eventData));<br> refreshApex(this.contactResults);<br> refreshApex(this.opportunityResults);<br> };<br>subscribe(this.channelName, -1, messageCallback).then(response =&gt; {<br> console.log(&#39;Successfully subscribed to : &#39;, JSON.stringify(response.subscription));<br> this.subscription = response;<br> });<br>onError(error =&gt; {<br> console.error(&#39;Received error from server: &#39;, JSON.stringify(error));<br> });<br> }</pre><p>Here’s what’s happening:</p><ul><li>subscribe: Listens to the platform event stream on the given channel.</li><li>messageCallback: Executes when a new event is published. In this case, it logs the payload and refreshes related Apex data (contactResults and opportunityResults).</li><li>onError: Handles server errors gracefully.</li></ul><h3>Managing the Subscription Lifecycle</h3><p>We should always clean up our event subscriptions when the component is destroyed.</p><pre>disconnectedCallback() {<br>   this.unsubscribeFromEvent();<br>}<br>unsubscribeFromEvent() {<br>   unsubscribe(this.subscription, response =&gt; {<br>     console.log(&#39;unsubscribe() response: &#39;, JSON.stringify(response));<br>   });<br> }</pre><p>And we re-subscribe when the component is initialized:</p><pre>connectedCallback() {<br> this.subscribeToEvent();<br> }</pre><p>This ensures that your component starts listening when it loads and stops when it’s removed.</p><h3>Why Does This Matter?</h3><p>By using <strong>Platform Events with LWC</strong>, you can:</p><ul><li>Build real-time dashboards that update as soon as data changes.</li><li>Notify users about record updates without manual refresh.</li><li>Synchronize related records (like Contacts and Opportunities) automatically.</li></ul><p>This approach improves the <strong>user experience</strong>, reduces the need for polling, and helps maintain <strong>scalable, event-driven Salesforce applications</strong>.</p><h3>Final Thoughts</h3><p>Real-time updates are no longer a luxury — they’re an expectation. Leveraging <strong>Salesforce Platform Events</strong> with <strong>Lightning Web Components</strong> allows you to deliver dynamic, responsive applications that keep your users in sync with business processes.</p><p>If you’re preparing for interviews, I recommend brushing up on <strong>LWC event handling</strong> — it’s a favorite topic among interviewers. You can find a list of common interview questions <a href="https://www.crsinfosolutions.com/61-lwc-lightning-web-component-interview-questions/">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=509995fc412b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>