tag:blogger.com,1999:blog-87079432995374663552024-03-26T23:37:59.102-07:00Salesforce Lightning Web Components, Aura Components, Apex Triggers, Apex REST API IntegrationBlog is all about How To Salesforce Lightning interview questions, Lightning web components, Aura components, Basics Salesforce Tutorials, Salesforce Apex-Visualforce, Triggers Real time scenarios, Salesforce Workflow Rules-Process Builder, Release Notes, Salesforce interview Questions for experienced & FresherUnknownnoreply@blogger.comBlogger62125tag:blogger.com,1999:blog-8707943299537466355.post-84601917845127416742024-01-24T22:10:00.000-08:002024-01-24T22:13:47.564-08:00Resolving the Issue: Ensuring Invocation of LWC Wire Function When Properties Are Undefined<p>Navigating the intricacies of Apex calls within the Lightning Web Components (LWC) framework often involves careful consideration of input properties. When employing the wire decorator to facilitate Apex calls with multiple input properties, encountering the scenario where one of these properties is undefined can pose a challenge. The consequence is a failure to trigger the intended Apex call, hindering the expected flow of data.</p><h3 style="text-align: left;">The Challenge:</h3><p>In a typical LWC setup, the wire decorator enables seamless communication between the client-side component and the server-side Apex controller. However, when dealing with multiple input properties, dependencies between them can become critical. This becomes especially apparent when certain properties rely on data fetched from another wire service, such as the getRecord service.</p><p><br /></p><p>Consider a example scenario where the accountId and contactId properties are integral to an wire Apex call, and their values are dependent on data obtained from a getRecord wire service. While successfully populating one of these properties with the received data, it becomes apparent that the second wire service fails to trigger when the property is undefined.</p><h3 style="text-align: left;">How to Resolve:</h3><p>A straightforward resolution to this challenge involves proactively addressing undefined properties. By assigning blank values to properties that might initially be undefined, you create a more robust and predictable flow for your Apex calls.</p><p><br /></p><p>Here's a closer look at the solution in action:</p><p><br /></p>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7808771366219927"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="2550029847"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<pre><code> @wire(getRecord, { recordId: '$recordId' })
wiredRecord({ error, data }) {
if (data) {
// Process data and populate properties
this.accountId = data.fields.AccountId.value || ''; // Assigning a blank value if undefined
this.contactId = data.fields.ContactId.value || ''; // Assigning a blank value if undefined
} else if (error) {
// Handle error
console.error('Error fetching record:', error);
}
}
@wire(triggerApexCall, { accountId: '$accountId', contactId: '$contactId' })
wiredApexCall({ error, data }) {
if (data) {
// Process data from the Apex call
console.log('Received data from Apex call:', data);
} else if (error) {
// Handle error
console.error('Error in Apex call:', error);
}
}
</code></pre><br />
<p> By adopting this approach, you ensure that both properties, accountId and contactId, are consistently defined before triggering the subsequent Apex call. This not only resolves the issue but also promotes a more reliable and resilient architecture within your Lightning Web Components.
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7808771366219927"
crossorigin="anonymous"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="2550029847"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
Conclusion:
Understanding the nuances of data flow and dependency management in LWC is essential for building robust and effective components. Addressing challenges like the one discussed here not only resolves immediate issues but also contributes to a more maintainable and scalable codebase. By proactively handling undefined properties, you enhance the predictability of your Apex calls, fostering a smoother user experience in your Lightning Web Components.</p>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-61491010350672687272022-12-27T06:52:00.004-08:002022-12-27T07:01:38.708-08:00Call Lightning Web Component in Quick Action Salesforce<script async="" crossorigin="anonymous" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7808771366219927"></script><h2 style="text-align: left;"> Lightning Web Component in Quick Action</h2><div>In this post, we will see how to add or show a Lightning web component in salesforce quick actions. When salesforce introduced LWC first time, LWC in quick action was not available, that time we encapsulated LWC component on Aura component and achieved this. But as part of the Salesforce summer release, they introduced this feature.</div><div><br /></div><h3 style="text-align: left;">Add LWC in Quick Action</h3><div><div>Define Component Metadata in the Configuration .xml File</div><div><br /></div><div>In targets, add lightning__RecordAction as a target to designate the Lightning web component as a quick action on a record page.</div><div>Add a targetConfig and set targets to lightning__RecordAction.</div><div>Set actionType to ScreenAction.</div></div><div><br /></div><h4 style="text-align: left;">Example for LWC as Quick Action</h4><div><span style="font-family: inherit;">Create a new LWC component: <b>l<span style="background-color: white; font-size: 14px; white-space: pre;">wcQuickAction</span></b></span></div><div><span style="font-family: inherit;"><br /></span></div><div><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;">
</span></div><div><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;"><b>lwcQuickAction.xml</b></span></div><div><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;"><pre><code><lightningcomponentbundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiversion>55.0</apiversion>
<isexposed>true</isexposed>
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetconfigs>
<targetconfig targets="lightning__RecordAction">
<actiontype>ScreenAction</actiontype>
</targetconfig>
</targetconfigs>
</lightningcomponentbundle>
</code></pre>
</span></div><div><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;"><b>lwcQuickAction.js
</b></span><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;"> </span></div><div><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;"><pre><code>import { LightningElement, api, wire } from 'lwc';
import { CloseActionScreenEvent } from 'lightning/actions';
export default class LwcQuickAction extends LightningElement {
@api recordId;
@api objectApiName;
handleCancel(event) {
// Add your cancel button implementation here
this.dispatchEvent(new CloseActionScreenEvent());
}
}
</code></pre></span></div><div><span style="background-color: white; font-family: inherit; font-size: 14px; white-space: pre;"><b>lwcQuickAction.html
</b>
</span><pre><code><template>
<lightning-quick-action-panel header="Test LWC Quick Action">
<p>This is Test LWC component in quick action</p>
<div slot="footer">
<lightning-button variant="neutral" label="Cancel" onclick={handleCancel}></lightning-button>
</div>
</lightning-quick-action-panel>
</template>
</code></pre>
</div><script async="" crossorigin="anonymous" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7808771366219927"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
If we want to display a standard header and footer then we can use "lightning-quick-action-panel" tag.
For closing the quick action on a custom button click, we need to import "CloseActionScreenEvent" from 'lightning/actions' and dispatch that in an event.<div><br /></div><h4 style="text-align: left;">Output:</h4><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/a/AVvXsEgEMHij2EkGrRRu764hQhW_FhJwJbb3fJlZ85UG3_PIODuStARyNY_dPpKhCJTOyKOmq1nVcICB_DUDZqbCaEkVZr7k4mK1ErHYIcN--l7Ngil32vn_1brHsebscBzAUyk1TL3xXRkIJrHQEd-lnqq9ENaHLWY8lSfNDayUankywPj-G-Y6Qzfw_Tlpzg" style="margin-left: 1em; margin-right: 1em;"><img alt="Call Lightning Web Component in Quick Action Salesforce" data-original-height="426" data-original-width="1338" src="https://blogger.googleusercontent.com/img/a/AVvXsEgEMHij2EkGrRRu764hQhW_FhJwJbb3fJlZ85UG3_PIODuStARyNY_dPpKhCJTOyKOmq1nVcICB_DUDZqbCaEkVZr7k4mK1ErHYIcN--l7Ngil32vn_1brHsebscBzAUyk1TL3xXRkIJrHQEd-lnqq9ENaHLWY8lSfNDayUankywPj-G-Y6Qzfw_Tlpzg=s16000" title="Output Lightning Web Component in Quick Action Salesforce" /></a></div><br /><br /></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-19550972530989974492021-10-16T07:28:00.001-07:002021-10-16T07:28:05.121-07:00How to get RecordTypeId Based On RecordType Name In Apex Salesforce<h2 style="text-align: left;">Get RecordTypeId Based On RecordType Name In Apex</h2><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijdA4gxi6L9K930iJWcnmd522hwPJQfAMaSn331LQB8jSFfU1EMWuiT0f6gbVjpcqmYZCycX0hKE1KO_0-gefu4BTTGuW_O9_B5KxbsIxaDW9YUPuHMb-ZGduLh5Wqxed8fU3P9ITuDV8J/s867/Get+RecordTypeId+In+Apex.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Get RecordTypeId Based On RecordType Name In Apex" border="0" data-original-height="401" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijdA4gxi6L9K930iJWcnmd522hwPJQfAMaSn331LQB8jSFfU1EMWuiT0f6gbVjpcqmYZCycX0hKE1KO_0-gefu4BTTGuW_O9_B5KxbsIxaDW9YUPuHMb-ZGduLh5Wqxed8fU3P9ITuDV8J/w640-h296/Get+RecordTypeId+In+Apex.jpg" title="Get RecordTypeId Based On RecordType Name In Apex example" width="640" /></a></div><br /><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div dir="ltr" style="text-align: left;" trbidi="on">In many use cases, we need to check recordtype conditions in apex logic. Below is the same peace of code that gives recordtypeId of given sobject name and recordType label.</div><div dir="ltr" style="text-align: left;" trbidi="on"><br /></div><div dir="ltr" style="text-align: left;" trbidi="on"><div dir="ltr" trbidi="on">
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-7808771366219927"
crossorigin="anonymous"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<pre><code>
String egRecordTypeID = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Record Type Label').getRecordTypeId();
</code></pre>
</div><div><br /></div><div>Here we need to provide Sobject name in place of "Case" and recordType label in place of "Record Type Label"</div></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-89581743511765462982021-07-01T21:42:00.023-07:002021-07-01T22:01:12.528-07:00disconnectedCallback () in LWC with example<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNrOn_acoyx9WWTeT_wiBpe14nKXosye5o_q06RNjs1k2kQru7YXdw_w7KlIo6Vlb4ynFy9eWGTgpbAfRpUaKqSFcDHHuEqfE_x2o-qY4XLDcRpINJQsL5PRzg61bz-s4531WKS2oYTln0/s867/disconnectedCallback+in+LWC+with+Example.jpg" style="margin-left: 1em; margin-right: 1em;"><img alt="disconnectedCallback in LWC with Example" border="0" data-original-height="401" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiNrOn_acoyx9WWTeT_wiBpe14nKXosye5o_q06RNjs1k2kQru7YXdw_w7KlIo6Vlb4ynFy9eWGTgpbAfRpUaKqSFcDHHuEqfE_x2o-qY4XLDcRpINJQsL5PRzg61bz-s4531WKS2oYTln0/w640-h296/disconnectedCallback+in+LWC+with+Example.jpg" title="disconnectedCallback in Lightning Web Components with Example" width="640" /></a></div><p><br /></p><h2 style="text-align: left;"> What is disconnectedCallback(): </h2><p>The <b>disconnectedCallback</b>() is one of the life cycle functions of modern web components. </p><h4 style="text-align: left;">When disconnectedCallback() fired?</h4><p>It gets invoked automatically when the corresponding web component gets removed from DOM. If we need to perform any logic when the component is removed from DOM, that logic can be added in disconnectedCallback(). This hook flows from Parent component to child. We use disconnectedCallback() to purging caches or removing event listeners that are created on connectedCallback().</p><h3 style="text-align: left;">Also Check: <a href="https://www.salesforcepoint.com/2020/10/connectedcallback-in-lightning-web.html" target="_blank">connectedCallback() LWC with example</a>.</h3><div><h3 style="text-align: left;">disconnectedCallback() in LWC Example</h3></div><p>In this example, we have two components. Those are 'disconnectedCallbackParentLwc' and 'disconnectedCallbackChildLwc'. Here disconnectedCallbackChildLwc referred in parent component. In the parent component, we have a button 'Show/Hide' to show and hiding the child component. Initially, the child component displayed, once users click on the button 'disconnectedCallbackChildLwc' the child component removed from DOM. Since the component getting removed from DOM, disconnectedCallback function on the child component gets invoked and an alert will appear.</p>
<br />
<b>disConnectedCallbackChildLwc.js</b>
<pre><code>import { LightningElement } from 'lwc';
export default class DisConnectedCallbackChildLwc extends LightningElement {
disconnectedCallback() {
console.log('child disconnected callback')
}
}</code></pre><br />
<b>disConnectedCallbackChildLwc.html</b>
<pre><code><template>
<p>I am child LWC component</p>
</template> </code></pre><br />
<b>disConnectedCallbackParentLwc.js</b>
<pre><code>import { LightningElement } from 'lwc';
export default class DisConnectedCallbackParentLwc extends LightningElement {
show = true;
handleShowHide() {
this.show = !this.show;
}
}</code></pre><br />
<b>disConnectedCallbackParentLwc.html</b>
<pre><code><template>
<lightning-card title="disconnectedCallback Example">
<p>Parent LWC component</p>
<lightning-button variant="brand" slot="actions" label="Show/Hide" onclick={handleShowHide}
class="slds-m-left_x-small"></lightning-button>
<template if:true={show}>
<c-dis-connected-callback-child-lwc></c-dis-connected-callback-child-lwc>
</template>
</lightning-card>
</template></code></pre>
<br/>
<b>Output</b><br/>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/hVe80-djWvY" title="YouTube video player" width="560"></iframe>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-8999199775363901662021-01-08T01:01:00.006-08:002021-01-08T01:10:40.656-08:00How to display Toast messages in LWC<h2 style="text-align: left;"> How to display Toast messages in Lightning Web Components</h2><div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4iC4OiHQuv6KL6cIgxJmxSxTTMSF8guRjl5ExWNn3xrfoXhyxW1RXMNi4n5kdNN3WHjEh6SQ0e3p9hccAatd2YZnrRKqShb1J7k5ZgxtY5KQ2q3klqkRfwBR9VV6_8HP8R7EYPYfx55uW/s1069/How+to+show+Toast+Notifications+in+LWC.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="How to display Toast messages in LWC" border="0" data-original-height="495" data-original-width="1069" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg4iC4OiHQuv6KL6cIgxJmxSxTTMSF8guRjl5ExWNn3xrfoXhyxW1RXMNi4n5kdNN3WHjEh6SQ0e3p9hccAatd2YZnrRKqShb1J7k5ZgxtY5KQ2q3klqkRfwBR9VV6_8HP8R7EYPYfx55uW/w640-h296/How+to+show+Toast+Notifications+in+LWC.jpg" title="How to show Toast messages in Lightning Web Components" width="640" /></a></div><div><br /></div><div>A lightning web component can send a toast notification that can be inform users of a success, error, or warning information. If we want to show a toast message notification in Lightning Experience or Lightning communities, then we need to import ShowToastEvent function from the lightning/platformShowToastEvent module. So that we can create <b>ShowToastEvent </b>in the function wherever we want. ShowToastEvent contains title, message, messageData, variant, mode parameters.</div><div><br /></div><div><b>title</b>: It is String attribute. Used for showing title of the toast and displayed as a heading.</div><div><div><b>message</b>: It is a String attribute. It is used for showing message in the toast.</div><div><b>variant</b>: It is a String attribute. It controls theme and icon displayed in the toast notification. We can give Success, Info, Error Warning values based on requirement.</div><div><b>mode</b>: It is a string to define how toast notification should persistent. Valid values: sticky, pester, dismissable .</div><div><ul style="text-align: left;"><li><b>sticky</b>: If we use this, toast notification will not be closed automatically, user need to click on close button to close toast notification.</li><li><b>dismissable</b>: it's a default value. If we use this, user can see close button & toast notification closed automatically after 3 seconds.</li><li><b>pester</b>: If we use this option, toast notification closed automatically after 3 seconds & user can't see close button.</li></ul></div></div><h3 style="text-align: left;">Example: Show Toast messages in Lightning Web Components(LWC)</h3><div>In below example we have four buttons, I.e Success, Info, Warning, Error. When particular button click event happens, we are dispatching <b>ShowToastEvent</b> event in the corresponding functions. </div><div><br /></div><div><br /></div><div><br /></div></div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>lwcShowToast.js</b>
<pre><code>
import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class LwcShowToast extends LightningElement {
//Sample Success Toast message code
showSuccessNotification() {
const evt = new ShowToastEvent({
title: "Success",
message: "This is sample success message",
variant: "success",
});
this.dispatchEvent(evt);
}
//Sample code for showing error message in Toast
showErrorNotification() {
const evt = new ShowToastEvent({
title: "Error",
message: "This is sample error message",
variant: "error",
});
this.dispatchEvent(evt);
}
//Sample code for showing warning message in Toast
showWarningNotification() {
const evt = new ShowToastEvent({
title: "Warning",
message: "This is sample warning message",
variant: "warning",
mode: "sticky"
});
this.dispatchEvent(evt);
}
//Sample code for showing Info message in Toast
showInfoNotification() {
const evt = new ShowToastEvent({
title: "Info",
message: "This is sample info message",
variant: "info",
mode: "pester"
});
this.dispatchEvent(evt);
}
}
</code></pre><br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>lwcShowToast.js</b>
<pre><code>
<template>
<lightning-card title="Toast Messages" icon-name="custom:custom19">
<div class="slds-p-around_medium">
<lightning-button variant="success" label="Show Success" onclick={showSuccessNotification}></lightning-button>
<lightning-button variant="destructive" label="Show Error" onclick={showErrorNotification}></lightning-button>
<lightning-button variant="destructive-text" label="Show Warning" onclick={showWarningNotification}></lightning-button>
<lightning-button label="Show Info" onclick={showInfoNotification}></lightning-button>
</div>
</lightning-card>
</template>
</code></pre>
<h4 style="text-align: left;">Output of Show Toast Message Notifications in LWC :</h4>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/iBSoyIqKRxQ" width="560"></iframe><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-54138366993677744752021-01-03T06:44:00.001-08:002021-01-03T06:44:32.776-08:00How To Get Current Record Id In LWC (Lightning Web components)<h2 style="text-align: left;">Get Record Id dynamically in LWC</h2><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgDKBeEHOjK64lfE6mbYiXB5dZ7IEsXAUATCjjiD6-KWfGz240N093Re_LcT3iw2_j8HD2XvuONRd1r1qhVsG76Yd_hrhS9c98m7Jq_Ei20iH2sKdoTsjNDD24fuP0sQOcvpSZxcQ8N4FeC/s867/How+To+Get+Current+Record+Id+In+LWC+-Lightning+Web+components+Example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="How To Get Current Record Id In LWC -Lightning Web components Example" border="0" data-original-height="401" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgDKBeEHOjK64lfE6mbYiXB5dZ7IEsXAUATCjjiD6-KWfGz240N093Re_LcT3iw2_j8HD2XvuONRd1r1qhVsG76Yd_hrhS9c98m7Jq_Ei20iH2sKdoTsjNDD24fuP0sQOcvpSZxcQ8N4FeC/w640-h296/How+To+Get+Current+Record+Id+In+LWC+-Lightning+Web+components+Example.png" title="How To Get Current Record Id In LWC Example" width="640" /></a></div><div>In many scenarios we need to have current record id in the lightning web component. Id we want get current record id then we need to define "recordId" prublic property in corresponding lwc component JavaScript file and the lightning web component should be added into lightning record page.</div><h3 style="text-align: left;"> How To Fetch Current Record Id In Lightning Web component Example</h3><div><br /></div>
<b>lwcGetRecordId.js</b><br />
<pre><code>
import { LightningElement, api } from 'lwc';
export default class LwcGetRecordId extends LightningElement {
@api recordId;
}
</code></pre>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>lwcGetRecordId.html</b><br />
<pre><code>
<template>
Current Record Id : {recordId}
</template>
</code></pre><br />
<b>Output:</b>
Add above ligtning web component to any of the record page(Ex: Account, contact, opportunity....)<br />
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhlaYaYkYEajtDy7vzt1cbRZUvqw7aGaxKTbo8IUqtHQG7SIqBVayun_P5XF2DOhKhvwzEa-SxzcLVpmviQZ1iRS418sqPJDZbduvep6uEjLCXnEJsjKCRQD_HJFOSBtQxaQReqrlYBjFZn/s424/How+to+get+current+record+id+in+LWC.JPG" style="display: block; padding: 1em 0px; text-align: center;"><img alt="How to get current record id in Lightning Web Component" border="0" data-original-height="70" data-original-width="424" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhlaYaYkYEajtDy7vzt1cbRZUvqw7aGaxKTbo8IUqtHQG7SIqBVayun_P5XF2DOhKhvwzEa-SxzcLVpmviQZ1iRS418sqPJDZbduvep6uEjLCXnEJsjKCRQD_HJFOSBtQxaQReqrlYBjFZn/s600/How+to+get+current+record+id+in+LWC.JPG" title="How to get current record id in Lightning Web Components" width="600" /></a></div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8707943299537466355.post-73900085242227050812020-12-23T23:47:00.007-08:002020-12-24T22:40:55.815-08:00How to pass values from child to parent lightning aura component with Component Event<div style="text-align: left;">
<h2 style="text-align: left;"> How to pass Data from child lightning aura component to parent lightning
aura component & Fire Parent component function from child component function</h2>
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZ6wtj8zT8GL5tBuCiXdatkcOgGP1WXkuCBN9t9a_w-Q0xphfXDo-LS0FatYHeKgC3zVSrA2agRKFbA8iRZE_5B0a7bR4GAlA4z7w9Y69EDjgjbW-ZoCsYJrjxUdhH_2uVhD6lu6tAzR96/s867/Pass+Data+From+Child+Lightning+Aura+Component+to+Parent+Lightning+Aura+Component.jpg" style="margin-left: 1em; margin-right: 1em;"><img alt="How to Pass Data From Child Lightning Aura Component to Parent Lightning Aura Component" border="0" data-original-height="401" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgZ6wtj8zT8GL5tBuCiXdatkcOgGP1WXkuCBN9t9a_w-Q0xphfXDo-LS0FatYHeKgC3zVSrA2agRKFbA8iRZE_5B0a7bR4GAlA4z7w9Y69EDjgjbW-ZoCsYJrjxUdhH_2uVhD6lu6tAzR96/w640-h296/Pass+Data+From+Child+Lightning+Aura+Component+to+Parent+Lightning+Aura+Component.jpg" title="How to Fire Parent Lightning Aura Component Function From Child Component Function" width="640" /></a></div><br /><div><br /></div><div>If we need to pass values from child aura component to parent, we can't pass directly, for that we need to
create custom lightning event.</div>
<div><br /></div>
<div><b>Steps for child to parent aura component communication:</b></div>
<div> 1. First we need to create custom <b>Component</b> event with required attributes (for passing values from child to
parent). eg: compEvent</div>
<div><br /></div>
<div>2. We need to register event on child component using <aura:registerEvent>.</div>
<div>examle: <pre><code><aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/></code></pre></div>
<div><br /></div>
<div>3. <b>Fire an Event</b>: Fire an Event when some event occurs on child component(Eg: Button onclick, onchange of Input
Text...).</div>Example:
<pre><code>var compEvent = component.getEvent("sampleComponentEvent");
compEvent.setParams({"message" : "Static Text" });
compEvent.fire();</code></pre><br />
<div>4. We need to handle event on Parent Component. Handler name and registerEvent name should be same. We can
invoke function with the help of "action" attribute.</div>
<div>Example:<pre><code> <aura:handler name="sampleComponentEvent" event="c:compEvent"
action="{!c.handleComponentEvent}"/></code></pre></div>
<div><br /></div>
<div>When the child function gets fired, it calls custom event and pass required parameter’s. After that event
invokes Handler method on Parent component(Eg: handleComponentEvent). By using "
event.getParam("eventAttributeName"); " we can retrieve values that are passed to custom event.</div>
<div><br /></div>
<h3 style="text-align: left;">Example: Fire Parent Lightning Aura Component function from Child component and pass
parameters.</h3>
<div><b>compEvent</b> (component Event):</div>
<pre><code><aura:event type="COMPONENT">
<aura:attribute name="message" type="String"/>
</aura:event></code></pre>
<br />
<div><b>childComponentCmp</b></div>
<pre><code>
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global" >
<aura:attribute name="enteredText" type="String"/>
<aura:registerEvent name="sampleComponentEvent" type="c:compEvent"/>
<div class="slds-box slds-p-around_medium">
<h2>This is Child Component</h2>
<lightning:input label="Enter Name" aura:id="name" value ="{!v.enteredText}" />
<lightning:button class="slds-m-top_small" variant="brand" label="Pass Value To Parent" title="Click Here" onclick="{! c.handleClick }"/>
</div>
</aura:component>
</code></pre>
<br />
<div><b>childComponentCmpController.js</b></div>
<pre><code>
({
handleClick : function(component, event, helper) {
var compEvent = component.getEvent("sampleComponentEvent");
compEvent.setParams({
"message" : component.get("v.enteredText")
});
compEvent.fire();
}
})
</code></pre>
<br /><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<div><b>ParentComponentCmp</b></div>
<pre><code>
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global" >
<aura:attribute name="enteredValue" type="String" />
<aura:handler name="sampleComponentEvent" event="c:compEvent" action="{!c.handleComponentEvent}"/>
<c:childComponentCmp/><br /><br />
<div class="slds-box slds-p-around_medium">
<h2>This is Parent Component</h2>
value entered on child component input Box: <b>{!v.enteredValue}</b>
</div>
</aura:component>
</code></pre>
<br />
<b>ParentComponentCmpController.js</b>
<pre><code>
({
handleComponentEvent : function(component, event, helper) {
var valueFromChild = event.getParam("message");
alert(valueFromChild)
component.set("v.enteredValue", valueFromChild);
}
})
</code></pre>
<br />
<b>Output</b><br />
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/ojmkD4nSVmM" width="560"></iframe>
</div><div style="text-align: left;"><b><br /></b></div><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8707943299537466355.post-90223860302346632432020-11-08T00:17:00.006-08:002020-11-08T21:01:23.853-08:00How To Access Custom Label In LWC<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgDSvy8cfBLSeslx9rXPcY26DfV8_Wolk4AdCBTzIG1Ugj1_mP_FkQtwAOCZ2TprPOjz1KEZcMnIsMpFb7Zmeiau6b1HzMr_xtwhPs1ETuqpqSCX6jL4jKIv4zGKPc7mCyaI0K58rDHuWhX/s867/How+To+Access+Custom+Label+In+LWC.jpg" style="margin-left: 1em; margin-right: 1em;"><img alt="How To Access Custom Label In LWC" border="0" data-original-height="401" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgDSvy8cfBLSeslx9rXPcY26DfV8_Wolk4AdCBTzIG1Ugj1_mP_FkQtwAOCZ2TprPOjz1KEZcMnIsMpFb7Zmeiau6b1HzMr_xtwhPs1ETuqpqSCX6jL4jKIv4zGKPc7mCyaI0K58rDHuWhX/w640-h296/How+To+Access+Custom+Label+In+LWC.jpg" title="How to refer Custom Label In LWC" width="640" /></a></div><br /><h1><br /></h1><h1>How to get Custom Label value in LWC (Lightning Web Components):</h1>
Usage of Custom Label: We know that we use custom label for error messages, constants and storing values which are translated into specific language by using translation workbench.<br />
<h2>How to access Custom Label in LWC components</h2>
For accessing custom label value we need to import it from salesforce/label module. check below.
<br /> <pre><code>import labelName from '@salesforce/label/labelApiName';</code></pre>
<h2>
Example: Accessing custom label in lightning web component</h2>
Create custom label in your org. Add <b>Hello_World</b> as <b>Name </b>and "<b>Hellow World! Welcome to salesforcepoint.com</b>" as <b>Value</b>. <div><br /></div><div><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>customLabelLwc.js</b><br />
<pre><code>import { LightningElement } from 'lwc';
//importing custom label to 'WELCOME_MESSAGE'
import WELCOME_MESSAGE from '@salesforce/label/c.Hello_World';
export default class CustomLabelLwc extends LightningElement {
message = WELCOME_MESSAGE; //assigning WELCOME_MESSAGE value to "message" property
}</code></pre>
<br /><br /><b>customLabelLwc.html</b><br />
<pre><code><template>
<div class="slds-box slds-theme_shade slds-align_absolute-center">
<h1>{message}</h1>
</div>
</template></code></pre>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br /><h3>Output:</h3>
<div class="separator" style="clear: both;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijTU90GMS2sWqKGIWUEQcuOXY33MC6yZi9GMRjqhCmvd7IFUFrZVz3hUyGkn2_bGLyO3-B3xbWj9Gxw1MYzvaWNs0XEky3V2TOLI_CKxnRaNynCBJJTQVmiw8xgnk1FboWa92l2z6Xy-GV/s835/Output+of+custom+label+in+lwc.jpg" style="display: block; padding: 1em 0px; text-align: center;"><img alt="How To Access Custom Label In LWC example" border="0" data-original-height="73" data-original-width="835" height="55" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijTU90GMS2sWqKGIWUEQcuOXY33MC6yZi9GMRjqhCmvd7IFUFrZVz3hUyGkn2_bGLyO3-B3xbWj9Gxw1MYzvaWNs0XEky3V2TOLI_CKxnRaNynCBJJTQVmiw8xgnk1FboWa92l2z6Xy-GV/w640-h55/Output+of+custom+label+in+lwc.jpg" title="How To Access Custom Label In LWC example output" width="640" /></a></div></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-83951447739426975682020-10-01T06:41:00.011-07:002023-03-28T08:17:38.956-07:00connectedCallBack() In LWC With Example<h2 style="text-align: left;"><span>LWC connectedCallBack()</span></h2><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjI0HuA-aKh9dSYO2G4Bz94ba8wEuX8QZslZMeXfNyR_I7uIePQjtKqtXbBRsEtKpZ4CdS2IEk7PXeindIL3VX7xKhjuEU-pbfR_TJa6MrQBhzGLP6aRFXcBmszXIe9MhmiFoN5qGyOlSN2/s867/connectedCallback+in+web+components.png" style="margin-left: 1em; margin-right: 1em;"><img alt="connectedCallBack in Lwc" border="0" data-original-height="401" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjI0HuA-aKh9dSYO2G4Bz94ba8wEuX8QZslZMeXfNyR_I7uIePQjtKqtXbBRsEtKpZ4CdS2IEk7PXeindIL3VX7xKhjuEU-pbfR_TJa6MrQBhzGLP6aRFXcBmszXIe9MhmiFoN5qGyOlSN2/w640-h296/connectedCallback+in+web+components.png" title="connectedCallBack in web components" width="640" /></a></div><br /><div><br /></div><div>This is one of the life cycle hooks in web component JavaScript. <b>connectedCallBack function invokes/fires automatically when a certain lwc component is inserted into web dom</b>. It works like an init handler in the lightning aura component, we can say it is <b>lwc init</b> handler. </div><h3 style="text-align: left;"><span style="font-weight: normal;">Important Points about ConnectedCallBack()</span></h3><div style="text-align: left;"><ul style="text-align: left;"><li>It flows from the parent to child component. I.e if the main component has inner component/child components then, ConnectedCallBack function on parent is invoked first, and then ConnectedCallBack of child lwc component will be fired.</li><li>In this function, we can access only host element i.e template. </li><li>By using "this.template" we can access the host element.</li><li>It's invoked after the constructor hook fired.</li><li>If we want to fire any logic on component load (for example dispatching the event, assigning values to properties) then we should use ConnectedCallBack life cycle hook.</li></ul><h3 style="text-align: left;">Examples for connectedCallBack in LWC</h3><div>These are the basic example to understand connectedCallback function. </div><div><b><span style="color: red;">In this example, we need to display the list of contacts on the table. While the table is loading we have to show the spinner.</span></b></div><div><b><br /></b></div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><div><b>AccountController</b></div><br />
<pre><code>public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList(){
return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5];
}
}</code></pre><br />
<div><b>connectedCallbackLwc.html</b></div>
<br />
<pre><code><template>
<template if:true={isSpinner}>
<div class="spinner">
<lightning-spinner alternative-text="Loading" size="medium"></lightning-spinner>
</div>
</template>
<lightning-card title="connectedCallback Example">
<lightning-datatable data={accountList} columns={cols} key-field="Id">
</lightning-datatable>
</lightning-card>
</template></code></pre><br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<div><b>connectedCallbackLwc.js</b></div><div><br />
<pre><code>import { LightningElement, wire, track } from 'lwc';
import getLatestAccounts from '@salesforce/apex/AccountController.getAccountList';
const COLS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Stage', fieldName: 'Phone', type: 'text' },
{ label: 'Amount', fieldName: 'Industry', type: 'text' }
];
export default class ConnectedCallbackLwc extends LightningElement {
cols = COLS;
@track isSpinner = false;
@track accountList = [];
connectedCallback() {
<b>this.isSpinner = true;</b>
}
@wire(getLatestAccounts) fetchAccList(result) {
<b>this.isSpinner = false;</b>
if (result.data) {
this.accountList = result.data;
this.error = undefined;
} else if (result.error) {
this.error = result.error;
this.accountList = [];
}
}
}</code></pre><br />
</div><div><b>LWC connectedCallBack() Output</b>:</div>
<iframe allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/_0h_eEaKiDU" width="560"></iframe>
</div><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
In above example, we make "isSpinner" equal to true in connectedCallback function, so that we will see spinner on the page load. Once page data loaded we turned off spinner by making "isSpinner" equal to false in fetchAccList wired functionUnknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-8682086272816537582020-09-20T07:23:00.002-07:002020-09-20T07:23:45.939-07:00How to align Lightning Button To Center, Right Or Left in LWC & Aura Components<h2 style="text-align: left;">Lightning Button Alignment</h2><div>In many cases we need button alignment to left, center or right. Event though we used correct slds classes, alignment will be not at expected position. In that cases we need to use "slds-clearfix" class for above div of the button, so that we can able to display lightning button at required place. </div><div><br /></div><div>Slds CSS class for center alignment: <b>slds-align_absolute-center</b></div><div>Slds CSS class for right alignment: <b>slds-float_right</b></div><div>Slds CSS class for left alignment: <b>slds-float_left</b></div><h3 style="text-align: left;">Button Alignment in LWC (Lightning Web Components)</h3><div><b>ButtonAlignmentInLwc.html</b></div><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<pre><code><template>
<div class="slds-clearfix">
<lightning-button label="Left" class="slds-float_left"></lightning-button>
</div>
<div class="slds-clearfix">
<lightning-button label="I am Center" class="slds-align_absolute-center"></lightning-button>
</div>
<div class="slds-clearfix">
<lightning-button label="I am Right" class="slds-float_right"></lightning-button>
</div>
</template></code></pre><h3 style="text-align: left;">Button Alignment In Lightning Aura Components:</h3>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>ButtonAlignmentInAura.cmp</b><br />
<pre><code><aura:component >
<div class="slds-clearfix">
<lightning:button label="Left" class="slds-float_left"/>
</div>
<div class="slds-clearfix">
<lightning:button label="I am Center" class="slds-align_absolute-center"/>
</div>
<div class="slds-clearfix">
<lightning:button label="I am Right" class="slds-float_right"/>
</div>
</aura:component></code></pre><h3 style="text-align: left;">Output</h3><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijenC0fdrHiDumfk0JZSHTmtP9rVIUkfSRG-y95ZAoE-R9lfdNH23t3VlcgUbYf8qsNDB0uAcJrPwXjpvE0P2VOdLD16DaHFhe56rgVoSS_K8ap9wzBZe2SHno6_rweiXuUn9VL4xaf9bx/s509/Slds+Button+Alignment.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Slds Lightning Button Alignment" border="0" data-original-height="125" data-original-width="509" height="158" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEijenC0fdrHiDumfk0JZSHTmtP9rVIUkfSRG-y95ZAoE-R9lfdNH23t3VlcgUbYf8qsNDB0uAcJrPwXjpvE0P2VOdLD16DaHFhe56rgVoSS_K8ap9wzBZe2SHno6_rweiXuUn9VL4xaf9bx/w640-h158/Slds+Button+Alignment.jpg" title="Slds Lightning Button Alignment in Lwc" width="640" /></a></div><br /><div><br /></div>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8707943299537466355.post-59584420356765714422020-09-08T08:25:00.001-07:002020-09-11T08:30:56.761-07:00Validate LWC Input Data: How To Add Validations In Input Form<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcpMntCvYAqXusLxMxm60QZhFhQCmIDCkmGYksxUb7wm6bz3LlI4Q8C4jUW4IOeYuwBMAg5NOLqUa1Xwem03OKoOqOFW9u3A39EbfScExKnMZSypGwmxayuycsAW2kp-Ys0GZn2zAqYIZQ/s1600/Validate+LWC+Input+Form+Data+How+To+Add+Validations+In+LWC+Input+Form.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="How To Add Validations In LWC Input Form" border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhcpMntCvYAqXusLxMxm60QZhFhQCmIDCkmGYksxUb7wm6bz3LlI4Q8C4jUW4IOeYuwBMAg5NOLqUa1Xwem03OKoOqOFW9u3A39EbfScExKnMZSypGwmxayuycsAW2kp-Ys0GZn2zAqYIZQ/s640/Validate+LWC+Input+Form+Data+How+To+Add+Validations+In+LWC+Input+Form.png" title="Validate LWC Input Form Data" width="640" /></a></div>
<br />
<div style="text-align: left;">
Hello folks, in this post we will see <b>how to add validations in lwc input form </b>and showing error message upon button click (most probably Save operation). In any input form we need to validate user entered data before commuting to database whether it is a insert/ update.</div>
<div>
<br />
Also Check : <a href="https://www.salesforcepoint.com/2020/06/lightning-web-componentlwc-custom-file.html" target="_blank">Custom File Upload Component Along With New Record Creation</a><br />
<br /></div>
<div>
<h2 style="text-align: left;">
<b>Example for Validate LWC Input Form Data:</b> </h2>
In below example we are going to create Contact form that contains First Name, Last Name, phone, email. Here we need to add validations like Name, email should be mandatory.<br />
<br />
<b>lwcValidateInputForm.html</b><br />
<pre><code><template>
<div class="slds-box slds-theme_default">
<div class="slds-m-around_medium">
<lightning-input type="text" max-length=12 required label="Name" onchange={onNameChange}></lightning-input>
<lightning-input type="tel" label="Phone" onchange={onPhoneChange}></lightning-input>
<lightning-input type="email" required label="Email" onchange={onEmailChange}></lightning-input>
</div>
<div>
<center>
<lightning-button label="Save" onclick={saveContact}>
</lightning-button>
</center>
</div>
</div>
</template></code></pre>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<b>LwcValidateInputForm.js</b><br />
<pre><code>import { LightningElement, track } from 'lwc';
export default class LwcValidateInputForm extends LightningElement {
@track name;
@track phone;
@track email;
onNameChange(event) {
this.name = event.detail.value;
}
onPhoneChange(event) {
this.phone = event.detail.value;
}
onEmailChange(event) {
this.email = event.detail.value;
}
saveContact() {
const isInputsCorrect = [...this.template.querySelectorAll('lightning-input')]
.reduce((validSoFar, inputField) => {
inputField.reportValidity();
return validSoFar && inputField.checkValidity();
}, true);
if (isInputsCorrect) {
//perform success logic
}
}
}</code></pre>
<br />
<b>Output:</b></div>
<iframe allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/V4ndcACZUJ8" width="560"></iframe>
</div>
<br />
If we need to make any field required then we need to mention "required" attribute in lightning-input tag so that we can show error message upon save button click. Once user click on save button, we are validating each filed by querying with the lightning-input. By using checkValidity() function we are checking each values entered in form. If all values are in required format then we can write further logic.<br />
<br />
If we don't want standard error message, we can set custom message with the help of below attributes.<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<b>message-when-value-missing:</b> Used for assigning custom error message when value missed on required field. <br />
<b>message-when-too-short:</b> Used for assigning custom error message when entered value not meeting expected length. For this we need to add one more attribute i.e <b>min-length</b>.<br />
<b>message-when-too-long:</b> Used for assigning custom error message when entered value exceeds expected length. For this we need to add one more attribute i.e <b>max-length</b>. <br />
<b>message-when-pattern-mismatch:</b> Used for assigning custom error message when entered value not matching the expected pattern. This is used for email, url, phone, password, text. For this we need to add one more attribute i.e "<b>pattern</b>".
<br />
<br />
Reference: https://developer.salesforce.com/docs/component-library/bundle/lightning-input/specification
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-46441676305570857462020-08-31T23:48:00.001-07:002020-09-01T00:04:59.508-07:00How to Use Safe Navigation Operator (?.) in Salesforce Apex | Winter 21 Release Notes<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
How to Use the Safe Navigation Operator in Apex</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2kOKtd0u1QtruUfPhQok5nS1ikJBirv58mGMHIKLGFdZPhzSvTTyciIekkx9RudMkytQ-b_TRkgixDQOMUWcBF8zo45xWns_lONDaICmnAFUNa0A-PTePaDNoCfqp4wDyhy9RTHeYFknQ/s1600/Safe+Navigation+Operator.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="How to use Safe Navigation Operator in Apex Salesforce" border="0" data-original-height="365" data-original-width="652" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2kOKtd0u1QtruUfPhQok5nS1ikJBirv58mGMHIKLGFdZPhzSvTTyciIekkx9RudMkytQ-b_TRkgixDQOMUWcBF8zo45xWns_lONDaICmnAFUNa0A-PTePaDNoCfqp4wDyhy9RTHeYFknQ/s1600/Safe+Navigation+Operator.png" title="Safe Navigation Operator in Apex" /></a></div>
<div>
<br /></div>
Hello guys, as part of salesforce winter 21 release, salesforce introduced Safe Navigation Operator( (?.) to avoid null pointer exceptions in apex. This is very useful feature for developers. If we need to check something (whether it is a object, map, list..) should not be null then we will write (?.) at the end. If the left side of the expression(?.) is null, then right side is not evaluated and result will be null.<br />
<br />
Till now we used != null condition to check object is not null like below.<br />
<br />
<pre><code>if (object!= null){
string s= object.fieldName;
}</code></pre>
<br />
we can write above code by using <b>safe navigation operator</b> like below<br />
<pre><code>string s= object?.fieldName;
</code></pre>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
Example: In this example we have a accountIdAccountMap, it contains account id as key, account record as value. We need to get name of the account.<br />
<br />
<pre><code>string accountName = accountIdAccountMap.get(accId).Name;
// this will return null pointer exception if accId not available in the map.
</code></pre>
<br />
if account not exist on map we will get null pointer exception because we accessing null object for fetching name.<br />
<br />
<h3 style="text-align: left;">
Traditional approach to avoid above null pointer exception<span style="font-weight: normal;">:</span></h3>
<pre><code>if(accountIdAccountMap.get(accId) != null) {
accountName = accountIdAccountMap.get(accId).Name;
}</code></pre>
<br />
OR<br />
<pre><code>if(accountIdAccountMap.containsKey(accId)) {
accountName = accountIdAccountMap.get(accId).Name;
}</code></pre>
</div>
<br />
<h3 style="text-align: left;">
By using Safe Navigation operator<span style="font-weight: normal;">:</span></h3>
<pre><code>string Account Name = accountIdAccountMap.get(accId)?.Name;
</code></pre>
<br />
<b>if we need to check whether map is not null then we can write</b><br />
<br />
<pre><code>accountIdAccountMap?.get(accId)?.Name;</code></pre>
</div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8707943299537466355.post-2078799689976628502020-08-28T06:12:00.001-07:002020-09-05T09:33:58.856-07:00LWC Combobox Picklist : Get Pick-list Values (With / Without Default Record Type Id)<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Fetching and Displaying Picklist Values In Lightning Web Components (LWC) : </h2>
By using "<b>lightning-combobox</b>" tag we can display picklist values in Lwc markp. In Lightning Aura Components if we want to display picklist values, we need to hit apex server and needs write logic to fetch picklist values by using dynamic schema. Even though we are write apex logic, we could not get picklist values based on recordtype name or recordTypeId, every time it shows all the values irrespective of record type. But in lightning web components we have a great privilege that don't need to hit apex for fetching picklist values. In Lwc we can get values based on recordtype name as well.<br />
<br />
By importing <b>getPicklistValues </b>or <b>getPicklistValuesByRecordType</b> from "lightning/uiObjectInfoApi" we can get picklist values in LWC JavaScript. <b>recordTypeId </b>is required parameter for both of these functions.<br />
<h3 style="-webkit-text-stroke-width: 0px; color: black; font-family: "Times New Roman"; font-style: normal; font-variant-caps: normal; font-variant-ligatures: normal; letter-spacing: normal; orphans: 2; text-align: left; text-decoration-color: initial; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px;">
Get picklist values based on recordtypeId In Salesforce LWC component</h3>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>lwcPicklistWithRecordtype.js</b><br />
<pre><code>import { LightningElement,wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import STAGE from '@salesforce/schema/Opportunity.StageName';
export default class LwcPicklistWithRecordtype extends LightningElement {
@wire(getPicklistValues,
{
recordTypeId: '01228000000XckuAAC', //pass id dynamically
fieldApiName: STAGE
}
)
stageValues;
}</code></pre>
<br />
<b>lwcPicklistWithRecordtype.html</b><br />
<pre><code><template>
<div class="slds-box">
<template if:true={stageValues.data}>
<lightning-combobox name="progress" label="Opportunity Stage" value={value}
options={stageValues.data.values} onchange={handleChange}>
</lightning-combobox>
</template>
</div>
</template></code></pre>
<br />
<b>Output</b>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-vID42WcYrEWHRoyAw9PCZadNDUGuvatj0b-KME0L2UnCuRKY4UxjXIlvdrHd_MOvhOLHAk1kYBYoo64iPPsxuRGHk5VWImkuE4ck3PE3H7abcJRD7ADE507Gz-acjFYh0yySMCHl_RwV/s1600/LWC+picklist+values+based+on+recordtype.png" imageanchor="1"><img alt="LWC picklist values based on recordtype values" border="0" data-original-height="407" data-original-width="1251" height="208" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-vID42WcYrEWHRoyAw9PCZadNDUGuvatj0b-KME0L2UnCuRKY4UxjXIlvdrHd_MOvhOLHAk1kYBYoo64iPPsxuRGHk5VWImkuE4ck3PE3H7abcJRD7ADE507Gz-acjFYh0yySMCHl_RwV/s640/LWC+picklist+values+based+on+recordtype.png" title="LWC picklist values without default recordtype id" width="640" /></a>
<br />
<h3 style="text-align: left;">
Get picklist values if we don't have recordtypes in Object In Lightning Web Components (LWC)</h3>
<div>
<div>
If object does not have record type's then use the defaultRecordTypeId property, this can be fetch from getRecordUi or getObjectInfo. See below example.</div>
</div>
<div>
<br /></div>
</div>
<b>lwcPicklistWithoutRecordtype.js</b>
<br />
<pre><code>import { LightningElement,wire } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import LeadSource from '@salesforce/schema/Contact.LeadSource';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
export default class LwcPicklistWithoutRecordtypeextends LightningElement {
@wire(getObjectInfo, { objectApiName: CONTACT_OBJECT })
contactInfo;
@wire(getPicklistValues,
{
recordTypeId: '$contactInfo.data.defaultRecordTypeId',
fieldApiName: LeadSource
}
)
leadSourceValues;
}</code></pre>
<b>lwcPicklistWithoutRecordtype.html</b>
<br />
<pre><code><template>
<div class="slds-box">
<template if:true={leadSourceValues.data}>
<lightning-combobox name="progress" label="Lead Source" value={value}
options={leadSourceValues.data.values} onchange={handleChange}>
</lightning-combobox>
</template>
</div>
</template></code></pre>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>Outut:</b>
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggEnkIAdGh4tJXwFoJu66u2qMwsPAU9gaIWHTavQ0ExFOXhJGo-9qrtzI3GXwXc-ThCNJ2LDQkaZqWC6JdwyESqoqXMQhg7nZ1TZ2xESk3sbv2qXgao2uUrrKO21QJwY0pYHlgVbKCbhq_/s1600/LWC+picklist+values+without+default+recordtype.png" imageanchor="1"><img alt="LWC picklist values based on recordtype" border="0" data-original-height="284" data-original-width="1251" height="145" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggEnkIAdGh4tJXwFoJu66u2qMwsPAU9gaIWHTavQ0ExFOXhJGo-9qrtzI3GXwXc-ThCNJ2LDQkaZqWC6JdwyESqoqXMQhg7nZ1TZ2xESk3sbv2qXgao2uUrrKO21QJwY0pYHlgVbKCbhq_/s640/LWC+picklist+values+without+default+recordtype.png" title="LWC picklist values based on recordtype" width="640" /></a></div>
Unknownnoreply@blogger.com4tag:blogger.com,1999:blog-8707943299537466355.post-19936666711070771652020-08-12T07:43:00.004-07:002020-10-01T07:03:55.293-07:00LWC refreshApex: How To Refresh Page Data in Lightning Web Component<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
refreshApex in lwc: </h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOF3UrsI5hn4MfPZ_4xMQi1ox-wSp23okFOJk46dy6OQhp3lpP3rmGC1aJUF4KHeAr3haaGYXYUP-UdPJMbviMF47sa0yFCdJe4aLyvcIrqR-CyDpuTv9jrtc230-4xah6M3ReYRSnv7dL/s1600/LWC+refreshApex-How+To+Refresh+Data+in+Lightning+Web+Component.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="refreshApex in Lightning Web Component Example" border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjOF3UrsI5hn4MfPZ_4xMQi1ox-wSp23okFOJk46dy6OQhp3lpP3rmGC1aJUF4KHeAr3haaGYXYUP-UdPJMbviMF47sa0yFCdJe4aLyvcIrqR-CyDpuTv9jrtc230-4xah6M3ReYRSnv7dL/s640/LWC+refreshApex-How+To+Refresh+Data+in+Lightning+Web+Component.png" title="refreshApex in LWC" width="640" /></a></div>
<div>
<br /></div>
In this post we are going to see how to use <b>refreshApex</b>() function in Lightning web Components with example. If we need to refresh lwc page data we should use refreshApex. We know that wire provisions data, if we use wire function or wire parameter to display data in front end, that data will not be changed or updated unless input parameters changed which are used in wire. By using refreshApex in lwc we can update wire function or wire parameter data, so that component values will be re-rendered.<br />
<br />
We need to import refreshApex function from salesforce/apex class, so that we can use it.<br />
<h3 style="text-align: left;">
refreshApex lwc example:</h3>
<div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
In below example we are displaying latest five account records in lwc data table and we have a radio button to select the record. Once we click on Delete button selected record will be deleted from apex database but not on table. So we use refreshApex() function (refreshApex(this.wiredAccountList)) to fetch latest data from server on delete success in deleteRecord function. We created "wiredAccountList" property to assign result of wire function "accList" and this property used in resfreshApex function.</div>
<div>
<br /></div>
<div>
<b>AccountController.cls</b></div>
<br />
<pre><code>public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<account> getAccountList(){
return [SELECT Id, Name,Phone,Industry FROM Account order by createddate desc LIMIT 5];
}
}</code></pre>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<div>
<b>lwcRefreshApex.js</b></div>
<br />
<pre><code>import { LightningElement, wire, track } from 'lwc';
import { deleteRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import getLatestAccounts from '@salesforce/apex/AccountController.getAccountList';
const COLS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Stage', fieldName: 'Phone', type: 'text' },
{ label: 'Amount', fieldName: 'Industry', type: 'text' }
];
export default class LwcRefreshApex extends LightningElement {
cols = COLS;
@track selectedRecord;
@track accountList = [];
@track error;
@track wiredAccountList = [];
@wire(getLatestAccounts) accList(result) {
<b> this.wiredAccountList = result;
</b>
if (result.data) {
this.accountList = result.data;
this.error = undefined;
} else if (result.error) {
this.error = result.error;
this.accountList = [];
}
}
handelSelection(event) {
if (event.detail.selectedRows.length > 0) {
this.selectedRecord = event.detail.selectedRows[0].Id;
}
}
deleteRecord() {
deleteRecord(this.selectedRecord)
.then(() => {
<b> refreshApex(this.wiredAccountList);
</b> })
.catch(error => {
})
}
}</code></pre>
<div>
<b>lwcRefreshApex.html</b></div>
<br />
<pre><code><template>
<lightning-card title="Latest Five Accounts">
<lightning-button slot="actions" label="Delete Account" onclick={deleteRecord}></lightning-button>
<lightning-datatable
data={accountList} columns={cols} key-field="Id"
max-row-selection="1" onrowselection={handelSelection} >
</lightning-datatable>
</lightning-card>
</template></code></pre>
<b>Output:</b><br />
<div>
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.blogger.com/video.g?token=AD6v5dxKq68b4LH-Lzb_ex-EBnWZv1wzxRo_JbVMu5gsjd82Jg7mDVaHbx4YY1bcNNtixGnJ4IMYrWC1LwvZQglRSA' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<br /></div>
<h3 style="text-align: left;">
LWC refreshApex() not working?</h3>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<div>
Make sure that the input parameter in the refreshApex should be total result of wire function but not only data, i.e in many cases we return { error, data } in wire function and we use data only for refresh apex, in this case refreshApex will not work. We must entire result (check above example where we return <b>result </b>not <b>{ error, data }</b> and that is assigned to one dummy variable i.e wiredAccountList and that is used as input parameter for refreshApex().</div>
</div>
Unknownnoreply@blogger.com11tag:blogger.com,1999:blog-8707943299537466355.post-80156435315285969842020-08-09T09:42:00.005-07:002020-10-01T06:55:53.951-07:00Pass Data/Values From Child LWC Component To Parent LWC Using Custom Event<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
How to Pass Values From Child to Parent component in LWC</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWh7iPQfulvxj6zt3N5zFueiCHXUqMecHXhyphenhyphenPpNKJe7GoNyyU6snaoyzpPvtf2YksCT8RDSmtf_P13wlsvNpAayduPzd8MtOeg33GAEbxH0o3aTgd564LCVEw-HO7_98SKz8blFRQs1a8k/s1600/How+to+Pass+Values+From+Child+to+Parent+component+in+LWC+example.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Pass Values data fromChild to Parent component in LWC example" border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgWh7iPQfulvxj6zt3N5zFueiCHXUqMecHXhyphenhyphenPpNKJe7GoNyyU6snaoyzpPvtf2YksCT8RDSmtf_P13wlsvNpAayduPzd8MtOeg33GAEbxH0o3aTgd564LCVEw-HO7_98SKz8blFRQs1a8k/s640/How+to+Pass+Values+From+Child+to+Parent+component+in+LWC+example.png" title="How to Pass Values From Child to Parent component in LWC example" width="640" /></a></div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
In this post we will see how to pass data from <b>child to parent in Lw</b>c. If we want to fire parent lightning web component function from child LWC component function when child function fired or if we need pass data from child LWC component to parent Lightning web component then we need to use custom events. Unlike aura component we don't to create separate event in lightning web components.<br />
<br />
<b>Steps for child to parent communication in LWC</b>:<br />
1. Define a custom event in child lightning web component.<br />
2. Add values (which needs to pass to parent lwc) to event. (optional)<br />
3. Dispatch the event.<br />
Example:<br />
<br /></div>
<pre><code>const lwcEvent= new CustomEvent('eventname', {
detail:{varible1:value, varible2 : value}
});
this.dispatchEvent(lwcEvent);</code></pre>
<br />
Here <b>eventName </b>is user defined key word for event, which is going to use in child component tag in parent component. Make sure that event name should not be starts with "<b>on</b>" word.<br />
4<b> </b>. Handle event on parent lightning web component with the "<b>oneventname</b>" handler function. Here <b>oneventname </b>is the dispathed event in child component(see above code), '<b>on'</b> should be added before event name.<br />
<br />
<pre><code><c-child-lwc-component oneventName={handleEvent}></c-child-lwc-component></code></pre><br/>
5. By using event.detail.variableName we will get value which is passed from child lwc.<br />
<h3 style="text-align: left;">
Example Scenario for Passing values from Child Lightning web component to Parent Lightning web component.</h3>
<div>
In Below example we have a child component(<b>lwcChild)</b> where we are showing list of account records. In parent component(<b>lwcParent)</b> we are referring child component. on click of record in table, we are firing custom event and dispatching the event with selected account id and then we are showing details of respective account in parent component.</div>
<div>
<br /></div>
<div>
<b>AccountController.cls</b></div>
<pre><code>public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<account> getAccountList(){
return [SELECT Id, Name,Phone,Industry FROM Account WITH SECURITY_ENFORCED LIMIT 10];
}
}</code></pre>
</div>
<br />
<b>Create new lightning web component: lwcChild</b><br />
<b>lwcChild.js</b>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="fluid" data-ad-layout="in-article" data-ad-slot="2550029847" style="display: block; text-align: center;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<pre><code>import { LightningElement, api } from 'lwc';
export default class LwcChild extends LightningElement {
@api accountList;
handleAccountClick(event) {
let selectedAccId = event.currentTarget.getAttribute("data-key");
//custom event
const passEvent = new CustomEvent('accountselection', {
detail:{recordId:selectedAccId}
});
this.dispatchEvent(passEvent);
}
}</code></pre>
<br />
<b>lwcChild.html</b>
<br />
<pre><code><template>
<table class="slds-table slds-table_bordered">
<thead>
<tr>
<th>Name</th>
<th>Phone</th>
<th>Industry</th>
</tr>
</thead>
<tbody>
<template if:true={accountList}>
<template for:each={accountList} for:item="acc">
<tr key={acc.Id} data-key={acc.Id} onclick={handleAccountClick}>
<td>{acc.Name}</td>
<td>
<lightning-formatted-phone value={acc.Phone}></lightning-formatted-phone>
</td>
<td>{acc.Industry}</td>
</tr>
</template>
</template>
</tbody>
</table>
</template></code></pre>
<b>Create new lightning web component: lwcParent</b><br />
<b>lwcParent.js</b>
<br />
<pre><code>import { LightningElement,wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';
export default class LwcParent extends LightningElement {
@track selectedAccountId;
@wire(getAccountList) accountList;
onAccountSelection(event){
this.selectedAccountId = event.detail.recordId;
}
}</code></pre>
<br />
<b>lwcParent.html</b>
<br />
<pre><code><template>
<div class="row">
<div class="column" style="float: left; width: 70%; padding: 10px;">
<div class="slds-box">
<template if:true={accountList.data}>
<c-lwc-child account-list={accountList.data} onaccountselection={onAccountSelection}></c-lwc-child>
</template>
</div>
</div>
<div class="column" style="float: right; width: 30%; padding: 10px;">
<div class="slds-box">
<div slot="actions">
<div class="slds-box">
Selected Account Information
</div>
</div>
<lightning-record-view-form record-id={selectedAccountId} object-api-name="Account">
<div class="slds-box slds-them_shade">
<lightning-output-field field-name="Name"></lightning-output-field>
<lightning-output-field field-name="Phone"></lightning-output-field>
<lightning-output-field field-name="Industry"></lightning-output-field>
</div>
</lightning-record-view-form>
</div>
</div>
</div>
</template></code></pre>
<br />
<b>Output</b>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.blogger.com/video.g?token=AD6v5dxJ2YVZixxZeztfHoUPuYfJz4W9EUJheaqBdZcfPoqnDRutkKvpD-47YflrN-EYYW761jebb6KRGLd9E5yHXA' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<b><br /></b></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-48950124643257646812020-08-03T10:26:00.000-07:002020-09-10T07:19:07.437-07:00Salesforce Lightning Web Components - LWC Interview Questions <div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Latest LWC Interview Questions </h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCm5pW6uCe-vzJKWQ0LzMHTqoYpkLM2a3gzn640QOPmHiL_pao9A1qRujy_acX5uPYGpL-XY2Ir4y2FPfVXhf3WhTF-485IqW6CtVzvxX0bUSVOXvFLXmT8_2W7MPMravJrkIc9uLFfmon/s1600/Latest+LWC+%2528Lightning+Web+Components%2529+Interview+Questions.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Latest LWC Interview Questions " border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgCm5pW6uCe-vzJKWQ0LzMHTqoYpkLM2a3gzn640QOPmHiL_pao9A1qRujy_acX5uPYGpL-XY2Ir4y2FPfVXhf3WhTF-485IqW6CtVzvxX0bUSVOXvFLXmT8_2W7MPMravJrkIc9uLFfmon/s640/Latest+LWC+%2528Lightning+Web+Components%2529+Interview+Questions.png" title="Lightning Web Components Interview Questions " width="640" /></a></div>
<div>
<br /></div>
<ol style="text-align: left;">
<li>What is LWC?</li>
<li>Difference between Lightning web components and Lightning aura components?</li>
<li><a href="https://www.salesforcepoint.com/2020/06/how-to-invoke-call-child-lightning-web.html" target="_blank">How to fire child lightning web component function from parent LWC component?</a></li>
<li>How to pass data from child LWC component to parent lightning aura component?</li>
<li>How to get dynamic record id in LWC? Answer: By using @api recordId; property we can dynamically fetch current record id in lightning web component.</li>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- salesforcepoint9_Normal Sidebar_AdSense2_1x1_as -->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="6769098577" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<li>What is difference between const, let and var types?</li>
<li>What's the difference between wire function imperative functon?</li>
<li><a href="https://www.salesforcepoint.com/2020/07/LWC-Component-In-Quick-Action-Example.html" target="_blank">Is it possible to use lwc component in quick action?</a></li>
<li>Why wire function gets invoked multiple times?</li>
<li>What is the importance of Constructor in LWC?</li>
<li>What are the differences between @api, @wire @track lwc decorators?</li>
<li>What is the purpose of refreshApex() in LWC? Ex: <a href="https://www.salesforcepoint.com/2020/06/lwc-data-table-with-checkbox-example.html">https://www.salesforcepoint.com/2020/06/lwc-data-table-with-checkbox-example.html</a></li>
<li> What is the meta data name of Lightning web component? Ans: <b>LightningComponentBundle</b></li>
<li><a href="https://www.salesforcepoint.com/2020/08/how-to-fix-cannot-assign-to-read-only.html" target="_blank">When will we get "Cannot Assign To Read Only Property Error" In LWC? How can we resolve that issue?</a></li>
<li>Can we refer lightning aura component inside Lightning web component?</li>
</ol>
<div>
Hello folks post your answers for above mentioned Lightning web component interview questions? </div>
<div>
<br /></div>
<div>
<b>Other LWC tutorials click here</b>: <a href="https://www.salesforcepoint.com/search/label/LWC">https://www.salesforcepoint.com/search/label/LWC</a></div>
</div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- links abo -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-slot="4931101293" style="display: inline-block; height: 90px; width: 180px;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-38294191391177121982020-08-02T06:02:00.002-07:002021-02-22T08:36:06.756-08:00How To Fix Cannot Assign To Read Only Property Error In LWC-Lighting Web Components <div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Fix Cannot Assign To Read Only Property Error In LWC
In Lightning web components </h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPOPlNtwlUza3k3GLrkuLhF-Wub26hpc7ghfqcFe281ccbejQWu3ZxTN_mLrKz8krvuwAQlskHt3OOdIjpPyX0Ifdy8Q8xNRKlZrLlcS2ipsipleFIzZQDWVqbeYMVaHasti7svV5bxZHF/s1600/How+To+Fix+Cannot+Assign+To+Read+Only+Property+Error+In+LWC-.png" style="margin-left: 1em; margin-right: 1em;"><img alt="How To Fix Cannot Assign To Read Only Property Error In Lightning Web Components" border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPOPlNtwlUza3k3GLrkuLhF-Wub26hpc7ghfqcFe281ccbejQWu3ZxTN_mLrKz8krvuwAQlskHt3OOdIjpPyX0Ifdy8Q8xNRKlZrLlcS2ipsipleFIzZQDWVqbeYMVaHasti7svV5bxZHF/s640/How+To+Fix+Cannot+Assign+To+Read+Only+Property+Error+In+LWC-.png" title="How To Fix Cannot Assign To Read Only Property Error In LWC-" width="640" /></a></div>
<div>
<center><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--links abo-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-slot="4931101293" style="display: inline-block; height: 90px; width: 180px;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></center>
<br /></div>
If we are trying to update public (@api) property or wired property in JavaScript function we usually get this issue. For resolving this issue, we need to <b>clone </b>that property to new variable and update it. After updating assign temporary variable to actual property.<br />
<br />
<b> Example Problem Code:
</b><br />
<pre> <code>allCheckBoxChange(event) {
for (let j = 0; j < this.allOppList.length; j++) {
this.allOppList[j].isChecked = event.detail.checked;
}
}</code></pre>
<br />
In above code "allOppList" is the data of wired property. When allCheckBoxChange() fynction
gets invoked we will get below error
Uncaught TypeError: Cannot assign to read only property '0' of object '[object Array]'<br />
<b><br /></b>
<b>Solution Code:</b><br />
<pre> <code>allCheckBoxChange(event) {
let tempAllRecords = Object.assign([], this.allOppList);
for (let j = 0; j < this.allOppList.length; j++) {
let tempRec = Object.assign({}, tempAllRecords[j]);
tempRec.isChecked = event.detail.checked;
tempAllRecords[j] = tempRec;
}
this.allOppList = tempAllRecords;
}</code></pre>
<br /><script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!--Jeevi Responsive New-->
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
In above code we are cloning wired property "allOppList" to new temporary variable tempAllRecords and after update, assigning temporary list to allOppList. In for loop we are updating every record of allOppList, so we are cloning every record and updating the cloned record and assigning back to actual record. So that we can avoid read only property issue.<br />
<br />
Note: Object.assign() function is the one of cloning method in JavaScript.</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-65735839094285662372020-08-01T22:28:00.000-07:002020-08-01T22:32:40.121-07:00How To Display [Object Object] In console.log or Alert in JavaScript (LWC & Lightning Aura Components)<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
<b>Display [Object Object] As String In JavaScript: </b></h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-cFxmd2zuc41xd93zh0lSdPu9d0s5_GnuGgNquFCbnZ6S0eNKb7Koi3CSSn-061oYiciNtqTD3G0q9Fl2djz1rgBSMKHFVibx402zAO7KvVgv15ev_k056AaXCKEwYMJhLGX3In6vYFrQ/s1600/Display+object+as+string+in+javascript.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Display Object as String in JavaScript" border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh-cFxmd2zuc41xd93zh0lSdPu9d0s5_GnuGgNquFCbnZ6S0eNKb7Koi3CSSn-061oYiciNtqTD3G0q9Fl2djz1rgBSMKHFVibx402zAO7KvVgv15ev_k056AaXCKEwYMJhLGX3In6vYFrQ/s640/Display+object+as+string+in+javascript.png" title="Display Object as String in js" width="640" /></a></div>
<center><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- links abo -->
<ins class="adsbygoogle"
style="display:inline-block;width:180px;height:90px"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="4931101293"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></center><br />
In JavaScript if we trying to print other than primitive type variables in console.log or alert, then it will returns [Object Object]. If its return output as [Object Object], we can't know output as expected or not.<br />
<br />
By using JSON.stringify() function we can print output in string format. JSON.stringify() is a predefined JavaScript function, it takes object as a input parameter and returns json string if object in JavaScript specific object structure.<br />
<b><br /></b>
<b>Example: Display Object as String in js</b><br />
<b><br /></b>
var cObj = { name: "Salesforec", age: 10, city: "CA" };<br />
console.log("cObj===>"+cObj ); //output : cObj===>"+[Object Object]<br />
console.log("cObj in String Format===>"+JSON.stringify(cObj) );<br />
// output: cObj in String Format===> { name: "Salesforec", age: 10, city: "CA" };<br />
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8707943299537466355.post-28677574147284937542020-07-26T23:50:00.001-07:002020-07-27T10:31:11.196-07:00How To Get Record Id From aura:iteration In Lightning Component<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Fetch Selected Record Id From Iteration Lightning Aura Component:</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjH65r6YMll2Im4VvmCG80DSNYNF2gprPxUsWmqZ5f72TBEOSafSRgvLRLZlRhnnGM1texQyg_Ao1aMhGJTgUQZvFloFIhoGlzIXuJRdMyH_GHW6ElWgjVXDtZQfCO1V6VwnttM8YuZmakz/s1600/Get+record+id+from+aura+iteration+lightning+component.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="402" data-original-width="867" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjH65r6YMll2Im4VvmCG80DSNYNF2gprPxUsWmqZ5f72TBEOSafSRgvLRLZlRhnnGM1texQyg_Ao1aMhGJTgUQZvFloFIhoGlzIXuJRdMyH_GHW6ElWgjVXDtZQfCO1V6VwnttM8YuZmakz/s640/Get+record+id+from+aura+iteration+lightning+component.png" width="640" /></a></div>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
If we need to fetch record id or some element from aura:iteration we can use html property dataset. By using this html dataset attributes we can pass id from component to JavaScript function when some event occurs. The name of a custom data element starts with <b>data-</b>. By using html elements, we can get not only id but we can get any element that we set for data element (ex: data-id, data-name) in lightning component.<br />
<h3 style="text-align: left;">
Example code for fetching record id in aura iteration:</h3>
In below example we are fetching all the student records, In aura iteration for div element we added data-id ="{!student.Id}". on click on student we are passing selected student id to JavaScript function handleSelect by using event.target.dataset.id. If we need to pass other attribute then we can create new data attribute, for example if we need to pass name of selected student then we add new attribute data-name and in js function we can get that attribute by using event.target.dataset.name.<br />
<br />
<b>StudentController.cls</b></div>
<pre><code> public class StudentController {
@AuraEnabled
public static List<Student__c> getStudentList() {
List<Student__c> studentList = [SELECT Id, Name FROM Student__c];
return studentList;
}
}
</code></pre>
<br /></div>
<b>StudentList.cmp</b>
<br />
<pre><code> <aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,
flexipage:availableForRecordHome,force:hasRecordId,
force:lightningQuickAction" controller="StudentController"
access="global" >
<aura:attribute name="studentList" type="List" />
<aura:handler name="init" action="{!c.fetchStudentList}" value="{!this}" />
<aura:iteration items="{!v.studentList}" var="student">
<div data-id ="{!student.Id}" class="slds-box slds-theme_shade" onclick="{!c.handleSelect}">
{!student.Name}
</div>
</aura:iteration>
</aura:component>
</code></pre>
<br />
<b>StudentListController.js</b>
<br />
<pre><code> ({
fetchStudentList : function(component, event, helper) {
var action = component.get("c.getStudentList");
action.setCallback(this, function(response) {
var state = response.getState();
if(state === 'SUCCESS') {
var studentList = response.getReturnValue();
component.set("v.studentList",studentList);
}
else {
alert('Error in getting data');
}
});
$A.enqueueAction(action);
},
handleSelect: function(component, event, helper) {
var selectedId = event.target.dataset.id;
alert(selectedId)
}
})
</code></pre>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<b>Output:</b>
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.blogger.com/video.g?token=AD6v5dxavO4r_GRlqJyDYTxvYh7MaB4FrWgRFTjyBcM5buLQWFdw8WLuzEzslWx-mqLN3yV_hgxCHmrX58gpMas1XQ' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<b><br /></b></div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-41441817480811160682020-07-26T08:20:00.001-07:002020-07-30T09:52:42.114-07:00Navigate/Redirect To Record Page Based On Record Id In LWC (Lightning Web Component)<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Redirect or Navigate to salesforce object record detail page in Lwc:</h2>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgun_UChQ2It0vDJj39x5hbY6wCWtecwb81r3H61mIeoUOZYZi0-CVtey7P-rWMpTmMQl9hg0pUzlxEoBgRdwli5YUOj_eaEiIQI403YPjteP8icFioQVkmYRb9iTX45_7P0QmwqPud6w-L/s1600/Navigate-+redirect-to-record-page-in-lwc.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="How to Navigate to record page in Lwc in lightning web component " border="0" data-original-height="402" data-original-width="867" height="294" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgun_UChQ2It0vDJj39x5hbY6wCWtecwb81r3H61mIeoUOZYZi0-CVtey7P-rWMpTmMQl9hg0pUzlxEoBgRdwli5YUOj_eaEiIQI403YPjteP8icFioQVkmYRb9iTX45_7P0QmwqPud6w-L/s640/Navigate-+redirect-to-record-page-in-lwc.jpg" title="How to Redirect to record page in Lwc" width="640" /></a></div>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
In many scenarios we need to <b>redirect</b> to record detail page upon successful record save or update into database. Below code is helpful for navigate to sobject record page in Lightning web components. For navigating to record page in lightning experience we need to use lightning navigation service.<br />
<h3 style="text-align: left;">
Implementation steps to navigate/Redirect to record page in LWC components: </h3>
For Using navigation service in Lwc we need to import <b>NavigationMixin </b>from lightning/navigation base.<br />
<pre><code>
import { NavigationMixin } from 'lightning/navigation';
</code></pre>
<br />
Then we need to Apply the NavigationMixin function to your component’s base class.<br />
<pre><code>
export default class MyCustomElement extends NavigationMixin(LightningElement) {
}
</code>
</pre>
</div>
Add new function to redirect to record page in JavaScript and specify object api name, record id in objectApiName and recordId attributes. Call this function wherever you want (Like after success return from apex).
<br />
<pre><code>
navigateToRecordPage() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: 'recordId',
objectApiName: 'ObjectApiName',
actionName: 'view'
}
});
}
</code>
</pre>
<br />
Example: in below example we create new button, once we click on button tit should redirect to specified account record page.<br />
<br />
<b>redirectToRecordPage.html</b><br />
<pre><code> <template>
<div class="slds-box slds-theme_shade">
<lightning-button label="Navigate To Account" onclick="{navigateToAccountPage}"> </lightning-button>
</div>
</template>
</code></pre>
<br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<b>redirectToRecordPage.js</b><br />
<pre> <code>
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class RedirectToRecordPage extends NavigationMixin(LightningElement) {
navigateToAccountPage() {
this[NavigationMixin.Navigate]({
type: 'standard__recordPage',
attributes: {
recordId: '0010K000027o6pWQAQ',
objectApiName: 'Account',
actionName: 'view'
}
});
}
}
</code>
</pre>
<br />
<b>Output</b>:<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.blogger.com/video.g?token=AD6v5dwp2ntvsBuDYNhz2TP_mTwa5QQbxkhMNuk_ZfqcGQpDfgHZmrnKd1IiT5RhpTpHl8mHkVXKliazhddPM4VUKA' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-31955772415287543792020-07-25T06:37:00.003-07:002020-07-25T06:39:08.564-07:00How To Display LWC Component In Quick Action <div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Lighting Web Component (LWC) In Quick action </h2>
<div>
We can't show lwc component directly in lightning quick action, if we need to show Lightning web component in quick action then we need to create simple lightning aura component and in that we need to refer Lwc component (check example code below). Then we can show lwc component content in quick action button.</div>
<h3 style="text-align: left;">
Showing LWC Component content in Lightning Quick Action </h3>
<div>
<b>Step 1: Create new lightning web component : lwcAction</b></div>
<div>
<b>lwcAction.html</b></div>
<pre><code> <template>
<div class="slds-box slds-theme_shade">
<P> I am from LWC Component</P>
</div>
</template>
</code></pre>
<div>
<div>
<b>Step2: Create new lightning aura component LwcInAuraQuickAction</b></div>
<div>
<br /></div>
<div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<b>LwcInAuraQuickAction.cmp</b></div>
<pre><code> <aura:component implements="flexipage:availableForAllPageTypes,
flexipage:availableForRecordHome,
force:hasRecordId,force:lightningQuickAction" access="global" >
<c:lwcAction />
</aura:component>
</code></pre>
<br />
<div>
<b>Add it to quick action button</b><br />
<b><br /></b></div>
<div>
Go to Object Manger--> Buttons, Links, and Actions --> New Action </div>
</div>
<div>
--> Select <b>Lightning Component</b> as Action Type</div>
<div>
--> Select <b>LwcInAuraQuickAction </b>as Lightning Component</div>
<div>
--> Give "<b>LWC ACtion</b>" as Label and save.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFyKpIi7rCKqJMxwBAMM1A4ZxlnZOeIMJ9CTeo59nteaXJ_FTyZ48PKN-eJRUa-kxXZbAJwN52d0V2AIkMVBkIUvy6zXWKAU0GSdaEtAS8Xd-tvAELUb-hwSTBwShWuQj6QhptesVNgeaI/s1600/LWC+quick+action+step+1.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Lightning web component Quick Action Example code" border="0" data-original-height="416" data-original-width="576" height="462" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjFyKpIi7rCKqJMxwBAMM1A4ZxlnZOeIMJ9CTeo59nteaXJ_FTyZ48PKN-eJRUa-kxXZbAJwN52d0V2AIkMVBkIUvy6zXWKAU0GSdaEtAS8Xd-tvAELUb-hwSTBwShWuQj6QhptesVNgeaI/s640/LWC+quick+action+step+1.JPG" title="Lwc Quick Action" width="640" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
--> Add this "LWC Action" button to page layout.</div>
<div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<div>
<b>Output:</b></div>
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen='allowfullscreen' webkitallowfullscreen='webkitallowfullscreen' mozallowfullscreen='mozallowfullscreen' width='320' height='266' src='https://www.blogger.com/video.g?token=AD6v5dwf9LjugmrVU6SV1uHNf6wrgwEMkSdMRSaAgVfraqWa7veXglCTOdWZznDldBlvX-OGwt1EtX1WMIMt1lQglw' class='b-hbp-video b-uploaded' frameborder='0'></iframe></div>
<div>
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-38389967921518129272020-07-25T05:06:00.001-07:002020-08-05T09:20:42.104-07:00LWC Modal: How To Create/Show Modal Popup in LWC<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
How Display Content In Modal Popup window using Lightning Web Components (LWC):</h2>
If we need to show something in modal dialog we need to use predefined slds class "<b>slds-modal</b>" . LWC modal has three section i.e header, body(modal content), footer. If we use "<b>slds-modal__header</b>" class we can show sticky header in modal window and by using "<b>slds-modal__footer</b>" class we can show sticky footer where usually show save, cancel buttons. By using "<b>slds-modal__content</b>" class we can show modal body content.<br />
<br />
In below example code we are showing lightning button, on click of that button, modal popup window will be opened.<br />
<h3 style="text-align: left;">
Code for Lightning Web Component (LWC) Modal Popup </h3>
<div>
Create new lightning web component: <b>lwcModalPopup</b></div>
<div>
<b><br /></b></div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<div>
<b>lwcModalPopup.html</b></div>
<pre><code> <template>
<div class="slds-box slds-theme_shade">
<lightning-button label="Show Modal" onclick={showModal}> </lightning-button>
</div>
<template if:true={openModal}>
<div class="slds-modal slds-fade-in-open slds-backdrop">
<div class="slds-modal__container">
<!------HEADER Section-->
<div class="slds-modal__header">
<lightning-button-icon icon-name="utility:close" alternative-text="Close this window" size="large"
variant="bare-inverse" onclick={closeModal} class="slds-modal__close">
</lightning-button-icon>
<h2>Welcome To SalesforcePoint.com</h2>
</div>
<!------Body Section-->
<div class="slds-modal__content slds-p-around_medium">
<center>
<P>Hello guys, welcome to salesforcepoint.com. <br>
This is the basic lightning web component Modal popup.
</P>
</center>
</div>
<!------Footer Section-->
<div class="slds-modal__footer">
<lightning-button icon-name="utility:close" label="close" variant="brand" onclick={closeModal}>
</lightning-button>
</div>
</div>
</div>
</template>
</template>
</code></pre>
<div>
<b>lwcModalPopup.js</b></div>
<pre><code>
import { LightningElement,track } from 'lwc';
export default class LwcModalPopup extends LightningElement {
@track openModal = false;
showModal() {
this.openModal = true;
}
closeModal() {
this.openModal = false;
}
}
</code></pre>
Deploy the modal component and add it lightning page.<br />
<div>
<br /></div>
<div>
<b>Output:</b><br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2FoIYV-v-cnChbPwGAtxFMXfD805V5eJsl42XUpCENADf-gwBoOszFS_-Glupk34HzDt1bsYdcDTZ9p5IVlyXncGzx8gDowKZY-mtfhJXTyQisSQKEmXh2vc7itT_P1N9b6JHkmokdaxH/s1600/Lwc+Modal+Component+in+Lightning+Web+Components.JPG" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img alt="LWC Modal popup Lightning web component code" border="0" data-original-height="362" data-original-width="497" height="466" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi2FoIYV-v-cnChbPwGAtxFMXfD805V5eJsl42XUpCENADf-gwBoOszFS_-Glupk34HzDt1bsYdcDTZ9p5IVlyXncGzx8gDowKZY-mtfhJXTyQisSQKEmXh2vc7itT_P1N9b6JHkmokdaxH/s640/Lwc+Modal+Component+in+Lightning+Web+Components.JPG" title="LWC Modal popup Lightning web component code" width="640" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Output of LWC Modal component</td></tr>
</tbody></table>
<br /></div>
</div>
Unknownnoreply@blogger.com2tag:blogger.com,1999:blog-8707943299537466355.post-67758918771010110882020-07-25T02:43:00.003-07:002020-07-25T03:53:56.164-07:00Create Calculator Using Lightning Web Component(LWC)<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
Simple LWC Calculator</h2>
<div>
In this we are going to see how to create or build simple lightning web component calculator with functions like </div>
<div>
<ul style="text-align: left;">
<li>How to add two numbers in Lwc.</li>
<li>How to subtract two numbers in Lwc. </li>
<li>Division of two numbers in Lwc.</li>
<li>Multiplication of two numbers in Lwc.</li>
</ul>
<h3 style="text-align: left;">
<span style="font-weight: normal;">Steps to create Lightning Web Component Calculator</span></h3>
</div>
<div style="text-align: left;">
<b>Step1 : Create New Lightning Web component with name: calculatorInLwc.</b><br />
<div style="text-align: left;">
<b>calculatorInLwc.html</b><br />
<pre><code> <template>
<div class="slds-box slds-theme_shade">
<lightning-input type="number" name="input2" label="Number 1" onchange={handleNumberOeChange} value={firstNumber}></lightning-input>
<lightning-input type="number" name="input2" label="Number 2" onchange={handleNumberTwoChange} value={secondNumber}></lightning-input>
</div>
<div class="slds-box slds-theme_shade">
<b>Output value is : </b>
<P>{resultValue}</p>
</div>
<div class="slds-box slds-theme_shade">
<lightning-button label="Addition" onclick={addition}> </lightning-button>
<lightning-button label="Multification" onclick={multification}> </lightning-button>
<lightning-button label="Subtraction" onclick={subtraction}> </lightning-button>
<lightning-button label="Divison" onclick={division}> </lightning-button>
</div>
</template>
</code></pre>
<br />
<b>calculatorInLwc.js</b></div>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
<pre><code>
import { LightningElement, track } from 'lwc';
export default class CalculatorInLwc extends LightningElement {
@track firstNumber;
@track secondNumber;
resultValue;
handleNumberOeChange(event) {
this.firstNumber = parseInt(event.target.value);
}
handleNumberTwoChange(event) {
this.secondNumber = parseInt(event.target.value);
}
addition() {
this.resultValue = parseInt(this.firstNumber) + parseInt(this.secondNumber);
}
multification() {
this.resultValue = this.firstNumber * this.secondNumber;
}
subtraction() {
this.resultValue = this.firstNumber - this.secondNumber;
}
division() {
this.resultValue = this.firstNumber / this.secondNumber;
}
}
</code></pre>
<br />
<div>
<b>Step2: Add this lwc component to lightning page.</b></div>
<div>
Add calculator Lightning web competent to lightning page in app builder.<br />
<h4 style="text-align: left;">
Output:</h4>
</div><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-7808771366219927"
data-ad-slot="9828091934"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGR5cSmk-yj8rGek4Tn9svxuySTSjXqUFeMsdI6E9KKLaZPsuaAMUbgIgWSGbU6yB8kC7K1GJQ4PLf3pHqqWDB-gjpY6oH-SiYiP9OFxnUf2bxfsy5tmVZZ1mfIY0smzqoCdThLjaDQEZY/s1600/Sample+Lwc+Calculator+Using+Lightning+Web+Component.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="298" data-original-width="407" height="468" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjGR5cSmk-yj8rGek4Tn9svxuySTSjXqUFeMsdI6E9KKLaZPsuaAMUbgIgWSGbU6yB8kC7K1GJQ4PLf3pHqqWDB-gjpY6oH-SiYiP9OFxnUf2bxfsy5tmVZZ1mfIY0smzqoCdThLjaDQEZY/s640/Sample+Lwc+Calculator+Using+Lightning+Web+Component.JPG" width="640" /></a></div>
<div>
<br /></div>
</div>
Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-8707943299537466355.post-74251512478433445992020-07-19T01:24:00.003-07:002020-08-12T21:57:23.799-07:00Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table Using Wrapper Class<div dir="ltr" style="text-align: left;" trbidi="on">
<div dir="ltr" style="text-align: left;" trbidi="on">
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikucPZDU1VxLDLiMEqBXQi0AUy2YIjER2xlkn38qBRo8Rlq1EUYbOWwrPlmgyDX47zkcRmIES7umv-NYl6Qb6nZ1rGe1ZiJTwuqvRVQMBI6-TtguTVar6b2J-o05XxbUKSY4lCZx6HGNhyphenhyphen/s1600/Populate++Preselected+Checkbox+for+Records+On+LWC+Lightning+Data+Table.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table" border="0" data-original-height="328" data-original-width="495" height="422" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEikucPZDU1VxLDLiMEqBXQi0AUy2YIjER2xlkn38qBRo8Rlq1EUYbOWwrPlmgyDX47zkcRmIES7umv-NYl6Qb6nZ1rGe1ZiJTwuqvRVQMBI6-TtguTVar6b2J-o05XxbUKSY4lCZx6HGNhyphenhyphen/s640/Populate++Preselected+Checkbox+for+Records+On+LWC+Lightning+Data+Table.jpg" title="Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table" width="640" /></a></div>
<h3 style="text-align: left;">
Lightning Data Table with Pre populated selected records in Lightning Web Components </h3>
In some scenarios we need auto populate selected checkbox for records in <a href="https://www.salesforcepoint.com/2020/06/lwc-data-table-with-checkbox-example.html" target="_blank">lightning-datatable</a> on page load. In this post we also covered how to use wrapper class in Lightning web components (LWC).Let's see how to populate preselected rows in LWC data table.<br />
<br />
<b>Also Check: <a href="https://www.salesforcepoint.com/2020/06/how-to-add-hyper-link-for-name-column.html" target="_blank">How To Add Hyper Link For Name Column In lightning-datatable in LWC</a></b><br />
<br />
We have a key-field attribute in <a href="https://www.salesforcepoint.com/2020/06/lwc-data-table-with-checkbox-example.html" target="_blank"><b>lightning-datatable</b></a> tag which is unique for every row in the table and based on this field only we can populate pre selected checkbox in data table. By using "selected-rows" attribute we can set the on load selected records in lightning-datatable, this is a array of unique key-field values. As per the requirements we set this attribute value in code.<br />
<h3>
Example for preselected rows/records in LWC data table:</h3>
<div>
Display all opportunity records and all these records should be pre selected.</div>
<h4 style="text-align: left;">
Step1: Create Apex class: OpportunityController.</h4>
<pre><code>
public with sharing class OpportunityController {
@AuraEnabled(cacheable=true)
public static oppWrapper getOpportunityRecords(){
oppWrapper ow = new oppWrapper();
ow.oppList = [SELECT Id, Name, StageName,Amount From Opportunity LIMIT 100];
Set<Id> selectedOppIdSet = new Set<Id>();
for(Opportunity opp: ow.oppList){
selectedOppIdSet.add(opp.Id);
}
ow.selectedIdSet = selectedOppIdSet;
return ow;
}
public class oppWrapper{
@AuraEnabled public List<opportunity> oppList {get; set;}
@AuraEnabled public set<Id> selectedIdSet {get; set;}
}
}
</code></pre>
<h4 style="text-align: left;">
Step2: Create New lightning web component: preSelectedLightningDataTable.</h4>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<div>
<b>preSelectedLightningDataTable.js</b><br />
<pre><code>
import { LightningElement,track,wire } from 'lwc';
import getOpportunityList from '@salesforce/apex/OpportunityController.getOpportunityRecords';
const COLS=[
{label:'Name',fieldName:'Name', type:'text'},
{label:'Stage',fieldName:'StageName', type:'text'},
{label:'Amount',fieldName:'Amount', type:'currency'}
];
export default class PreSelectedLightningDataTable extends LightningElement {
oppList;
cols = COLS;
@track preSelectedRows;
@wire(getOpportunityList)
getOpportunityList(result){
if(result.data) {
this.oppList=result.data.oppList;
this.preSelectedRows = result.data.selectedIdSet;
this.errorList=undefined;
}else if(result.error){
this.oppList=undefined;
this.errorList=result.error;
}
}
}
</code> </pre>
<b>preSelectedLightningDataTable.html</b><br />
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><br />
<pre><code>
<template>
<lightning-card title="Opportunity Records">
<div class="slds-box">
<lightning-datatable selected-rows={preSelectedRows}
data={oppList} columns={cols} key-field="Id">
</lightning-datatable>
</div>
</lightning-card>
</template>
</code></pre>
</div>
</div>
<br />
<b>Output: Data Table with Pre populated selected checkbox records in Lightning Web Components.</b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWZfTgg6pKEpVWzSSTVvmLJo16xXeYI9PToJhZegvJDjkNL9KgyI_nvIzzltfEp8epZFRms-nHgUjKmEbm9R7R2si2XPQuMS91JYL-FADlpXZYZc4CRoeXUqmjYGgCEPhfQ-TpszHBf89U/s1600/output+How+To+Populate++Preselected+Checkbox+for+Records-Rows+On+LWC+Lightning+Data+Table.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="How To Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table2" border="0" data-original-height="372" data-original-width="645" height="369" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjWZfTgg6pKEpVWzSSTVvmLJo16xXeYI9PToJhZegvJDjkNL9KgyI_nvIzzltfEp8epZFRms-nHgUjKmEbm9R7R2si2XPQuMS91JYL-FADlpXZYZc4CRoeXUqmjYGgCEPhfQ-TpszHBf89U/s640/output+How+To+Populate++Preselected+Checkbox+for+Records-Rows+On+LWC+Lightning+Data+Table.jpg" title="How To Populate Preselected Checkbox for Records/Rows On LWC Lightning Data Table2" width="640" /></a></div>
</div>
Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-8707943299537466355.post-84925059639726401572020-07-10T23:39:00.002-07:002020-09-05T09:27:55.230-07:00How To Iterate Array/List In Lightning Web Components (LWC)<div dir="ltr" style="text-align: left;" trbidi="on">
<h2 style="text-align: left;">
How To Iterate List Of Items In LWC</h2>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFyw6obyAJNdp46xYDVhUvPT0OoJXN9awwB0eHpDuBUKWsKCKAdRGX2lGk5xm0J1AJSZTDOQQrW0yiyjIBpZIB9SNRj5qYxxjMFPWKxI7UnYSXQV7ueM9_1lSv1DkBoXm3i6rewiU8KfHQ/s1600/Iteration+in+Lwc+Template.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img alt="Iterate array of elments in LWC html template" border="0" data-original-height="568" data-original-width="1280" height="284" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgFyw6obyAJNdp46xYDVhUvPT0OoJXN9awwB0eHpDuBUKWsKCKAdRGX2lGk5xm0J1AJSZTDOQQrW0yiyjIBpZIB9SNRj5qYxxjMFPWKxI7UnYSXQV7ueM9_1lSv1DkBoXm3i6rewiU8KfHQ/s640/Iteration+in+Lwc+Template.png" title="Iteration in LWC html template" width="640" /></a></div>
<div>
<br /></div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<div>
<b>LWC iteration:</b> In this post we will see how to use iteration in Lightning Web Components template. Like aura:iteration in Aura, we have <b>"for:each" in lwc</b>. By using <b>"for:each" </b>we can iterate set of elements/items in lwc html template. We can access element by using <b>for:item</b> and we can get index value with <b>for:index</b> .</div>
<div>
<br /></div>
<div>
<b>Syntax: </b></div>
<pre style="background: white; border: 1px solid #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; height: auto; line-height: 20px; overflow: auto; overflow: auto; padding: 0px; text-align: left; width: 99%; width: 99%;"><code style="color: black; word-wrap: normal;"> <template for:each={itemList} for:item="item" for:index="index">
{item}
</template> </code></pre>
<h4 style="text-align: left;">
Iteration in lwc html Example: Iterate List of Accounts.</h4>
<div>
<span style="font-weight: normal;"><br /></span></div>
<div>
Create apex class: <b>IterationInLwcController</b></div>
<pre style="background: white; border: 1px solid #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; height: auto; line-height: 20px; overflow: auto; overflow: auto; padding: 0px; text-align: left; width: 99%; width: 99%;"><code style="color: black; word-wrap: normal;"> public with sharing class IterationInLwcController {
@AuraEnabled(cacheable = true)
public static List<Account> fetchAccounts(){
return [SELECT Id,Name,Phone,Type,Industry,Rating,Website FROM Account LIMIT 100];
}
}
</code></pre>
<h4 style="text-align: left;">
Create New Lightning Web Component: <b>iterationInLwc</b></h4>
<div>
<b><br /></b></div>
<div>
<b>iterationInLwc.html</b><br />
If you getting list from wired property then, we need o use list.data to "for:each". Because wired property contains data and error. </div>
<pre style="background: white; border: 1px solid #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; height: auto; line-height: 20px; overflow: auto; overflow: auto; padding: 0px; text-align: left; width: 99%; width: 99%;"><code style="color: black; word-wrap: normal;"> <template>
<lightning-card title="Iteration In LWC">
<div class="slds-p-around_small">
<template for:each={accounts.data} for:item="account" for:index="index">
<div class="slds-p-left_small" key={account.Id}>
{account.Name}
</div>
</template>
</div>
</lightning-card>
</template>
</code></pre>
<div>
<div>
<b><br /></b>
<b>iterationInLwc.js</b></div>
</div>
<script async="" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Jeevi Responsive New -->
<br />
<ins class="adsbygoogle" data-ad-client="ca-pub-7808771366219927" data-ad-format="auto" data-ad-slot="9828091934" data-full-width-responsive="true" style="display: block;"></ins><script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<br />
<div>
<pre style="background: white; border: 1px solid #cccccc; color: black; font-family: "arial"; font-size: 12px; height: auto; height: auto; line-height: 20px; overflow: auto; overflow: auto; padding: 0px; text-align: left; width: 99%; width: 99%;"><code style="color: black; word-wrap: normal;"> import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/IterationInLwcController.fetchAccounts';
export default class IterationInLwc extends LightningElement {
@wire(fetchAccounts) accounts;
}
</code></pre>
</div>
<br />
<b>Output: </b><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXkFxUOIG-X76e4k58h9kDoMfw5K_EHoyn-q0Ja6ZCgtHGreonbJpop-I1FHgP4EQxRcwT2HzHAbOdwgksNzlLupGIzC-wgW_VZtdismjWLmw_16-BBVCp2TJj0YGYcB38aHWyIIkxxNk6/s1600/Iterration+In+Lwc+Html+template.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="315" data-original-width="678" height="296" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjXkFxUOIG-X76e4k58h9kDoMfw5K_EHoyn-q0Ja6ZCgtHGreonbJpop-I1FHgP4EQxRcwT2HzHAbOdwgksNzlLupGIzC-wgW_VZtdismjWLmw_16-BBVCp2TJj0YGYcB38aHWyIIkxxNk6/s640/Iterration+In+Lwc+Html+template.jpg" width="640" /></a></div>
<b><br /></b></div>
Unknownnoreply@blogger.com2