<?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 Vikranth Karollu Hanumanth on Medium]]></title>
        <description><![CDATA[Stories by Vikranth Karollu Hanumanth on Medium]]></description>
        <link>https://medium.com/@vikranthkaru?source=rss-ade0d38f3972------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rgzQ6ikhzOA89MKyul6vVg.jpeg</url>
            <title>Stories by Vikranth Karollu Hanumanth on Medium</title>
            <link>https://medium.com/@vikranthkaru?source=rss-ade0d38f3972------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 00:18:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikranthkaru/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[Omnistudio — Integration Procedure]]></title>
            <link>https://vikranthkaru.medium.com/omnistudio-integration-procedure-04d11d61c5f1?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/04d11d61c5f1</guid>
            <category><![CDATA[integration-procedure]]></category>
            <category><![CDATA[omnistudio]]></category>
            <category><![CDATA[ip-in-omnistudio]]></category>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 12:29:55 GMT</pubDate>
            <atom:updated>2024-03-24T12:29:55.963Z</atom:updated>
            <content:encoded><![CDATA[<h3>Omnistudio — Integration Procedure</h3><p>What is an Integration Procedure?</p><p>Integration Procedures are indeed server-side processes that execute multiple actions in a single server call.</p><ol><li><strong>Declarative</strong>: This means that Integration Procedures can be configured and defined using declarative tools within the Salesforce platform, such as Flow Builder, without the need for writing custom code (Although in some cases apex class can be invoked as remote action).</li><li><strong>Actions</strong>: Integration Procedures can perform various actions, such as reading or writing data from Salesforce objects, making REST API calls to external systems, or invoking Apex code.</li><li><strong>Invocation</strong>: Integration Procedures can be triggered or invoked from various sources, including. Omniscript, API’s, Apex methods.</li><li><strong>Data Source</strong>: Integration Procedures can serve as a data source for Flex Cards. Flex Cards are components used in Salesforce Lightning Experience to display information from various sources in a flexible, customizable format.</li><li><strong>Single Server Call</strong>: Integration Procedures are optimized for efficiency by allowing multiple actions to be bundled and executed in a single server call. This reduces overhead and improves performance, especially when dealing with complex integration scenarios involving multiple systems and data sources.</li></ol><p>Overall, Integration Procedures provide a powerful and flexible mechanism for integrating Salesforce with external systems, orchestrating complex processes, and automating business logic without the need for extensive custom development.</p><p>Integration procedure are portable, can be used in flex cards and omni-scripts once created.</p><ol><li><strong>Flex Cards</strong>: Integration Procedures can serve as a data source for Flex Cards. Flex Cards are components used in Salesforce Lightning Experience to display information from various sources. By configuring an Integration Procedure as a data source for a Flex Card, you can dynamically fetch and display relevant data within the card, leveraging the capabilities of both Integration Procedures and Flex Cards to create rich user experiences.</li><li><strong>Omniscripts</strong>: Similarly, Integration Procedures can be integrated into Omniscripts. Omniscripts are user interface scripts used in Salesforce to guide users through complex processes. By incorporating Integration Procedures into Omniscripts, you can automate and streamline various tasks and interactions within the user interface, making it easier for users to navigate and complete processes seamlessly.</li></ol><p>When integration procedure is created, there are several details which needs to be displayed, and the integration procedure is typically divided into 4 blocks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1B0drJnrBslVye2doxohww.png" /></figure><ol><li><strong>Available Components: </strong>All the supported components divided as Groups and Actions.</li><li><strong>Structure:</strong> This is where the components used for development of integration procedure will appear, need to drag and drop the components.</li><li><strong>Properties:</strong> Properties provides the information of Integration procedure such as type, subtype, tracking, rollback, required permission and chaining etc.. will go through them in detail.</li><li><strong>Preview</strong>: After IP is saved preview tab appears and used to test the IP.</li></ol><h4><strong>Properties</strong></h4><ol><li><strong>Integration Procedure Name:</strong> The name displayed on the Integration Procedures tab when you expand Type/SubType node. Mark the name unique.</li><li><strong>Type and SubType: </strong>Type and Subtype (needs to be unique name). The Type and SubType are joined by an underscore to create a unique identifier used to call the Integration Procedure.</li><li><strong>Description: </strong>A general description of the Integration procedure.</li><li><strong>Include All Actions in Response</strong> — Write the results of each action to the root level of the Data JSON. By default, results are written to the Data JSON under a node with the same name as the action. (Will explain about it in a while).</li><li><strong>Rollback on Error:</strong> Check this true, if rollback is required in case of errors for DML.</li><li><strong>Required Permission: </strong>Used to specifiy who can run this IP.</li><li><strong>Chainable, Queable Configuration: </strong>This is used to avoid Salesforce governor limits, when invoking long running integration procedures. Can also chain one or more specific long running steps.</li><li><strong>Cache Configuration:</strong> This is used for caching for IP. This is used cache to store frequently accessed data.</li><li><strong>Test Configuration:</strong> To perform unit testing in Integration procedure.</li></ol><p>Let’s create a straightforward Integration Procedure in Salesforce that retrieves data from a Salesforce object using DataRaptor Turbo Extract and then applies transformation on the output.</p><p>In previous post of <a href="https://vikranthkaru.medium.com/omnistudio-dataraptors-9ece72f102b1">DataRaptor</a> i have created the dataraptor turbo extract and dataraptor transform, will utilize them to use in single IP.</p><p>High level steps to create Dataraptor</p><p><strong>Define DataRaptor Turbo Extract:</strong></p><ol><li>Navigate to the OmniStudio app → OmniStudio Dataraptor.</li><li>Opt for “New DataRaptor Turbo Extract”.</li><li>Configure the DataRaptor Turbo Extract to fetch data from the desired Salesforce object and specify any necessary filtering or query criteria.</li><li>Save the DataRaptor Turbo Extract.</li></ol><p><strong>Define DataRaptor Transformation:</strong></p><ol><li>Similarly, create a DataRaptor Transformation to specify how you want the fetched data to be transformed. This may involve mapping fields, applying formulas, or other necessary transformations.</li></ol><p>Drag and drop the dataRaptor turbo action from available components panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*517267tVqoTV2R-IffV3cQ.png" /></figure><p>Output of the GetContacts DR inside this ip will be as below :</p><pre>&quot;GetContacts&quot;: {<br>    &quot;Contact&quot;: [<br>      {<br>        &quot;LastName&quot;: &quot;karu&quot;,<br>        &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>        &quot;FirstName&quot;: &quot;vikranth&quot;<br>      }<br>    ]<br>  },</pre><p>Drag and drop the <strong>Dataraptor Transform Action</strong> from available components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uEYtoyHrKbEsAuHZr5artg.png" /></figure><p>In the image provided, it’s evident that the “GetContacts” operation has been included in the JSON path for sending.</p><p>What does the transformcontacts action does?</p><p>Well, it just transform the JSON and gives us desired JSON. Transform DR validates input JSON to check if email is present, and the returns transformed JSON with true or false.</p><pre>{<br>    &quot;Contact&quot;: [<br>      {<br>        &quot;LastName&quot;: &quot;karu&quot;,<br>        &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>        &quot;FirstName&quot;: &quot;vikranth&quot;,<br>        &quot;NoEmail&quot;: true<br>      }<br>    ]<br>  }</pre><p>Drag and drop <strong>Response Action</strong>.</p><p>Adding the “TransformContacts” node to the send JSON path of the response action signifies that the output of a transformation operation, likely named “TransformContacts,” should be included in the response. The “Response Action” in an Integration Procedure serves various functions: it concludes the IP, appends additional data to the JSON response, facilitates conditional termination, and aids in debugging and data trimming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0610ojsORzhzi0Mm_QPb5A.png" /></figure><p>Preview Integration procedure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPVz-9ct5fcRpEREFU4xOg.png" /></figure><p>Let’s consider a scenario: if the “NoEmail” field is flagged as true, the task is to update a dummy email for that record. To accomplish this, we’ll create a new DataRaptor Load that’s capable of accepting input JSON. Here’s a step-by-step approach:</p><p><strong>Initiate a New DataRaptor Load:</strong></p><ol><li>Head to the DataRaptor section within Salesforce.</li><li>Navigate to the OmniStudio app → OmniStudio Dataraptor.</li><li>Opt for “New DataRaptor Load”.</li><li>Configure the DataRaptor Load to update the contact record with dummy email.</li><li>Below is the sample input json and steps to update.</li></ol><pre>{<br>    &quot;UnqualifiedContact&quot;: [<br>      {<br>        &quot;LastName&quot;: &quot;karu&quot;,<br>        &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>        &quot;FirstName&quot;: &quot;vikranth&quot;<br>      }<br>    ]<br>  }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PWkzzCFryLDU8ABMgm56w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G-5hB_dcZOMOU4AMiW1ZYA.png" /></figure><p>So new lets add this DataRaptor before response action in Integration Procedure.</p><h4>Conditional Block</h4><p>Drag and drop the Conditional block , into the Integration Procedure. This condition block functions as if condition. Within the conditional block, drag and drop the DataRaptor Post action, and add the newly created DataRaptor Load to the Post action. Insert the execution condition formula for conditional block. This formula determines the conditions under which the block or action inside the IP executes. For our scenario, the provided condition is added as follows:</p><pre>%TransformContacts:Contact:NoEmail% == &quot;true&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lkRWiZJy3drg4MUev6VsWA.png" /></figure><p>Therefore, the Conditional block will execute only if the “Noemail” flag is true from the DataRaptor Transform step.</p><p><strong><em>Note: In the image above, there’s a checkbox labeled “If Else Block.” When this checkbox is selected, actions within the Conditional block will function as if-else conditions.</em></strong></p><p>Lets try to execute the IP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVfV225V0LmE6stzTgfr8A.png" /></figure><p>There seems to be an error, do you have any thoughts on what might be causing it? Remember, the DataRaptor Load accepts the JSON format provided below.</p><pre>{<br>    &quot;UnqualifiedContact&quot;: [<br>      {<br>        &quot;LastName&quot;: &quot;karu&quot;,<br>        &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>        &quot;FirstName&quot;: &quot;vikranth&quot;<br>      }<br>    ]<br>  }<br><br>JSON passed from IP?<br> {<br>    &quot;Contact&quot;: [<br>      {<br>        &quot;LastName&quot;: &quot;karu&quot;,<br>        &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>        &quot;FirstName&quot;: &quot;vikranth&quot;<br>      }<br>    ]<br>  }</pre><p>The DataRaptor Load expects the JSON data with a node named “UnqualifiedContact,” but the Integration Procedure is providing input with a node named “Contact.”</p><p>When you add “UnqualifiedContact” under the Send JSON Node in the Load Transform, it serves the purpose of renaming the specified node. In an Integration Procedure (IP), the Send JSON Path is utilized to transmit the designated node of the IP as input to various action components. On the other hand, the Send JSON Node facilitates the renaming of the node specified in the Send JSON Path and sends it as input to the action components.</p><p>Additionally, achieving the same outcome can also be done using Response JSON Path and Response JSON Node. However, this alternative approach requires handling within the Transform Contacts action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nkQIjuKN6kmBcFyUgi62Nw.png" /></figure><p>The action “Renamed ResponseNode1 to Dont Update Contact” will only execute if the “NoEmail” condition is false.</p><p>The action “ContactUpdateSuccessfully” is a response action that executes exclusively within the conditional block.</p><p>In the “Additional Output Response” section, there’s an option to return only additional output. Here, you can include key/value pairs. In our scenario, I have added these below pairs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OPyuaNQc52899ECqUfha7A.png" /></figure><p>and ContactUpdate = true for latter. Final output will be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkXYj93S2fbnq9yqUTFVJw.png" /></figure><p>The “Available Components” panel comprises two sections: “Groups” and “Actions.”</p><p>The “Groups” section contains the following blocks: Cache Block, Conditional Block, Loop Block, and Try Catch Block.</p><p>The “Actions” section includes the following actions:</p><ul><li>Express Set</li><li>Chatter</li><li>DataRaptor Extract</li><li>DataRaptor Transform</li><li>DataRaptor Post</li><li>DataRaptor Turbo</li><li>Delete</li><li>Docusign Envelope Action</li><li>Email Action</li><li>Integration Procedure Action</li><li>Intelligence Action</li><li>List Action</li><li>Decision Matrix Action</li><li>Remote Action</li><li>Response Action</li><li>Http Action</li><li>Set Values</li></ul><p>The Conditional Block example has been covered earlier. Now, let’s delve into the other blocks available.</p><h4><strong>Loop Block</strong></h4><p>Let’s see how Loop Blocks works. In the above given example where the GetContacts operation is expected to return only a single contact, let’s consider what would happen if it were to receive multiple contacts where the email field is null.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EsnVLG-W5Y1Oz12XAMLrxQ.png" /></figure><p>If the GetContacts operation returns multiple contacts, each with a null email field, the DataRaptor Transform would need to iterate over this data to set the NoEmail flag as true for each contact. Then, the transformed data can be passed to the DataRaptor Load to update the contacts with a dummy email address.</p><p>For this I will be using the Loop Block.</p><p>Drag and drop the Loop Block from components panel. Parameters to pass for loop block are</p><ol><li>Loop List : The list that needs to be iterated over. In our scenario, this would be the list obtained from the GetContacts operation. Therefore, the node would be “<strong>GetContacts:Contacts</strong>”.</li><li>Additional Loop Output: This parameter specifies the output to be provided for each iteration of the loop. Since the loop will execute the Transform DataRaptor, each iteration’s output from the Transform DataRaptor should be added to the loop output.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O26G9qlGoO4PMkRsPN9IZw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1f354SmNB6rX4qWcp_t2Tw.png" /></figure><p>So how does the Input is passed as JSON to Loop.</p><pre>{<br>  &quot;ElapsedTime&quot;: 146,<br>  &quot;Type&quot;: &quot;Loop Block&quot;,<br>  &quot;Input&quot;: [<br>    {<br>      &quot;LastName&quot;: &quot;karu&quot;,<br>      &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>      &quot;FirstName&quot;: &quot;vikranth&quot;<br>    },<br>    {<br>      &quot;LastName&quot;: &quot;Davis&quot;,<br>      &quot;Id&quot;: &quot;003F900001giQOCIA2&quot;,<br>      &quot;FirstName&quot;: &quot;Josh&quot;<br>    }<br>  ],<br>  &quot;Status&quot;: true<br>}<br></pre><p>Lets change the Transform DataRaptor Input node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Y42CoySOdQrrB1OImY9nA.png" /></figure><p>Output of Loop after Iteration</p><pre>[<br>  {<br>    &quot;LoopBlockIterationIndex&quot;: 1,<br>    &quot;TransformContactsStatus&quot;: true,<br>    &quot;LoopBlockIterationStatus&quot;: true,<br>    &quot;TransformContacts&quot;: {<br>      &quot;Contact&quot;: {<br>        &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>        &quot;LastName&quot;: &quot;karu&quot;,<br>        &quot;FirstName&quot;: &quot;vikranth&quot;,<br>        &quot;NoEmail&quot;: true<br>      }<br>    }<br>  },<br>  {<br>    &quot;LoopBlockIterationIndex&quot;: 2,<br>    &quot;TransformContactsStatus&quot;: true,<br>    &quot;LoopBlockIterationStatus&quot;: true,<br>    &quot;TransformContacts&quot;: {<br>      &quot;Contact&quot;: {<br>        &quot;Id&quot;: &quot;003F900001giQOCIA2&quot;,<br>        &quot;LastName&quot;: &quot;Davis&quot;,<br>        &quot;FirstName&quot;: &quot;Josh&quot;,<br>        &quot;NoEmail&quot;: true<br>      }<br>    }<br>  }<br>]</pre><p>Now lets us merge the loop output and need output as below.</p><pre>  {<br>    &quot;Contact&quot;: {<br>      &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>      &quot;LastName&quot;: &quot;karu&quot;,<br>      &quot;FirstName&quot;: &quot;vikranth&quot;,<br>      &quot;NoEmail&quot;: true<br>    }<br>  },<br>  {<br>    &quot;Contact&quot;: {<br>      &quot;Id&quot;: &quot;003F900001giQOCIA2&quot;,<br>      &quot;LastName&quot;: &quot;Davis&quot;,<br>      &quot;FirstName&quot;: &quot;Josh&quot;,<br>      &quot;NoEmail&quot;: true<br>    }<br>  }</pre><p>For merging lets use List Action.</p><p><strong>List Action: </strong>List Action in part of the Integration procedure which allows merging, sorting and modifying multiple list of items.</p><ol><li>Merging: Used for combining two or more seperate lists into a single, unified list. Merging list order is in which order we want to display it in response. Advanced merge is used when common identifier is present in two different list which needs to be merged.</li></ol><pre>{<br>   &quot;Account&quot;: [<br>    {<br>      &quot;Id&quot;: &quot;000000001&quot;,<br>      &quot;Name&quot;: &quot;karu&quot;,<br>      &quot;Industry&quot;: &quot;IT&quot;<br>    }<br>  ],<br>  &quot;Contact&quot;:[<br>   {<br>      &quot;AccountId&quot;: &quot;000000001&quot;,<br>      &quot;Email&quot;: &quot;email.com&quot;,<br>      &quot;FirstName&quot;: &quot;Josh&quot;,<br>      <br>    }<br>]<br>}</pre><p>So above two list will be merged to single list as below.</p><pre>{<br>   &quot;FinalList&quot;: [<br>    {<br>      &quot;Id&quot;: &quot;000000001&quot;,<br>      &quot;Name&quot;: &quot;karu&quot;,<br>      &quot;Industry&quot;: &quot;IT&quot;,<br>      &quot;Email&quot;: &quot;email.com&quot;,<br>      &quot;FirstName&quot;: &quot;Josh&quot;,<br>    }<br>  ]<br>}</pre><p>How does the matching happens, from above JSON of contact and account, both has common identifier accountId and Id from account, will this use for matching and merging.</p><p>2. <strong>Sorting: </strong>Sorting the list on specific order, such as alphabetical, numerical or date order. Default is Ascending, after adding the sorting output is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-yFA6atAiRXKZNd-qFjFQ.png" /></figure><pre>[<br>  {<br>    &quot;Contact&quot;: {<br>      &quot;Id&quot;: &quot;003F900001giQOCIA2&quot;,<br>      &quot;LastName&quot;: &quot;Davis&quot;,<br>      &quot;FirstName&quot;: &quot;Josh&quot;,<br>      &quot;NoEmail&quot;: true<br>    }<br>  },<br>  {<br>    &quot;Contact&quot;: {<br>      &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>      &quot;LastName&quot;: &quot;karu&quot;,<br>      &quot;FirstName&quot;: &quot;vikranth&quot;,<br>      &quot;NoEmail&quot;: true<br>    }<br>  }<br>]</pre><p>3. <strong>Modifying:</strong> It is used for making changes to a list structure. Like updating or replacing existing items in the list or removing items from the list.</p><h4><strong>Try-Catch Block</strong></h4><p>Try Catch block is like any other coding technology, used for running the piece of code between in try and catch for any failures.</p><p>Drag and drop the try catch block from available components to structure panel.</p><p>Drag all the steps of Integration Procedure inside the Try-Catch block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WICNBDcT8GRJgIW08vPXog.png" /></figure><p>Drap an Dataraptor Post action, and add DR, dont specify any JSON input and try to execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aBfZ113aKUl_BZO5ce4ZTg.png" /></figure><p>Lets generalize the error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JvthHTVTn6TxWXDFcnsfGg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*yVhVOaloPcrUV3cD8IrylA.png" /></figure><h4>Cache Block</h4><p>Leveraging a cache to store data that’s frequently accessed yet updated infrequently can notably boost performance by minimizing database round trips. Cache Blocks prove valuable when some segments of the Integration Procedure alter data or when varying cached data require distinct expiration times. For instance, current weather information may undergo more frequent changes compared to user session data.</p><p>Cache block saves the output of step to Org or Session cache in the VlcityAPIResponse cache partition for quick retrieval.</p><p>Ignore Cache: This setting, with a default value of true, refrains from either clearing or saving data to the cache. It’s employed to test Integration Procedure steps devoid of any potential interference from caching effects..</p><p>ResetCache: With a default value of false, this setting compels data to be stored in the cache. It’s utilized primarily in testing caching mechanisms.</p><p>More about cache can be seen <a href="https://help.salesforce.com/s/articleView?id=sf.os_enhance_performance_using_cache_blocks_48810.htm&amp;type=5">here</a>.</p><h4>Set Values Action</h4><p>Set values action sets values in the data JSON of an Integration Procedure literally, using merge fields, or using formulas. In the Integration Procedure, drag and drop the set contact values.</p><p>Set values are used if we want to set some variables inside node, it supports formulas as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqM8psZUzWhb2ObGP8oXFg.png" /></figure><p>Add firstname and last name to set values, and pass SetValues node to UpdateContact_DR to update a contact.</p><p>In response action show the output of UpdateContact_DR.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4kRfk8UUciNrhJ5NwRNpeQ.png" /></figure><h4>Delete Action</h4><p>This action is used to delete the sObject records from salesforce. Drag and drop the delete action from available components to the structure panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrBMEZAp76TrlUTQbEcQFA.png" /></figure><p>Select the SObject, for which records needs to be deleted. <em>Path To Id </em>is where Ids to delete is mentioned. Such as Node:Ids.</p><p>Example : { &quot;Account&quot;: { &quot;accId&quot;: [&quot;001f400000EPQ8o&quot;, &quot;001f400000BAkbn&quot;] } } then path will be %Account:accId%.</p><p>Add Delete Action data to Response Action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4x79rjxKSbwIe5fa4nC-A.png" /></figure><h4>Email Action</h4><p>This action is used to send an email using Integration procedure. This uses Salesforce Email API. Need to specifiy the email template, email target object id, what id, org wide email address etc.</p><h4>Integration Procedure</h4><p>This is used to invoke an other Integration Procedure.</p><p>Create an new Integration Procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avJvKl77UCHo5fNONligkA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFqFcDpytmJQcAsDDIsQzg.png" /></figure><p>Add Response Action to display the output in parent Integration Procedure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3VnqANPi0fXNOFxhxlbbFg.png" /></figure><p>Remote Options? This is used to add extra data to Integration Procedure.</p><p>Disable Chainable: This is used to disable chainable settings of child IP, if specified.</p><p>Remote Options: Specifies additional properties for Integration Procedure.</p><p>Output will be shown as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FZbFYIeZZ4g2M2KWSHeBBg.png" /></figure><h4>Intelligence Action</h4><p>This action is used to run Vlocity Intelligence Machine. Will discuss about this in separate post.</p><h4>Decision Matrix Action</h4><p>This is used when, some data needs to be returned to IP, based on Input provided. Like example if a customer is qualified for the discount based on tier value, this configuration can be loaded in decision matrix. Will discuss about this in separate post.</p><h4>Remote Action</h4><p>If there is a requirement of calling Apex class in Integration Procedure, the use Remote Action.</p><p>Lets have a simple use cases, User enters First Name, Last Name and Email. Then will use Apex class to check if duplicate is present, then returns the duplicate record, if no duplicate is found, insert and return record details.</p><p>Create an Apex Class, with Interface Callable.</p><pre>global class HelperIntegrationClass implements Callable {<br>    public Object call(String action, Map&lt;String, Object&gt; args) {<br>        Map&lt;String, Object&gt; input = (Map&lt;String, Object&gt;)args.get(&#39;input&#39;);<br>        Map&lt;String, Object&gt; output = (Map&lt;String, Object&gt;)args.get(&#39;output&#39;);<br>        Map&lt;String, Object&gt; options = (Map&lt;String, Object&gt;)args.get(&#39;options&#39;);<br>        return invokeMethod(action, input, output, options);<br>    }<br>    private Object invokeMethod(String action, Map&lt;String,Object&gt; input, <br>                                Map&lt;String,Object&gt; output, Map&lt;String,Object&gt; options) <br>    {  <br>        List&lt;Contact&gt; lCon = new List&lt;Contact&gt;();<br>        if(action == &#39;Insert&#39;)<br>        {<br>   String firstName = (String)input.get(&#39;FirstName&#39;);  <br>            String lastName = (String)input.get(&#39;LastName&#39;);      <br>            String email = (String)input.get(&#39;Email&#39;);<br>            <br>            lCon = [Select Id,FirstName,LastName,Email from Contact Where FirstName =: firstName <br>                                 AND LastName =: lastName AND Email =: email];<br>            if(lCon.isEmpty())<br>            {<br>                Contact con = new Contact();<br>                con.LastName = lastName;<br>                con.FirstName = firstName;<br>                con.Email = email;<br>                lCon.add(con);<br>                insert lCon;<br>            }<br>        }<br>        return output.put(&#39;result&#39;,lCon);    <br>    } <br>}</pre><p>Default method is call which accepts parameter action, and input data type as defined above.</p><p>Code returns the output back to Integration Procedure.</p><ol><li>Create an Integration Procedure.</li><li>Drag and drop set values and add FirstName, LastName and Email.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2bSfmRBtcC8wZv7p_ccjg.png" /></figure><p>3. Drag and drop Remote Action, and specify Remote Class name and Remote Method name.</p><p>4. Value for Remote Class name is <em>HelperIntegrationClass</em> and value for Remote Method will be <em>‘Insert’ </em>which we have specified in apex class action param.</p><p>5. Pass the InputSet step json node to Send JSON path of Remote Action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntW2IwqHBXW_8kD4Dz_OMQ.png" /></figure><p>6. Additional Input can also be sent, if required.</p><p>7. Drag and drop the Response Action.</p><p>Output will be as below.</p><p>If existing contact details are entered then response will be null, if new details are entered, new record is created and returns recordId.</p><pre>{<br>  &quot;error&quot;: &quot;OK&quot;,<br>  &quot;errorCode&quot;: &quot;INVOKE-200&quot;,<br>  &quot;result&quot;: [<br>    {<br>      &quot;Id&quot;: &quot;003F900001d8MRZIA2&quot;,<br>      &quot;Email&quot;: &quot;rose123@edge.com&quot;,<br>      &quot;FirstName&quot;: &quot;Rose123N&quot;,<br>      &quot;LastName&quot;: &quot;Gonzalez123N&quot;,<br>      &quot;attributes&quot;: {<br>        &quot;url&quot;: &quot;/services/data/v60.0/sobjects/Contact/003F900001d8MRZIA2&quot;,<br>        &quot;type&quot;: &quot;Contact&quot;<br>      }<br>    }<br>  ]<br>}</pre><h4>HTTP Action</h4><p>This is used to make an external API call, mention HTTP URL, Method, Named Credential, Timeout, Send Body, Retry Count etc.. Will discuss about this in separate post.</p><p>Expose integration procedure as Rest Api.</p><p>This can be used as Get Action and Post Action. Will use workbench for this demo.</p><p>URL format to use Rest API will be {baseURL}/services/apexrest/{namespace}/v1/integrationprocedure/{Type}_{SubType}/</p><p>Lets use the medium01 Integration Procedure for Get Action.</p><p>Open workbench → Utilities → Rest API → Get</p><p>/services/apexrest/omnistudio/v1/integrationprocedure/medium_demoip1</p><p>Execute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YonUpkCslaAthqeueLDPig.png" /></figure><p>Inline query, now lets use the IPWithApex Integration Procedure which we have created earlier in restAPI. For inline query, we can add the Parameters directly to URL in Get Method.</p><p>/services/apexrest/omnistudio/v1/integrationprocedure/Remote_CallIn/?FirstName=’Vikranth’&amp;LastName=’Karu’</p><p>Response</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxcUKnfgHEyIPCvaC17d7Q.png" /></figure><p>For Post API. URL will be /services/apexrest/omnistudio/v1/integrationprocedure/Remote_CallIn/ and request as below format.</p><pre>{<br>    &quot;FirstName&quot;: &quot;Rose123N&quot;,<br>    &quot;LastName&quot;: &quot;Gonzalez123N&quot;,<br>    &quot;Email&quot;: &quot;rose123@edge.com&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5pfG55CSM-sqsPLnerK7vQ.png" /></figure><p>Common Integration Procedure Action Properties:</p><ol><li>Element Name: Label of script element.</li><li>Send JSON Path: Used for trimming the JSON node.</li><li>Send JSON Node: Reparenting the JSON node.</li><li>Response JSON Node: Trimming the output of JSON Node.</li><li>Send Only Additional Input: If is selected, then accepts only the data in Additional Output.</li><li>Additional Input: Includes key/value pair in input JSON node.</li><li>Return Only Additional Output: If selected, returns only the data in Additional Ouput property.</li><li>Additional Output: Includes key/value pair in output JSON node.</li><li>Send Only Failure Response: If selected, returns only the Failure response if the action fails.</li><li>Failure Response: Key/value pairs to be returned in output data.</li><li>Execution Conditional Formula: Formula to run before the step to execute, if true step is executed else not.</li><li>Failure Conditional Formula: Custom failure condition is specified.</li><li>Fail On Step Error: If set to True, the Integration Procedure ends if the step fails.</li><li>Chain On Step: This is useful, when action needs to run in its own transaction, and helpful in maintaining the governor limits.</li><li>Additional Chainable Response: Accepts key/value pair.</li><li>Action Message: Sends a message to the user if this is the first action message in the Integration Procedure or if the action is chained. Useful for long running actions.</li><li>Internal Notes: Descriptive text that only someone who is viewing the Integration Procedure in the Vlocity Integration Procedure app sees.</li></ol><h4>Best Practices</h4><ol><li>Use Integration Procedure for all data calls to salesforce.</li><li>Trim the data returned by using Response Action.</li><li>Use execution condition formula and only execute required steps.</li><li>For asynchronous Integration Procedure use Future , Non Blocking, Fire and Forgot.</li><li>Use cache in case of frequent data.</li></ol><p><em>Follow me on linkedIn: </em><a href="https://www.linkedin.com/in/vikranth-karollu-hanumanth-2b1922164/"><em>Vikranth Karollu Hanumanth</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=04d11d61c5f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Omnistudio — Dataraptors]]></title>
            <link>https://vikranthkaru.medium.com/omnistudio-dataraptors-9ece72f102b1?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ece72f102b1</guid>
            <category><![CDATA[dataraptor]]></category>
            <category><![CDATA[vlocity]]></category>
            <category><![CDATA[salesforce-vlocity]]></category>
            <category><![CDATA[omnistudio]]></category>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 19:22:15 GMT</pubDate>
            <atom:updated>2024-03-24T12:30:45.678Z</atom:updated>
            <content:encoded><![CDATA[<h3>Omnistudio — Dataraptors</h3><h3>What is Dataraptor?</h3><p>Dataraptor is a tool within the Salesforce part of OmniStudio/ Vlocity developed for reading, transformation, and writing of Salesforce data. It falls under the category of low-code/no-code tools, which means it allows users to perform these operations without extensive coding knowledge.</p><p>The primary functions of Dataraptor include:</p><ol><li>Insert/Update Operations: Dataraptor enables users to insert or update Salesforce data, which means adding new records or modifying existing ones.</li><li>SOQL Queries: Users can perform SOQL queries to retrieve data from Salesforce objects.</li><li>Data Transformation: Dataraptor has the capability to transform data between different formats such as XML to JSON, JSON to PDF, Document, XML, etc.</li></ol><p>Dataraptors are categorized into four main types:</p><ol><li><strong>Turbo Extract: </strong>This type retrieves data from a single Salesforce object. It is particularly useful for scenarios where a filter condition, such as an identifier, is applied to fetch specific data quickly. Turbo Extracts have simpler configurations and better runtime performance but do not support formulas or complex output mappings.</li><li><strong>Extract: </strong>This type retrieves data from one or more Salesforce objects. It is more versatile than Turbo Extract and can handle a broader range of use cases.</li><li><strong>Load:</strong> Load Dataraptors are responsible for saving data to one or more Salesforce sObjects. They can perform operations like updating existing records, creating new records, or migrating CSV data into Salesforce records.</li><li><strong>Transform:</strong> Transform Dataraptors manipulate data, either from within or outside Salesforce. They can perform operations such as trimming, mapping, restructuring, and transforming data in JSON, XML, or custom schemas. Formulas and functions can be utilized for data transformation.</li></ol><h4><strong>DataRaptor Turbo Extract</strong></h4><blockquote>Dataraptor Turbo Extract retrieves data from the object, and provides output. Dataraptor’s accepts input and provides output. I/p and O/p can be XML, Custom and JSON.</blockquote><blockquote>In Turbo Extract, there are 3 tabs, Extract, Options, Preview.</blockquote><blockquote><strong>Extract:</strong> On the extract tab, specify the salesforce object, that needs to query. Can also add filter to query, and specify the fields to extract.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evkOpqH912FN8rCsTj_YVA.png" /></figure><blockquote><strong>Preview: </strong>It is used to preview the dr.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nx46joKYMfOV8oO_rh7Krg.png" /></figure><blockquote>Some important points for dataraptor. <strong><em>Can only fetch the data from single object and its parents data. To filter for null, use $Vlocity.null, Can travserse upto five parent levels. When select custom as input for DR, provide the input class. Like csv as input, because it supports only xml and json, for anyother inputs customapex can be used.</em></strong></blockquote><h4><strong>DataRaptor Extract</strong></h4><blockquote>In dataraptor extract there are 4 tabs.</blockquote><blockquote>Extract, Formula, Output, Options and Preview. Lets go each of module individually.</blockquote><blockquote><strong>Extract Tab</strong>: It is used to specify the Salesforce Objects for querying, can add multiple Objects. Lets add query to fetch the Account and Related Contacts.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Mh9H2AnF2ZIne-s-v4zew.png" /></figure><blockquote>Lets decode the above declaration. 1st block is to fetch the account, and defined its output name result as accounts as we can see on right side.</blockquote><blockquote>To fetch the related contacts, and place it inside the node of accounts, mapped the o/p path of contact as accounts:contacts and passed the account id as a query filter to contact.</blockquote><blockquote>3rd block is fetching cases and is independent of above two blocks, so we can see it is placed below account node.</blockquote><blockquote><strong>Output: </strong>To map data from the extraction step JSON to the output JSON, use o/p tab.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ya6VFjOrAbeRjA_9Z5Nh6A.png" /></figure><blockquote>Use + tab to create the O/p json path.</blockquote><blockquote><strong>Options: </strong>Check field Level Security: Checks user permission for the fields, enforce field level security.</blockquote><blockquote>Overwrite Target for All Null Inputs: This make sure that an o/p nude is created regardless of wether a field is null.</blockquote><blockquote>Time to live in minutes: If data caching is enabled , determines how long data remains in cache. The minimum value is 5.</blockquote><blockquote>Session Platform Cache Type: Session Cache for data related to users and their login sessions, Org cache for all other types of data.</blockquote><p><strong>Preview</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M5L3W83iSrpfZFuOk5syTg.png" /></figure><blockquote>As we can see the desired o/p as declared during the Extract JSON path and O/p json path is achieved.</blockquote><h4>DataRaptor Load</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TidfrLzfUlKCiMTx8BC3w.png" /></figure><blockquote>When creating the load dataraptor, need to define some parameters.</blockquote><blockquote><strong>Batch Size:</strong> Number of records to be processed. (1–2000).</blockquote><blockquote><strong>Input Type:</strong> JSON, XML or Custom (Apex based).</blockquote><blockquote><strong>Output Type:</strong> JSON always.</blockquote><blockquote>Load DR consists of Object which is described earlier, Formulas, Fields, Options and Preview.</blockquote><blockquote><strong>Objects:</strong> Need to specifiy the salesforce object, so now we will be creating the account and its related contact. So there is an option to link the Account record with contact, inshort after account is created id is auto passed to contact’s accountid.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aAO853UHjQs0BQChFb1P0g.png" /></figure><blockquote><strong>Fields: </strong>Fields tab is used to map the salesforce object fields to json, this can also used for upsert.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H19MAeXhF2NUN34atYqCxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3VuLHtJSvq_hQ1IuDUD7w.png" /></figure><blockquote>As we can see accountId is linked to contact automatically as it was linked in object tab.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uACGabaCrUNcTVFPHIWu-A.png" /></figure><h4>Dataraptor Transform</h4><blockquote>Used for transforming data without reading from or writing to salesforce.</blockquote><blockquote>Convert JSON into XML or vice versa.</blockquote><blockquote>Convert data to PDF, Docusign or Document Template format. Will learn about data transform of above type in separate module, which we will be related to Document Generation.</blockquote><blockquote>We will see how to convert JSON to JSON.</blockquote><blockquote>JSON to JSON: In this use case, for given JSON will check if there is an email, and add new element to JSON, NoEmail (True if email is not present and false if email is present).</blockquote><blockquote>Let us create formula to check if email is present.</blockquote><blockquote>Sample input JSON:</blockquote><pre>{<br>    &quot;Contact&quot;: [<br>        {<br>            &quot;LastName&quot;: &quot;karu&quot;,<br>            &quot;Id&quot;: &quot;003F900001d8F2QIAU&quot;,<br>            &quot;FirstName&quot;: &quot;vikranth&quot;,<br>            &quot;Email&quot;:&quot;vickyvikranth016@gmail.com&quot;<br>        }<br>    ]<br>}</pre><blockquote>In formula field ISBLANK(%Contact:Email%), use % % for dynamic field value.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0OXPqVIyDP41GxuQro6Ahg.png" /></figure><blockquote>Give formula result path an identifier. Will be using this identifier in transform node.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKBzT1egHEJpS8PWMbncDQ.png" /></figure><blockquote>Input data is JSON object name Contact, and o/p is same as we are not transforming the JSON, but will add new NoEmail key as part of JSON.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZ30WmVGz-TXLBk9usCq2g.png" /></figure><blockquote>Input JSON path will be the formula o/p name, and in o/p json path we are adding this new key.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkPl1F07FInF7SyMQjOiIA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vhc7_N_vcO1n_ockxY3Dcw.png" /></figure><blockquote>As we can see the o/p in both scenarios with true and false.</blockquote><blockquote><strong>Required Permissions: </strong>This determines who has runtime access for Integration procedures and data raptors, if this is blank any user can run the DR or IP. If an IP is calling DR, or an IP is calling IP then permissions of calling IP is considered.</blockquote><blockquote>Required Permissions can have roles, profiles, permission sets, custom permissions or any combination. Example: PermSet: AdminSet, Role: Admin etc..</blockquote><p><strong>In upcoming article, will give an examples of Integration Procedure, Omniscripts, Flexcards and Rest API’s in OmniStudio.</strong></p><p><em>Follow me on linkedin: </em><a href="https://www.linkedin.com/in/vikranth-karollu-hanumanth-2b1922164/"><em>Vikranth Karollu Hanumanth</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ece72f102b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Salesforce Web Server Flow Using OAuth]]></title>
            <link>https://vikranthkaru.medium.com/salesforce-web-server-flow-using-oauth-3631f356dfd2?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/3631f356dfd2</guid>
            <category><![CDATA[salesforce-oauth-flow]]></category>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Sun, 21 Jan 2024 21:39:13 GMT</pubDate>
            <atom:updated>2024-01-21T21:39:13.973Z</atom:updated>
            <content:encoded><![CDATA[<h3>OAuth Topic Part — 1</h3><p>What is OAuth?</p><blockquote>OAuth is an open-standard protocol or framework that provides applications the ability for secure designated access. OAuth 2.0, which stands for “Open Authorization”, is a standard designed to allow a website or application to access resource hosted by other web apps on behalf of a user. Although the web is main platform for OAuth 2, this can be used for browser based applications, server side web applications, native mobile/apps, connected devices etc..</blockquote><blockquote>Example of an OAuth in real time : For example you can tell Facebook that its ok for espn.com to access your profile or post updates on your timeline without having to give ESPN your Facebook password</blockquote><blockquote>OAuth 2.0 is an authorization protocol and not an authentication protocol. Authorization decides what the users can access. Example to view the account information, or access the custom lightning web component.</blockquote><blockquote>OAuth 2.0 uses an Access Token.</blockquote><blockquote>An Access Token is a string that the OAuth client uses to make requests to the resource server. Access Tokens may be either “bearer tokens” or “sender-constrained tokens”.</blockquote><blockquote>Bearer Token is an opaque string, does not have any meaning to clients using it. It can be of format hexadecimal characters, while others may use structured token such as JSON Web Token. If Bearer Token gets into the hands of unauthorized actors, they can impersonate the user and get unauthorized access to the protected resources. The resource server cannot determine if the sender of a Bearer Token is legit or not as long as token is valid.</blockquote><blockquote>A solution of this problem is Sender Constrained Tokens. This is a type of mechanisms that ensures that only the authorized sender can use a particular access token to access protected resources. Such examples are as below.</blockquote><blockquote><a href="https://datatracker.ietf.org/doc/html/rfc8705">OAuth 2.0 Mutual-TLS Client Authentication and Certificate-Bound Access Tokens</a></blockquote><blockquote><a href="https://datatracker.ietf.org/doc/html/draft-ietf-oauth-dpop">OAuth 2.0 Demonstrating Proof-of-Possession at the Application Layer (DPoP)</a></blockquote><blockquote>In OAuth 2.0 there are 4 roles which participate in the OAuth 2.0 authorization cycle.</blockquote><blockquote>Resource Owner: The user or system that owns the protected resource and can grant access to them. In our use cases this is Salesforce and its user.</blockquote><blockquote>Client: The client is the system that requires access to the protected resources. To access resources, the client must hold the appropriate Access Token. It can be web application, such as external application or salesforce itself or mobile application.</blockquote><blockquote>Authorization Server: This server receives requests from the client for access tokens and access token is issued if authentication is success and consent by resource owner. Authorization server exposes two end points. The Authorization Endpoint, which handles the authorization and consent of the user, and the token end point which is involved in a machine to machine interaction. This is salesforce url.</blockquote><blockquote>Resource Server: A server that protects the users resources and receive access request from client, it accepts and validates access token from the client and returns the appropriate resource to it. This will be salesforce rest api url.</blockquote><blockquote>OAuth 2.0 Scopes: This are used to specify type of protected resources that the connected app can access.</blockquote><blockquote>Authorization Code is returned from authentication url, this code is used to exchange for Access Token.</blockquote><blockquote>In this module we will go through Web Server Flow.</blockquote><blockquote>Use case, we are using custom Node.Js application, User needs to fetch the account owned by them. User lands to OAuth Web Flow tab. User initiate the Web flow by clicking on Accounts button. All the accounts owned by user will be displayed in table format.</blockquote><blockquote>Using OAuth Web App.</blockquote><blockquote>Create a folder in your local from vs code.</blockquote><blockquote>mkdir oauthwithsalesforce.</blockquote><blockquote>cd oauthwithsalesforce.</blockquote><blockquote>code .</blockquote><blockquote>create a file app.js</blockquote><blockquote>node install.</blockquote><blockquote>npm install express.</blockquote><blockquote>npm install nodemon.</blockquote><blockquote>npm install jsforce.</blockquote><blockquote>npm install dotenv.</blockquote><blockquote>npm save.</blockquote><blockquote>npm install ejs.</blockquote><blockquote>The code can be copied from my <a href="https://github.com/vikranthkaru/oauthwithsalesforce">github</a>.</blockquote><blockquote>I have used Render for hosting apps.</blockquote><blockquote>how to deploy node app to render site : <a href="https://www.freecodecamp.org/news/how-to-deploy-nodejs-application-with-render/">https://www.freecodecamp.org/news/how-to-deploy-nodejs-application-with-render/</a></blockquote><blockquote>Well our basic node js app is ready and up and running on render.</blockquote><blockquote>But how does it will talk to salesforce, remember our aim is here to demo oAuth flow, so we are good if OAuth works.</blockquote><blockquote>First create a Connected App in salesforce.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6vi3v8kQE9Vt4YRgnpG7g.png" /></figure><blockquote>Enable OAuth Settings, and add callback url as some randow value, we will change it later.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EW96HQQKdaCtQhyZLEIJNw.png" /></figure><blockquote>Check the PKCE extension, we will see it about some time later.</blockquote><blockquote>Well copy the consumer secret and consumer key from connected app and save it on some other place for time being.</blockquote><pre><br>var express = require(&#39;express&#39;);<br>var http = require(&#39;http&#39;);<br>var jsforce = require(&#39;jsforce&#39;);<br>var fs = require(&#39;fs&#39;);<br>var ejs = require(&#39;ejs&#39;);<br>var app = express();<br>app.set(&#39;port&#39;, process.env.PORT || 3001);<br>app.use(express.urlencoded({ extended: true }));<br>app.set(&#39;view engine&#39;, &#39;ejs&#39;);<br>app.get(&#39;/&#39;, (req, res) =&gt; {<br>    const data = {<br>        displayButton: true,<br>        displayContext: false<br>    };<br>    res.render(&#39;pages/webserverflow&#39;, {data, activeTab: &#39;OAuth Web Flow&#39;});<br>})<br><br>const crypto = require(&#39;crypto&#39;);<br><br>function base64UrlEscape(str) {<br>    return str.replace(/\+/g, &#39;-&#39;).replace(/\//g, &#39;_&#39;).replace(/=/g, &#39;&#39;);<br>}<br><br>const codeVerifier = base64UrlEscape(crypto.randomBytes(32).toString(&#39;base64&#39;));<br>const codeChallenge = base64UrlEscape(crypto.createHash(&#39;sha256&#39;).update(codeVerifier).digest(&#39;base64&#39;));<br>var instantceURL;<br>var accessToken;<br>app.get(&#39;/oauthcallback&#39;, function (req, res) {<br>    const oauth2 = new jsforce.OAuth2({<br>        clientId: process.env.CONSUMER_KEY,<br>        clientSecret: process.env.CONSUMER_SECRET,<br>        redirectUri: process.env.REDIRECT_URI<br>    });<br>    const conn = new jsforce.Connection({ oauth2: oauth2 });<br>    conn.authorize(req.query.code, { code_verifier: codeVerifier }, function (err, userInfo) {<br>        if (err) {<br>            return console.error(err);<br>        }<br>        instantceURL = conn.instanceUrl;<br>        accessToken = conn.accessToken;<br>        const conn2 = new jsforce.Connection({<br>            instanceUrl: conn.instanceUrl,<br>            accessToken: conn.accessToken<br>        });<br>        const restApiEndpoint = `${conn.instanceUrl}/services/data/v53.0/query/?q=SELECT+Id,Name+FROM+Account`;<br>        conn2.request(restApiEndpoint, function (err, result) {<br>            if (err) {<br>                console.error(err);<br>                res.status(500).json({ error: &#39;Internal Server Error&#39; });<br>                return;<br>            }<br>    <br>            // Process and send the account details to the client<br>            const account = result.records.map(account =&gt; {<br>                return {<br>                    id: account.Id,<br>                    name: account.Name<br>                };<br>            });<br>            const data = {<br>                accounts:account,<br>                displayButton: false,<br>                displayContext: true<br>            }<br>            const response = res;<br>            response.render(&#39;pages/webserverflow&#39;, { data ,  activeTab: &#39;OAuth Web Flow&#39;});<br>        });<br>    });<br>});<br><br>app.post(&#39;/oauthconn&#39;, (req, res) =&gt; {<br>    const oauth2 = new jsforce.OAuth2({<br>        clientId: process.env.CONSUMER_KEY,<br>        clientSecret: process.env.CONSUMER_SECRET,<br>        code_challenge_method: &#39;S256&#39;,<br>        code_challenge: codeChallenge,<br>        redirectUri: process.env.REDIRECT_URI,<br>    });<br>    const authorizationUrl = oauth2.getAuthorizationUrl({}) + `&amp;code_challenge=${encodeURIComponent(codeChallenge)}`;<br>    res.redirect(authorizationUrl);<br>});<br><br>app.get(&#39;/flow&#39;, (req, res) =&gt; {<br>    const flowName = req.query.flow;<br>    res.render(&#39;pages/userAgentFlow&#39;, { activeTab: flowName });<br><br>});<br><br>http.createServer(app).listen(app.get(&#39;port&#39;), () =&gt; {<br>    console.log(&#39;Express server listening on port &#39; + app.get(&#39;port&#39;));<br>});</pre><blockquote>app.post(‘/oauthconn’, (req, res) =&gt; {<br> const oauth2 = new jsforce.OAuth2({<br> clientId: process.env.CONSUMER_KEY,<br> clientSecret: process.env.CONSUMER_SECRET,<br> code_challenge_method: ‘S256’,<br> redirectUri: process.env.REDIRECT_URI,<br> });<br> const authorizationUrl = oauth2.getAuthorizationUrl({}) + `&amp;code_challenge=${encodeURIComponent(codeChallenge)}`;<br> res.redirect(authorizationUrl);<br>});</blockquote><blockquote>This above code will initiate when Fetch Account button is clicked on UI. Consumer Key and Consumer Secret are from connected app, redirect uri we will come back to later, just add as Redirect_URI (as this values will be coming from render environment variables.</blockquote><blockquote>There are two parameters code_challenge and code_challenge_method, well these are used for Proof Key for Code Exchange (PKCE).</blockquote><blockquote>This is an additional security layer for OAuth, PKCE makes sure that the client that initiated the flow is the same client that completes the flow. Looks confusing, maybe but concept is really simple.</blockquote><blockquote>A random string is created, known as code verifier, then this value is hashed by using SHA-256 algorithim which is known as code_challenge that is sent to the Authorization server.</blockquote><blockquote>After succesfully authorized, to request the access token, client server will send the Authorization Code with Code_Verifier.</blockquote><blockquote>Below code is used to generate the Code Verifier and its hash value.</blockquote><pre>function base64UrlEscape(str) {<br>    return str.replace(/\+/g, &#39;-&#39;).replace(/\//g, &#39;_&#39;).replace(/=/g, &#39;&#39;);<br>}<br><br>const codeVerifier = base64UrlEscape(crypto.randomBytes(32).toString(&#39;base64&#39;));<br>const codeChallenge = base64UrlEscape(crypto.createHash(&#39;sha256&#39;).update(codeVerifier).digest(&#39;base64&#39;));</pre><blockquote>After the User has Authorized the request, redirect uri will redirect to specified url, this is callback url in the connected call back.</blockquote><pre>app.get(&#39;/oauthcallback&#39;, function (req, res) {<br>    const oauth2 = new jsforce.OAuth2({<br>        clientId: process.env.CONSUMER_KEY,<br>        clientSecret: process.env.CONSUMER_SECRET,<br>        redirectUri: process.env.REDIRECT_URI<br>    });<br>    const conn = new jsforce.Connection({ oauth2: oauth2 });<br>    conn.authorize(req.query.code, { code_verifier: codeVerifier }, function (err, userInfo) {<br>        if (err) {<br>            return console.error(err);<br>        }<br>        instantceURL = conn.instanceUrl;<br>        accessToken = conn.accessToken;<br>        const conn2 = new jsforce.Connection({<br>            instanceUrl: conn.instanceUrl,<br>            accessToken: conn.accessToken<br>        });<br>        const restApiEndpoint = `${conn.instanceUrl}/services/data/v53.0/query/?q=SELECT+Id,Name+FROM+Account`;<br>        conn2.request(restApiEndpoint, function (err, result) {<br>            if (err) {<br>                console.error(err);<br>                res.status(500).json({ error: &#39;Internal Server Error&#39; });<br>                return;<br>            }<br>    <br>            // Process and send the account details to the client<br>            const account = result.records.map(account =&gt; {<br>                return {<br>                    id: account.Id,<br>                    name: account.Name<br>                };<br>            });<br>            const data = {<br>                accounts:account,<br>                displayButton: false,<br>                displayContext: true<br>            }<br>            const response = res;<br>            response.render(&#39;pages/webserverflow&#39;, { data ,  activeTab: &#39;OAuth Web Flow&#39;});<br>        });<br>    });<br>});</pre><blockquote><strong>/oauthcallback is used when redirect happens after the authorization is successful, this parameter will append to the url generated by render.com later.</strong></blockquote><blockquote>Deploy the code to github. Login to render.com using the github.</blockquote><p>Now select the project to deploy to render.com. It generates an url. This url is used to access node js application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*zmf_g-WIJ5w7i7Smr1pGWQ.png" /></figure><blockquote>Add this url to callback url on connected call back with the string mentioned above <a href="https://oauthwithsalesforce.onrender.com/oauthcallback">https://oauthwithsalesforce.onrender.com/oauthcallbac</a>k</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5q9wIEBKq7EnPqEIDy-iyQ.png" /></figure><blockquote>Add Environment variables in the render.com. This environment variables are passed as process.env.EnvironmentVariableName in our node.js application.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ShyAy9e_aFlusnmIp38Azw.png" /></figure><blockquote>Now our Web app is ready. Lets test it.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zl3t_pDebkY3V64TAz35sQ.png" /></figure><blockquote>On click of fetch Account, user is redirected to salesforce login page.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*iJd_SkLb6-6OlOp5WMCxaQ.png" /></figure><blockquote>Enter login details, and authorization completes succesfully and account details are displayed.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Up0TyGA_XPg_rS8ivZrMTw.png" /></figure><blockquote><em>Code can be found on my GitHub : </em><a href="https://github.com/vikranthkaru/oauthwithsalesforce"><em>vikranthkaru/</em>oauthwithsalesforce</a><em>.</em></blockquote><blockquote>Follow me on linkedin: <a href="https://www.linkedin.com/in/vikranth-karollu-hanumanth-2b1922164/">https://www.linkedin.com/in/vikranth-karollu-hanumanth-2b1922164/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3631f356dfd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GraphQL in LWC]]></title>
            <link>https://vikranthkaru.medium.com/graphql-in-lwc-cb21c4045efd?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb21c4045efd</guid>
            <category><![CDATA[graphql-lwc]]></category>
            <category><![CDATA[graphql-related-objects]]></category>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Sun, 24 Dec 2023 20:45:47 GMT</pubDate>
            <atom:updated>2023-12-24T20:45:47.063Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>What is GraphQL?</blockquote><blockquote>By definition GraphQL is a query language for APIs (Application Programming Interfaces) and a runtime environment for executing those queries against your data.</blockquote><blockquote>GraphQL is available in LWC as wire adapter. Using this wire adapter query can be constructed on objects and fetch the data. It considers Object level and field level security.</blockquote><blockquote>To use the adapter in LWC, import gql and graphQL adapters. Query needs to be passed in gql function.</blockquote><blockquote>import { gql, graphql } from “lightning/uiGraphQLApi”;</blockquote><blockquote>How to construct graphql query. GraphQL requires following parameter</blockquote><blockquote>Query: Constructed in gql format using template literals format (`).</blockquote><pre> query: gql`<br>      query AccountWithName {<br>        uiapi {<br>          query {<br>            Account(first: 10) {<br>              edges {<br>                node {<br>                  Id<br>                  Name {<br>                    value<br>                  }<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }`</pre><blockquote>Variables: A key, value pair of dynamic values, and to be used with getter function, so wire adapter can react to changes.</blockquote><pre>    get variables() {<br>        return {<br>            searchKey: this.searchKey === &#39;&#39; ? &#39;%&#39; : `%${this.searchKey}%`<br>        };<br>    }</pre><blockquote>OperationName: Name of the operation on query. Declare it as below</blockquote><blockquote>query operationName.</blockquote><blockquote>This helps in debugging on the server side to identify GraphQL requests.</blockquote><pre> query: gql`<br>      query operationName {<br>        uiapi {<br>          query {<br>            Object_Name(first: 10) {<br>              edges {<br>                node {<br>                  Id<br>                  Field_Name {<br>                    value<br>                  }<br>                }<br>              }<br>            }<br>          }<br>        }<br>      }<br>    }`,<br>  })</pre><blockquote><strong>Before we proceed further with a use case, below are limitations of GraphQL Api</strong></blockquote><blockquote>Experience Cloud sites</blockquote><blockquote>Dynamic construction of GraphQL queries at runtime, such as referencing a fragment from another component</blockquote><blockquote>String interpolation constructs using ${}</blockquote><blockquote>Using variables in <a href="https://graphql.org/learn/queries/#directives">directives</a> such as @skip and @include</blockquote><p><strong>Use Case: Display the All accounts and related contacts and cases.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRpkAc-MytLtK-LiVYgjiQ.png" /></figure><blockquote>Create an LWC Component with name GraphQLWithRelatedObjects.</blockquote><pre>import { LightningElement,wire,track,api } from &#39;lwc&#39;;<br>import { gql, graphql, refreshGraphQL } from &quot;lightning/uiGraphQLApi&quot;;<br><br>const DELAY = 300;<br>export default class GraphQLWithRelatedObjects extends LightningElement {<br>    pageSizeOptions = [5,10,15,20];<br>    accounts;errors;graphqlQueryResult;<br>    searchKey = &#39;&#39;;<br>    @track displayaccounts=[];<br>    @wire(graphql, {<br>        query: gql`<br>        query getAccountAndRelatedbjects($searchKey: String!, $limit: Int = 2000) {<br>            uiapi {<br>                query {<br>                    Account(<br>                        where: { Name: { like: $searchKey } }<br>                        first: $limit<br>                        orderBy: { Name: { order: ASC } }<br>                    ) {<br>                        edges {<br>                            node {<br>                                Id<br>                                Name {<br>                                    value<br>                                }<br>                                Contacts<br>                                {<br>                                    edges {<br>                                        node {<br>                                            Id<br>                                            Name {<br>                                                value<br>                                            }<br>                                        }<br>                                    }<br>                                }<br>                                Cases(<br>                                    orderBy: { LastModifiedDate: { order: ASC } }<br>                                ) {<br>                                    edges {<br>                                        node {<br>                                            Id<br>                                            CaseNumber{<br>            value<br>           }<br>                                            Subject {<br>                                                value<br>                                                displayValue<br>                                            }<br>                                            Owner  {<br>                                                ... on User {<br>                                                    Name {<br>                                                        value<br>                                                    }<br>                                                }<br>                                            }<br>                                            CreatedDate {<br>                                                displayValue<br>                                            }<br>                                            Id<br>                                            IsEscalated {<br>                                                value<br>                                            }<br>                                        }<br>                                    }<br>                                }<br>                            }<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>        `,<br>        variables: &#39;$variables&#39;<br>    })<br>    wiredValues(result) {<br>        this.isLoading = false;<br>        this.account = undefined;<br>        this.errors = undefined;<br>        this.graphqlQueryResult = result;<br>        const { errors, data } = result;<br>        if (data) {<br>            const accounts = data.uiapi.query.Account.edges.map((edge) =&gt; ({<br>                Id: edge.node.Id,<br>                Name: edge.node.Name.value,<br>                Contact: edge.node.Contacts,<br>                Case:edge.node.Cases<br>            }));<br>            if (accounts.length === 0) {<br>                this.errors = [`Couldn&#39;t find account.`];<br>            } else {<br>                this.accounts = accounts;<br>            }<br>        }<br>        if (errors) {<br>            this.errors = errors;<br>        }<br>    }<br><br>    handlePaginatorChange(event) {<br>        this.displayaccounts = event.detail;<br>    }<br><br>    get variables() {<br>        return {<br>            searchKey: this.searchKey === &#39;&#39; ? &#39;%&#39; : `%${this.searchKey}%`<br>        };<br>    }<br><br>    handleKeyChange(event) {<br>        window.clearTimeout(this.delayTimeout);<br>        const searchKey = event.target.value;<br>        this.delayTimeout = setTimeout(() =&gt; {<br>            this.searchKey = searchKey;<br>        }, DELAY);<br>    }<br><br>    @api<br>    async handleRefresh() {<br>      return refreshGraphQL(this.graphqlQueryResult);<br>    }<br>}</pre><blockquote>@wire(graphql) start of graphql function.</blockquote><blockquote>query getAccountAndRelatedbjects($searchKey: String!, $limit: Int = 2000) // Start of Query with operation Name , passing the parameters.</blockquote><blockquote>On above code, contact and case related to account are fetched in a single go.</blockquote><blockquote>To fetch the value, need to traverse deep down till node, followed by fieldname.</blockquote><blockquote>If user enter search parameter, handleKeyChange function triggers and assigns the value to searchkey.</blockquote><pre>&lt;template&gt;<br>    &lt;lightning-card&gt;<br>        &lt;header&gt;<br>            &lt;h1 class=&quot;header&quot;&gt;GraphQL Source&lt;/h1&gt;<br>        &lt;/header&gt;<br>        &lt;main class=&quot;container&quot;&gt;<br>            &lt;div class=&quot;slds-var-m-around_medium&quot;&gt;<br>                &lt;lightning-input type=&quot;search&quot; onchange={handleKeyChange} class=&quot;slds-var-m-bottom_small&quot; label=&quot;Search&quot;<br>                    value={searchKey}&gt;&lt;/lightning-input&gt;<br>                &lt;c-button label=&quot;Refresh&quot; variant=&quot;brand&quot; onclick={handleRefresh}&gt;&lt;/c-button&gt;<br>                &lt;template lwc:if={accounts}&gt;<br>                    &lt;c-paginator-component<br>                    page-size-options = {pageSizeOptions}<br>                    records={accounts} <br>                    total-records={accounts.length} <br>                    show-search-box=&quot;true&quot; <br>                    onpaginatorchange={handlePaginatorChange}&gt;<br>                    &lt;/c-paginator-component&gt;<br>                    &lt;template for:each={displayaccounts} for:item=&quot;account&quot;&gt;<br>                        &lt;c-collapsible-section key={account.Id} id={account.Id} label={account.Name}&gt;<br>                            &lt;b&gt;Contacts:&lt;/b&gt; &lt;br/&gt;<br>                            &lt;template for:each={account.Contact.edges} for:item=&quot;contact&quot;&gt;<br>                                {contact.node.Name.value} &lt;br key={contact.node.Name.value}/&gt;<br>                            &lt;/template&gt;<br>                            &lt;hr/&gt;<br>                            &lt;b&gt;Cases: &lt;/b&gt; &lt;br/&gt;<br>                            &lt;template for:each={account.Case.edges} for:item=&quot;cases&quot;&gt;<br>                                {cases.node.CaseNumber.value} &lt;br key={cases.node.CaseNumber.value}/&gt;<br>                            &lt;/template&gt;<br>                        &lt;/c-collapsible-section&gt;<br>                    &lt;/template&gt;<br>                &lt;/template&gt;<br>            &lt;/div&gt;<br>        &lt;/main&gt;<br>        &lt;footer&gt;<br>        &lt;/footer&gt;<br>    &lt;/lightning-card&gt;<br>&lt;/template&gt;</pre><p><em>Code can be found on my GitHub : </em><a href="https://github.com/vikranthkaru/salesforce/tree/master/force-app/main/default"><em>vikranthkaru/salesforce</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb21c4045efd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusable Lightning Modal with Dynamic Instantiate Component in LWC]]></title>
            <link>https://vikranthkaru.medium.com/reusable-lightning-modal-with-dynamic-instantiate-component-in-lwc-832c8d45edad?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/832c8d45edad</guid>
            <category><![CDATA[lwc-modal]]></category>
            <category><![CDATA[lightning-modal-lwc]]></category>
            <category><![CDATA[reusable-modal-lwc]]></category>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Tue, 19 Dec 2023 19:53:13 GMT</pubDate>
            <atom:updated>2023-12-19T19:53:13.280Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Dynamic components in web component world refers to elements that can be created, modified at run time.</blockquote><blockquote>In world of Lightning Web Components (LWC), a dynamic component typically refers to the ability to create, render, or manipulate components dynamically at runtime.</blockquote><blockquote>As part of this article lets build a reusable lightning data modal, with concept of dynamically instantiate component.</blockquote><blockquote>Enable lightning Web Security in org.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-m6gXDmhYK5f5H-mvxRxQg.png" /></figure><blockquote>We will use the <a href="https://medium.com/@vikranthkaru/reusable-lightning-data-table-4222ce232d96">Lightning Datatable</a> from other post.</blockquote><blockquote>Create a lightning Modal component with ReusableLightningModal</blockquote><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;LightningComponentBundle xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br>    &lt;apiVersion&gt;59.0&lt;/apiVersion&gt;<br>    &lt;description&gt;Resuable Modal Box&lt;/description&gt;<br>    &lt;isExposed&gt;true&lt;/isExposed&gt;<br>    &lt;masterLabel&gt;Resuable Modal Box&lt;/masterLabel&gt;<br>    &lt;targets&gt;<br>        &lt;target&gt;lightningCommunity__Page&lt;/target&gt;<br>        &lt;target&gt;lightningCommunity__Default&lt;/target&gt;<br>        &lt;target&gt;lightning__RecordPage&lt;/target&gt;<br>        &lt;target&gt;lightning__AppPage&lt;/target&gt;<br>        &lt;target&gt;lightning__HomePage&lt;/target&gt;<br>    &lt;/targets&gt;<br>    &lt;capabilities&gt;<br>      &lt;capability&gt;lightning__dynamicComponent&lt;/capability&gt;<br>    &lt;/capabilities&gt;<br>&lt;/LightningComponentBundle&gt;</pre><blockquote>To call a component during runtime from lwc, component configuration file must include the lightning__dynamicComponent capability. Apiversion should be 55.0 or later.</blockquote><pre>&lt;lwc:component lwc:is={componentConstructor}&gt;&lt;/lwc:component&gt;</pre><blockquote>To render the specified component in runtime declare lwc:component which is placeholder on html markup and use to render the declared dynamic component. lwc:component should be used with lwc:is,</blockquote><blockquote>lwc:is feeds the imported component at runtime to lwc:component</blockquote><blockquote>In the javascript file declare componentConstructor as variable, and component can be imported as below</blockquote><pre> import(&quot;c/concreteComponent&quot;)<br>      .then(({ default: ctor }) =&gt; (this.componentConstructor = ctor))<br>      .catch((err) =&gt; console.log(&quot;Error importing component&quot;));</pre><blockquote>using import function component is instantiated and attached to the DOM.</blockquote><blockquote>Component can be instantiated in runtime dynamically or statically. Above example shows where the component is loaded statically.</blockquote><blockquote>To pass the param from parent to child component, lwc:spread operator is used.</blockquote><blockquote>As part of this article dynamic import is covered with passing props to child element.</blockquote><pre>import { api } from &#39;lwc&#39;;<br>import LightningModal from &#39;lightning/modal&#39;;<br>export default class ReusableLightningModal extends LightningModal {<br>    @api componentName;<br>    childProps; ctx; label;<br><br>    handleOkay() {<br>        this.close(&#39;okay&#39;);<br>    }<br><br>    _runtimevalue;<br><br>    @api <br>    get runtimevalue()<br>    {<br>        return this._runtimevalue;<br>    }<br>    set runtimevalue(val)<br>    {<br>        if(val != undefined)<br>        {<br>            const componentName = `c/${val.name}`;<br>            this.childProps = val.childProps;<br>            this.label = val.label;<br>            import(componentName).then(({default : ctx}) =&gt;{<br>              this.ctx = ctx; <br>            });<br>        }<br>    }<br><br>    renderedCallback() {<br>        // this.refs.myCmp will be available on the next rendering cycle after the constructor is set<br>        if (this.refs.myCmp) {<br>          // this.refs.myCmp will contain a reference to the DOM node<br>          console.log(this.refs.myCmp);<br>        }<br>    }<br>}</pre><blockquote>const componentName = `c/${val.name}`; val.name is dynamically setting the component name in run time.</blockquote><pre>&lt;template&gt;<br>    &lt;lightning-modal-header label={label}&gt;&lt;/lightning-modal-header&gt;<br>    &lt;lightning-modal-body&gt; <br>        &lt;lwc:component lwc:is={ctx}  lwc:ref=&quot;myCmp&quot; lwc:spread={childProps}&gt;<br>        &lt;/lwc:component&gt;<br>    &lt;/lightning-modal-body&gt; <br>    &lt;lightning-modal-footer&gt;<br>        &lt;lightning-button label=&quot;OK&quot; onclick={handleOkay}&gt;&lt;/lightning-button&gt;<br>    &lt;/lightning-modal-footer&gt; <br>&lt;/template&gt;</pre><blockquote>&lt;lwc:component lwc:is={ctx} lwc:ref=”myCmp” lwc:spread={childProps}&gt;<br> &lt;/lwc:component&gt;</blockquote><blockquote>Modal Body is set dynamically and can be used to call from other components.</blockquote><blockquote>childProps is set in javascript and information is passed from the parent component. lwc:spread takes care of assigning the values to public variables in child.</blockquote><blockquote>Create a new component CallDynamicComponent. This component on click of button opens the modal pop and content is displayed dynamically, passed from this component.</blockquote><pre>&lt;template&gt;<br>    &lt;lightning-card&gt;<br>        &lt;c-button label=&quot;Click To Fetch Accounts&quot; variant=&quot;brand&quot; onclick={handleclick}&gt;&lt;/c-button&gt;<br>    &lt;/lightning-card&gt;<br>&lt;/template&gt;</pre><pre>import { LightningElement } from &#39;lwc&#39;;<br>import MyModal from &#39;c/reusableLightningModal&#39;;<br>export default class CallDynamicComponent extends LightningElement {<br>    columns = [{label:&#39;Name&#39;, fieldName:&#39;Name&#39;, sortable:true}, {label:&#39;Phone&#39;,fieldName:&#39;Phone&#39;}, {label:&#39;Account Source&#39;,fieldName:&#39;AccountSource&#39;}, {label:&#39;Rating&#39;,fieldName:&#39;Rating&#39;},{type:&#39;action&#39;,typeAttributes:{rowActions:[{label:&#39;View&#39;,name:&#39;view&#39;},{label:&#39;Edit&#39;,name:&#39;edit&#39;}]}}];<br>    async handleclick()<br>    {<br>        const childProps = {<br>            sObjName : &#39;Account&#39;,<br>            limitValue : 1000,<br>            recordPerPage : &#39;3,5,15&#39;,<br>            columns : JSON.stringify(this.columns),<br>            isLightningPage : true<br>        }<br>        const runtimeload = {<br>            name:&#39;reusableDataTable&#39;,<br>            label:&#39;Data Table&#39;,<br>            childProps : childProps<br>        }<br>        const result = await MyModal.open({<br>            size: &#39;large&#39;,<br>            description: &#39;Accessible description of modal\&#39;s purpose&#39;,<br>            runtimevalue: runtimeload<br>        });<br>        console.log(result);<br>    }<br>}</pre><blockquote>On handleClick parameters are added to object childProps and runtimeload and passed to modal for dynamically loading the component during runtime.</blockquote><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;LightningComponentBundle xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br>    &lt;apiVersion&gt;59.0&lt;/apiVersion&gt;<br>    &lt;description&gt;Dynamic Component&lt;/description&gt;<br>    &lt;isExposed&gt;true&lt;/isExposed&gt;<br>    &lt;masterLabel&gt;Component To Test Dynamic Import&lt;/masterLabel&gt;<br>    &lt;targets&gt;<br>        &lt;target&gt;lightningCommunity__Page&lt;/target&gt;<br>        &lt;target&gt;lightningCommunity__Default&lt;/target&gt;<br>        &lt;target&gt;lightning__RecordPage&lt;/target&gt;<br>        &lt;target&gt;lightning__AppPage&lt;/target&gt;<br>        &lt;target&gt;lightning__HomePage&lt;/target&gt;<br>    &lt;/targets&gt;<br>    &lt;capabilities&gt;<br>      &lt;capability&gt;lightning__dynamicComponent&lt;/capability&gt;<br>    &lt;/capabilities&gt;<br>&lt;/LightningComponentBundle&gt;</pre><blockquote>More information for <a href="https://developer.salesforce.com/docs/platform/lwc/guide/js-dynamic-components.html">Dynamically Instantiate Components</a>.</blockquote><blockquote>Code can be found on my GitHub : <a href="https://github.com/vikranthkaru/salesforce/tree/master/force-app/main/default">vikranthkaru/salesforce</a>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=832c8d45edad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusable Lightning Data Table]]></title>
            <link>https://vikranthkaru.medium.com/reusable-lightning-data-table-4222ce232d96?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/4222ce232d96</guid>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 11:30:46 GMT</pubDate>
            <atom:updated>2023-12-19T19:54:03.147Z</atom:updated>
            <content:encoded><![CDATA[<p>Reusable Lightning Data Table</p><p>In Salesforce, the Lightning Data Table is a powerful and customizable component for displaying tabular data. As part of this article, lets create reusable data table with pagination.</p><p>Create a lightning web component with name PaginatorComponent</p><pre>import { LightningElement,api,track } from &#39;lwc&#39;;<br>const pageNumber = 1;<br>const showIt = &#39;visibility:visible&#39;;<br>const hideIt = &#39;visibility:hidden&#39;; <br>export default class PaginatorComponent extends LightningElement {<br>@api showPagination; <br>    @api pageSizeOptions; <br>    @api totalRecords; <br>    @api records;  <br>    @track pageSize; <br>    @track totalPages; <br>    @track pageNumber = pageNumber; <br>    @track controlPagination = showIt;<br>    @track controlPrevious = hideIt; <br>    @track controlNext = showIt; <br>    recordsToDisplay = [];<br>     connectedCallback() {<br>        if (this.pageSizeOptions &amp;&amp; this.pageSizeOptions.length &gt; 0)<br>            this.pageSize = this.pageSizeOptions[0];<br>        else {<br>            this.pageSize = this.totalRecords;<br>            this.showPagination = false;<br>        }<br>        this.controlPagination = this.showPagination === false ? hideIt : showIt;<br>        this.setRecordsToDisplay();<br>    }<br><br>    handleRecordsPerPage(event) {<br>        this.pageSize = event.target.value;<br>        this.setRecordsToDisplay();<br>    }<br>    handlePageNumberChange(event) {<br>        if (event.keyCode === 13) {<br>            this.pageNumber = event.target.value;<br>            this.setRecordsToDisplay();<br>        }<br>    }<br>    previousPage() {<br>        this.pageNumber = this.pageNumber - 1;<br>        this.setRecordsToDisplay();<br>    }<br>    nextPage() {<br>        this.pageNumber = this.pageNumber + 1;<br>        this.setRecordsToDisplay();<br>    }<br>    setRecordsToDisplay() {<br>        this.recordsToDisplay = [];<br>        if (!this.pageSize)<br>            this.pageSize = this.totalRecords;<br><br>        this.totalPages = Math.ceil(this.totalRecords / this.pageSize);<br><br>        this.setPaginationControls();<br><br>        for (let i = (this.pageNumber - 1) * this.pageSize; i &lt; this.pageNumber * this.pageSize; i++) {<br>            if (i === this.totalRecords) break;<br>            this.recordsToDisplay.push(this.records[i]);<br>        }<br>        this.dispatchEvent(new CustomEvent(&#39;paginatorchange&#39;, { detail: this.recordsToDisplay })); //Send records to display on table to the parent component<br>    }<br>    setPaginationControls() {<br>        if (this.totalPages === 1) {<br>            this.controlPrevious = hideIt;<br>            this.controlNext = hideIt;<br>        } else if (this.totalPages &gt; 1) {<br>            this.controlPrevious = showIt;<br>            this.controlNext = showIt;<br>        }<br>        if (this.pageNumber &lt;= 1) {<br>            this.pageNumber = 1;<br>            this.controlPrevious = hideIt;<br>        } else if (this.pageNumber &gt;= this.totalPages) {<br>            this.pageNumber = this.totalPages;<br>            this.controlNext = hideIt;<br>        }<br>        if (this.controlPagination === hideIt) {<br>            this.controlPrevious = hideIt;<br>            this.controlNext = hideIt;<br>        }<br>        <br>    }<br>}</pre><pre>.customSelect select {<br>    padding-right: 1.25rem;<br>    min-height: inherit;<br>    line-height: normal;<br>    height: 1.4rem;    <br>}<br>.customSelect label {<br>    margin-top: .1rem;<br>}<br>.customSelect .slds-select_container::before {<br>    border-bottom: 0;<br>}<br>.customInput {<br>    width: 3rem;<br>    height: 1.4rem;<br>    text-align: center;<br>    border: 1px solid #dddbda;<br>    border-radius: 3px;<br>    background-color:#fff;<br>}</pre><pre>&lt;template&gt;  <br>    &lt;div class=&quot;slds-grid slds-grid_vertical-align-center slds-grid_align-spread&quot;&gt;<br>        &lt;div class=&quot;slds-col&quot;&gt;&lt;!--RECORDS PER PAGE--&gt;<br>            &lt;div style={controlPagination} class=&quot;slds-list_inline slds-p-bottom_xx-small customSelect&quot;&gt;<br>                &lt;label class=&quot;slds-text-color_weak slds-p-horizontal_x-small&quot; for=&quot;recordsPerPage&quot;&gt;Records per page:&lt;/label&gt; <br>                &lt;div class=&quot;slds-select_container&quot;&gt;<br>                    &lt;select class=&quot;slds-select&quot; id=&quot;recordsPerPage&quot; onchange={handleRecordsPerPage}&gt;<br>                        &lt;template for:each={pageSizeOptions} for:item=&quot;option&quot;&gt;<br>                            &lt;option key={option} value={option}&gt;{option}&lt;/option&gt;<br>                        &lt;/template&gt;<br>                    &lt;/select&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;div class=&quot;slds-col&quot;&gt;&lt;!--PAGE NAVIGATION--&gt;<br>            &lt;div style={controlPagination}&gt;<br>                &lt;div class=&quot;slds-col slds-p-bottom_xx-small&quot;&gt;<br>                    &lt;span style={controlPrevious}&gt;<br>                        &lt;lightning-button-icon icon-name=&quot;utility:left&quot; variant=&quot;bare&quot; size=&quot;medium&quot; alternative-text=&quot;Previous Page&quot; onclick={previousPage}&gt;&lt;/lightning-button-icon&gt;<br>                    &lt;/span&gt;<br>                    &lt;label class=&quot;slds-text-color_weak slds-p-horizontal_x-small&quot; for=&quot;pageNum&quot;&gt;Page:&lt;/label&gt; <br>                    &lt;input type=&quot;number&quot; id=&quot;pageNum&quot; value={pageNumber} maxlength=&quot;4&quot; onkeypress={handlePageNumberChange} class=&quot;customInput&quot; title=&quot;Go to a Page&quot;&gt;&lt;/input&gt;<br>                    &lt;span&gt;&amp;nbsp;of&amp;nbsp;&lt;b id=&quot;totalPages&quot;&gt;{totalPages}&lt;/b&gt;&lt;/span&gt;<br>                    &lt;span style={controlNext}&gt;<br>                        &lt;lightning-button-icon icon-name=&quot;utility:right&quot; variant=&quot;bare&quot; size=&quot;medium&quot; alternative-text=&quot;Next Page&quot; onclick={nextPage} class=&quot;slds-p-horizontal_x-small&quot;&gt;&lt;/lightning-button-icon&gt;<br>                    &lt;/span&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;<br>&lt;/template&gt;</pre><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;LightningComponentBundle xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br> &lt;apiVersion&gt;57.0&lt;/apiVersion&gt;<br> &lt;isExposed&gt;true&lt;/isExposed&gt;<br>&lt;/LightningComponentBundle&gt;</pre><p>Create a Apex Controller</p><pre>public class ReusableDataTableController {<br>    @AuraEnabled<br>    public static list&lt;sObject&gt; fetchRecords(string sObjectName, string filterCriteria,string recordId,integer limitValue)<br>    {<br>        try<br>        {<br>            string sQuery = createDynamicQuery(sObjectName);<br>            if(!string.isBlank(filterCriteria))<br>            {<br>                sQuery += &#39; &#39; + filterCriteria;<br>            }<br>            sQuery += &#39; LIMIT &#39;+limitValue;<br>            return DataBase.Query(sQuery);<br>        }<br>        catch(Exception e)<br>        {<br>            throw new AuraHandledException(LightningErrorFrameWork.handleErrorMessage(e.getMessage()));<br>        }<br>    }<br><br>    public static string createDynamicQuery(string sObjectName)<br>    {<br>        List&lt;String&gt; fieldNames = new List&lt;String&gt;();<br>        Schema.SObjectType objType = Schema.getGlobalDescribe().get(sObjectName);<br>        Schema.DescribeSObjectResult objDescribe = objType.getDescribe();<br>        Map&lt;String, Schema.SObjectField&gt; fieldMap = objDescribe.fields.getMap();<br>        fieldNames.addAll(fieldMap.keySet());<br>        return &#39;Select &#39; + String.join(fieldNames, &#39;,&#39;)+ &#39; from &#39;+ sObjectName;<br>    }<br>}</pre><p>Create LWC Component with name ReusableDataTable</p><pre>import { LightningElement,api,track } from &#39;lwc&#39;;<br>import { NavigationMixin } from &#39;lightning/navigation&#39;;<br>import { showToastMessage } from &quot;c/utilModule&quot;;<br>import jsFetchDataFromController from &#39;@salesforce/apex/ReusableDataTableController.fetchRecords&#39;;<br>export default class ReusableDataTable extends NavigationMixin(LightningElement) {<br><br>    @api sObjName;<br>    @api filterCriteria;<br>    @api records;  <br>    @api recordId; <br>    @api sFields;<br>    @api limitValue = 1000; <br>    @api recordPerPage; <br>    @api columns; <br>    @api showCheckBox; <br>    @api showRowNumber;<br>    @api useDefaultRecordId;<br>    pageSizeOptions = [];<br><br>    @track visibleData = null;<br>    @track recordsToDisplay = []; <br>    _records;<br>    sortedBy; defaultSortDirection = &#39;asc&#39;; sortDirection = &#39;asc&#39;;<br>    _isLightningPage;<br><br>    @api <br>    get isLightningPage()<br>    {<br>        return this._isLightningPage;<br>    }<br><br>    set isLightningPage(value)<br>    {<br>        if(value === false)<br>        {<br>            <br>            if(this.records != undefined)<br>            {<br>                this.pageSizeOptions = this.recordPerPage.split(&quot;,&quot;);<br>                this.func_processRecords(this.records);<br>            }<br>        }<br>        else<br>        {<br>             this.func_fetchDataFromController();<br>        }<br>    }<br><br>   async func_fetchDataFromController()<br>    {<br>        jsFetchDataFromController({sObjectName:this.sObjName,filterCriteria:this.filterCriteria,recordId:this.recordId,limitValue:this.limitValue})<br>        .then(result=&gt;{<br>            this.func_processRecords(result);<br>        })<br>        .catch(error=&gt;{<br>            let evt = showToastMessage(&quot;Error&quot;, &quot;Oops looks like not able to fetch records, please contact admin team&quot;, error);<br>            this.dispatchEvent(evt);<br>        });<br>    }<br><br>    func_processRecords(value)<br>    {<br>        this.pageSizeOptions = this.recordPerPage.split(&quot;,&quot;);<br>        this._records = value.map((assign) =&gt; {<br>            return {<br>                ...assign,<br>                recordURL: &#39;/lightning/r/&#39; + assign.Id + &#39;/view&#39;<br>            };<br>        });<br>        this.columns = JSON.parse( this.columns.replace( /([a-zA-Z0-9]+?):/g, &#39;&quot;$1&quot;:&#39; ).replace( /&#39;/g, &#39;&quot;&#39; ) );<br>    }<br><br>    func_handlePaginatorChange(event) {<br>        this.recordsToDisplay = event.detail;<br>    }<br><br>    func_onHandleSort(event) {<br>         <br>        const { fieldName: sortedBy, sortDirection } = event.detail;<br>        const cloneData = [...this.recordsToDisplay];<br>        cloneData.sort( this.func_sortBy( sortedBy, sortDirection === &#39;asc&#39; ? 1 : -1 ) );<br>        this.recordsToDisplay = cloneData;<br>        this.sortDirection = sortDirection;<br>        this.sortedBy = sortedBy;<br>    }<br><br>    func_sortBy( field, reverse, primer ) {<br>        const key = primer<br>            ? function( x ) {<br>                  return primer(x[field]);<br>              }<br>            : function( x ) {<br>                  return x[field];<br>              };<br> <br>        return function( a, b ) {<br>            a = key(a);<br>            b = key(b);<br>            return reverse * ( ( a &gt; b ) - ( b &gt; a ) );<br>        };<br>    }<br><br>    func_handleRowAction( event ) {<br> <br>        const actionName = event.detail.action.name;<br>        const row = event.detail.row;<br>        switch ( actionName ) {<br>            case &#39;view&#39;:<br>                this[NavigationMixin.GenerateUrl]({<br>                    type: &#39;standard__recordPage&#39;,<br>                    attributes: {<br>                        recordId: row.Id,<br>                        actionName: &#39;view&#39;,<br>                    },<br>                }).then(url =&gt; {<br>                     window.open(url);<br>                });<br>                break;<br>            case &#39;edit&#39;:<br>                this[NavigationMixin.Navigate]({<br>                    type: &#39;standard__recordPage&#39;,<br>                    attributes: {<br>                        recordId: row.Id,<br>                        objectApiName: this.RelatedObject,<br>                        actionName: &#39;edit&#39;<br>                    }<br>                });<br>                break;<br>            default:<br>        }<br> <br>    }<br>}</pre><pre>&lt;template&gt;<br>        &lt;template if:true={_records}&gt;<br>                &lt;c-paginator-component<br>                page-size-options = {pageSizeOptions}<br>                records={_records} <br>                total-records={_records.length} <br>                show-search-box=&quot;true&quot; <br>                onpaginatorchange={func_handlePaginatorChange}&gt;<br>                &lt;/c-paginator-component&gt;<br>                &lt;lightning-datatable<br>                key-field=&quot;Id&quot;<br>                data={recordsToDisplay}  <br>                columns={columns}  <br>                hide-checkbox-column <br>                show-row-number-column={showRowNumber}<br>                default-sort-direction={defaultSortDirection}<br>                sorted-direction={sortDirection}<br>                sorted-by={sortedBy}<br>                onsort={func_onHandleSort}<br>                onrowaction={func_handleRowAction}&gt;<br>                &lt;/lightning-datatable&gt; <br>        &lt;/template&gt;<br>&lt;/template&gt;</pre><pre>&lt;?xml version=&quot;1.0&quot;?&gt;<br>&lt;LightningComponentBundle xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br> &lt;apiVersion&gt;57.0&lt;/apiVersion&gt;<br> &lt;isExposed&gt;true&lt;/isExposed&gt;<br>    &lt;targets&gt;<br>        &lt;target&gt;lightning__AppPage&lt;/target&gt;<br>        &lt;target&gt;lightning__RecordPage&lt;/target&gt;<br>        &lt;target&gt;lightning__HomePage&lt;/target&gt;<br>    &lt;/targets&gt;<br>     &lt;targetConfigs&gt;<br>        &lt;targetConfig targets=&quot;lightning__HomePage,lightning__RecordPage&quot;&gt;<br>              &lt;property name=&quot;isLightningPage&quot; type=&quot;boolean&quot; label=&quot;Lightning Page&quot; default=&quot;false&quot;/&gt;<br>              &lt;property name=&quot;sObjName&quot; type=&quot;String&quot; label=&quot;Object&quot; required=&quot;true&quot; datasource=&quot;apex://reusableDataTableDesignComponent&quot;/&gt;<br>              &lt;property name=&quot;sFields&quot; type=&quot;String&quot; label=&quot;Fields&quot; required=&quot;true&quot; default=&quot;Name,AccountNumber,Phone,AccountSource,Rating&quot;/&gt;<br>              &lt;property name=&quot;filterCriteria&quot; type=&quot;String&quot; label = &quot;Filter&quot; default = &quot; Where Id =:recordId&quot;/&gt;<br>              &lt;property name=&quot;recordId&quot; type=&quot;String&quot; default=&quot;00000000000&quot; label = &quot;Use Different Id&quot;/&gt;<br>              &lt;property name=&quot;limitValue&quot; type=&quot;Integer&quot; label=&quot;Limit&quot; required=&quot;true&quot; default=&quot;1000&quot;/&gt;<br>              &lt;property name=&quot;recordPerPage&quot; type=&quot;String&quot; default=&quot; &quot; label=&quot;Select How Many Records Needs to Displayed Per Page&quot;/&gt;<br>              &lt;property name=&quot;columns&quot; type=&quot;String&quot; label=&quot;Columns&quot; default=&quot;[{label:&#39;Name&#39;, fieldName:&#39;Name&#39;, sortable:true}, {label:&#39;Phone&#39;,fieldName:&#39;Phone&#39;}, {label:&#39;Account Source&#39;,fieldName:&#39;AccountSource&#39;}, {label:&#39;Rating&#39;,fieldName:&#39;Rating&#39;},{type:&#39;action&#39;,typeAttributes:{rowActions:[{label:&#39;View&#39;,name:&#39;view&#39;},{label:&#39;Edit&#39;,name:&#39;edit&#39;}]}}]&quot;/&gt;<br>        &lt;/targetConfig&gt;<br>    &lt;/targetConfigs&gt;<br>&lt;/LightningComponentBundle&gt;</pre><p>Property isLightningPage will help in deciding if the component is placed on record page or called as child from another component. If data table is used as child component in another component pass values from parent to child</p><pre>HTML:<br>&lt;c-reusable-data-table <br> record-per-page={recordPerPage}<br> records={assignmentLog} columns={columns} show-check-box={showCheckBox}<br> show-row-number={showRowNumber} is-lightning-page={isLightningPage}&gt;&lt;/c-reusable-data-table/&gt;<br><br><br>JS<br><br>export default class extens LightningElement{<br>assignmentLog;<br>tempcolumns = [  <br>        {  <br>         label: &#39;Name&#39;,  <br>         fieldName: &quot;Name&quot;,  <br>         sortable: true,<br>        },  <br>        {  <br>         label: &#39;Phone&#39;,  <br>         fieldName: &quot;Phone&quot;,  <br>         sortable: true,<br>        },<br>        {  <br>         label: &#39;Account Source&#39;,  <br>         fieldName: &quot;AccountSource&quot;,  <br>         sortable: true,<br>        },<br>    ];<br>    columns = JSON.stringify(tempColumns);<br>isLightningPage = false;<br>}</pre><p>On record Page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Taa6pxPIDhbY_Lzdc1GVPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bQwoscktaHJLJ5Zo_9D1w.png" /></figure><p><em>Code can be found on my GitHub : </em><a href="https://github.com/vikranthkaru/salesforce/tree/master/force-app/main/default"><em>vikranthkaru/salesforce</em></a><em>.</em></p><p>Follow me on Linkedin : <a href="https://linkedin.com/in/vikranth-karollu-hanumanth-2b1922164/">https://linkedin.com/in/vikranth-karollu-hanumanth-2b1922164/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4222ce232d96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reusable Lightning Data Service (LWC)]]></title>
            <link>https://vikranthkaru.medium.com/reusable-lightning-data-service-lwc-1b2a2be24929?source=rss-ade0d38f3972------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b2a2be24929</guid>
            <dc:creator><![CDATA[Vikranth Karollu Hanumanth]]></dc:creator>
            <pubDate>Sun, 19 Nov 2023 19:49:41 GMT</pubDate>
            <atom:updated>2023-12-19T19:54:40.777Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the many among use cases of building custom component in salesforce is to build custom detail page. This can be achieved by using Lightning Data Service.</p><p>Lightning Web Components (LWC) in Salesforce empowers developers to create modular and reusable components, streamlining the development process. Reusable components offer a strategic advantage by encapsulating functionality into self-contained units that can be easily integrated across different parts of an application or even shared across projects.</p><p>This not only enhances code organization but also accelerates development cycles. In the dynamic world of web development, efficiency and maintainability are paramount.</p><p>Create a lightning web component with name reusableRecordForm. This component can be used in lightning app builder or can be used as child component.</p><pre>import { LightningElement,api } from &#39;lwc&#39;;<br><br>export default class ReusableRecordForm extends LightningElement {<br>    @api recordId;<br>    @api columns;<br>    @api fieldsToDisplay;<br>    @api displayMode;<br>    @api error;<br>    @api sObjectName;<br> <br>    get praseFields(){<br><br>        <br>        if(this.fieldsToDisplay !== undefined)<br>        {<br>            let displayFields = this.fieldsToDisplay.replace(/\s/g, &#39;&#39;).split(&#39;,&#39;);<br>            displayFields = displayFields.filter(function (el) {<br>                return el != null &amp;&amp; el!==&#39;&#39;;<br>            });<br>            return displayFields;<br>        }<br>    }<br>}</pre><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;LightningComponentBundle xmlns=&quot;http://soap.sforce.com/2006/04/metadata&quot;&gt;<br>    &lt;apiVersion&gt;58.0&lt;/apiVersion&gt;<br>    &lt;isExposed&gt;true&lt;/isExposed&gt;<br>    &lt;targets&gt;<br>        &lt;target&gt;lightning__RecordPage&lt;/target&gt;<br>        &lt;target&gt;lightning__HomePage&lt;/target&gt;<br>        &lt;target&gt;lightning__Tab&lt;/target&gt;<br>    &lt;/targets&gt;<br>    &lt;targetConfigs&gt;<br>        &lt;targetConfig targets=&quot;lightning__RecordPage, lightning__HomePage&quot;&gt;<br>            &lt;property name=&quot;sObjectName&quot; label=&quot;Object&quot; type=&quot;String&quot;  required=&quot;true&quot; datasource=&quot;apex://ObjectController&quot;/&gt;<br>            &lt;property name=&quot;columns&quot; label=&quot;Columns&quot; type=&quot;Integer&quot; min=&quot;1&quot; max=&quot;6&quot; default=&quot;2&quot;/&gt;<br>            &lt;property name=&quot;fieldsToDisplay&quot; label=&quot;Fields To Display (API Name)&quot; type=&quot;String&quot; default=&quot;Name__c&quot;/&gt;<br>            &lt;property name=&quot;displayMode&quot; label=&quot;Read or Edit Mode&quot; type=&quot;String&quot; default=&quot;view&quot; datasource=&quot;view, edit, readonly&quot;/&gt;<br>        &lt;/targetConfig&gt;<br>    &lt;/targetConfigs&gt;<br>&lt;/LightningComponentBundle&gt;</pre><pre>&lt;template&gt;<br>    &lt;lightning-card&gt;  <br>        &lt;div class=&quot;slds-p-around_medium&quot;&gt;  <br>            &lt;lightning-record-form<br>                record-id = {recordId}<br>                object-api-name = {sObjectName}<br>                fields = {praseFields}<br>                columns = {columns}<br>                mode = {displayMode}<br>                &gt; <br>                &lt;/lightning-record-form&gt;  <br>        &lt;/div&gt;<br>    &lt;/lightning-card&gt; <br>&lt;/template&gt;</pre><pre>global class ObjectController extends VisualEditor.DynamicPickList {<br>    global override VisualEditor.DataRow getDefaultValue(){<br>        VisualEditor.DataRow defaultValue = new VisualEditor.DataRow(&#39;Account&#39;, &#39;Account&#39;);<br>        return defaultValue;<br>    }<br>    <br>    global override VisualEditor.DynamicPickListRows getValues() {<br>        VisualEditor.DynamicPickListRows  objValues = new VisualEditor.DynamicPickListRows();<br>        Map&lt;string, Schema.SObjectType&gt; sobj = Schema.getGlobalDescribe();<br>        for(schema.SObjectType thisobj : sobj.values()){<br>            Schema.DescribeSObjectResult objResult = thisobj.getDescribe();<br>            if(objResult.isQueryable()==true)<br>            {<br>                VisualEditor.DataRow value = new VisualEditor.DataRow(objResult.getName(), objResult.getName());<br>                objValues.addRow(value);<br>            }            <br>        }   <br>        return objValues;<br>    }<br>}</pre><p><em>Code can be found on my GitHub : </em><a href="https://github.com/vikranthkaru/salesforce/tree/master/force-app/main/default"><em>vikranthkaru/salesforce</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b2a2be24929" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>