<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>lwc &#8211; Hamza Siddiqui</title>
	<atom:link href="https://www.mhamzas.com/blog/tag/lwc/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.mhamzas.com</link>
	<description>4x Salesforce MVP &#124; 26x Certified &#124; Salesforce App &#38; System Architect</description>
	<lastBuildDate>Tue, 03 Jan 2023 08:14:48 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>
<site xmlns="com-wordpress:feed-additions:1">233526040</site>	<item>
		<title>force:refreshView (getRecordNotifyChange) in Lightning web component</title>
		<link>https://www.mhamzas.com/blog/2021/06/17/forcerefreshview-getrecordnotifychange-in-lightning-web-component/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=forcerefreshview-getrecordnotifychange-in-lightning-web-component</link>
					<comments>https://www.mhamzas.com/blog/2021/06/17/forcerefreshview-getrecordnotifychange-in-lightning-web-component/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Thu, 17 Jun 2021 13:25:10 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[lwc]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3248</guid>

					<description><![CDATA[We&#8217;re kind of in love with the lightning UI and the aura feature (e.force:refreshview) which updated the data on the current lightning page/record/component. We missed the feature in LWC and I saw many using the workaround to use a combination of AURA <br /><a href="https://www.mhamzas.com/blog/2021/06/17/forcerefreshview-getrecordnotifychange-in-lightning-web-component/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>We&#8217;re kind of in love with the lightning UI and the aura feature (e.force:refreshview) which updated the data on the current lightning page/record/component. We missed the feature in LWC and I saw many using the workaround to use a combination of AURA and LWC to just have this functionality.</p>



<p id="3e86">Starting&nbsp;<a href="https://releasenotes.docs.salesforce.com/en-us/winter21/release-notes/rn_lwc_modules.htm">Winter ’21</a>, there is a new function in town !</p>



<p id="1e90">Using it is as simple as what we’ve been used to in Aura. You’ll just need to import it <br>(<code>import { getRecordNotifyChange } from 'lightning/uiRecordApi';</code>), and then call it with a list of record Ids <br>(<code>getRecordNotifyChange([{recordId: this.recordId}]);</code>).</p>



<p id="33f7">Full sample code looks like this:</p>



<script src="https://gist.github.com/mhamzas/bd26b731bbdcfbf504b4c16f8463268d.js"></script>



<p>This implies one change though: <code>force:refreshView</code> was refreshing the whole page, whereas <code>getRecordNotifyChange()</code> is only refreshing the records you ask him to refresh. So if your Apex code is for instance updated the current Account, but also some child Contacts, you may have to pass to <code>getRecordNotifyChange()</code> all the Ids updated by your Apex method.</p>



<p>Credits: https://blog.texei.com/refresh-a-record-page-from-a-lightning-web-component-14a5874ff68e</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/06/17/forcerefreshview-getrecordnotifychange-in-lightning-web-component/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3248</post-id>	</item>
		<item>
		<title>LWC Best Practices &#038; Considerations</title>
		<link>https://www.mhamzas.com/blog/2021/05/23/lwc-best-practices-considerations/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=lwc-best-practices-considerations</link>
					<comments>https://www.mhamzas.com/blog/2021/05/23/lwc-best-practices-considerations/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Sun, 23 May 2021 02:11:00 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[lwc]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3244</guid>

					<description><![CDATA[Hi again! This blog post is going to be a different one as I&#8217;ll keep updating this post with all the latest findings. In this blog post, I am going to share all the best practices and considerations regarding LWC for not <br /><a href="https://www.mhamzas.com/blog/2021/05/23/lwc-best-practices-considerations/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>Hi again! This blog post is going to be a different one as I&#8217;ll keep updating this post with all the latest findings.</p>



<p>In this blog post, I am going to share all the best practices and considerations regarding LWC for not just by the Salesforce but even with personal experience.</p>



<p>First, let&#8217;s start with <strong>FOR LOOP</strong>,</p>



<p><strong>1- FOR LOOP</strong></p>



<p>JS ES6 bring a different kind of FOR LOOPS (<a href="https://niksdeveloper.com/salesforce/loop-through-list-in-lwc-and-javascript/" target="_blank" rel="noreferrer noopener nofollow">click here</a> to have a look in details) but in LWC &#8211; make sure to use the one which doesn&#8217;t conflict with lwc architecture.</p>



<p>For example, if you&#8217;re going to use <strong>forEach</strong>,</p>



<pre class="wp-block-code"><code>this.lstAccounts.forEach(function(acc){
    console.log(acc.Name);
});</code></pre>



<p>You won&#8217;t be able to access THIS.VARIABLE inside this loop. Here is a demonstration, </p>



<pre class="wp-block-code"><code>this.lstAccounts.forEach(function(acc){
    console.log(acc.Name);
    console.log(this.someBooleanval); //THIS VALUE WILL BE NULL
});</code></pre>



<p>The reason is that such kind of loop also uses THIS. and looks for the value inside a loop where such variable is not assigned hence &#8211; NULL.</p>



<p>SO what should you do ? Use another kind of FOR LOOP &#8211; like:</p>



<pre class="wp-block-code"><code>for(let acc of this.lstAccounts){
    console.log(acc.Name);
   console.log(this.someBooleanval); //VALUE WILL BE ACCESSIBLE HERE
}</code></pre>



<p><strong>2- Dealing with Time field</strong></p>



<p>The number you are getting is in milliseconds &#8220;65700000&#8221;. We need to convert it to time format in js itself. I used the below method to do so.</p>



<pre class="wp-block-code"><code>// Convert milliseconds into 'h:mm a' time format
    msToTime(s){
        let ms = s % 1000;
        s = (s - ms) / 1000;
        let secs = s % 60;
        s = (s - secs) / 60;
        let mins = s % 60;
        let hrs = (s - mins) / 60;
        hrs = hrs &lt; 10 ? '0' + hrs : hrs;
        mins = mins &lt; 10 ? '0' + mins : mins;
        console.log(hrs + '  ' + mins);
        return hrs+':' + mins + ':00.000Z';
    }</code></pre>



<p><strong>3-</strong> <strong>setInterval Binding</strong></p>



<p id="c2ba">setInterval runs on different browser subthread thingy… That is it doesn’t maintain the context of what happens after.</p>



<p id="015f">Take this code for eg.</p>



<pre class="wp-block-preformatted">var count = 0;<br>var intervalID = setInterval(function (){<br>  this.count++;<br>  console.log(this.count);     // prints number from 0 to percentage<br>  if (this.count === this.percentage) {<br>    clearInterval(intervalID);<br>  }<br>},10)<br>console.log(this.count);       // prints 0 </pre>



<p id="995a">The second console prints ‘0&#8242;, which explains the fact that context is not maintained. To make that happen we bind the context to each anonymous function call that is made.</p>



<p id="bea6">Just use</p>



<pre class="wp-block-preformatted">.bind(this) // 'this' is the context</pre>



<p id="46e9">So the JS becomes,</p>



<pre class="wp-block-preformatted">import { LightningElement, track } from 'lwc';<br>export default class App extends LightningElement {<br>  @track count = 0;<br>  @track percentage = 99;<br>  <br>  connectedCallback() {<br>    var intervalID = setInterval(function (){<br>      this.count++;<br>      if (this.count === this.percentage) {<br>        clearInterval(intervalID);<br>      }<br>    }.bind(this),10);<br>  }<br>}</pre>



<p>I hope this will help you at some point &#8211; I&#8217;ll keep updating this post with latest updates.</p>



<p>Happy Coding!</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2021/05/23/lwc-best-practices-considerations/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3244</post-id>	</item>
		<item>
		<title>Dynamic Toggle Class in LWC</title>
		<link>https://www.mhamzas.com/blog/2020/07/08/dynamic-toggle-class-in-lwc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=dynamic-toggle-class-in-lwc</link>
					<comments>https://www.mhamzas.com/blog/2020/07/08/dynamic-toggle-class-in-lwc/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Wed, 08 Jul 2020 14:36:02 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3157</guid>

					<description><![CDATA[This is a very simple scenario where you need to hide/show some div but you can&#8217;t use &#60;template if:true> tag. Let&#8217;s say you&#8217;re using loop. Here we&#8217;re discussing 2 approaches if you&#8217;re looking for answer to how you can use dynamic hide/show <br /><a href="https://www.mhamzas.com/blog/2020/07/08/dynamic-toggle-class-in-lwc/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>This is a very simple scenario where you need to hide/show some div but you can&#8217;t use &lt;template if:true> tag. Let&#8217;s say you&#8217;re using loop.</p>



<p>Here we&#8217;re discussing 2 approaches if you&#8217;re looking for answer to how you can use dynamic hide/show in LWC without template if:true approach</p>



<h2 class="wp-block-heading">Toggle Class (Simple Approach)</h2>



<script src="https://gist.github.com/mhamzas/454978473c593d8397c43fa0442d5dbf.js"></script>



<h2 class="wp-block-heading">Toggle (classList Approach)</h2>



<script src="https://gist.github.com/mhamzas/7dbb8633c7ee31102e1fe707651c4129.js"></script>



<p>Source <a href="https://salesforce.stackexchange.com/questions/260614/lwc-how-to-toggle-css-class-on-button-click">https://salesforce.stackexchange.com/questions/260614/lwc-how-to-toggle-css-class-on-button-click</a></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2020/07/08/dynamic-toggle-class-in-lwc/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3157</post-id>	</item>
		<item>
		<title>Checkbox label with URL in AURA/LWC</title>
		<link>https://www.mhamzas.com/blog/2020/06/05/checkbox-label-with-url-in-aura-lwc/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=checkbox-label-with-url-in-aura-lwc</link>
					<comments>https://www.mhamzas.com/blog/2020/06/05/checkbox-label-with-url-in-aura-lwc/#comments</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Fri, 05 Jun 2020 12:47:39 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[aura]]></category>
		<category><![CDATA[component]]></category>
		<category><![CDATA[lightning]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3134</guid>

					<description><![CDATA[This is a pretty common use case where you want to show a simple checkbox to authorize the terms and condition with a URL to your terms of service or privacy url. But using lightning:input or lightning-input, we&#8217;re not allowed to add <br /><a href="https://www.mhamzas.com/blog/2020/06/05/checkbox-label-with-url-in-aura-lwc/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>This is a pretty common use case where you want to show a simple checkbox to authorize the terms and condition with a URL to your terms of service or privacy url. </p>



<div class="wp-block-image"><figure class="aligncenter size-large"><img data-recalc-dims="1" decoding="async" width="369" height="43" src="https://i0.wp.com/www.mhamzas.com/wp-content/uploads/2020/06/image.png?resize=369%2C43&#038;ssl=1" alt="" class="wp-image-3135" srcset="https://i0.wp.com/www.mhamzas.com/wp-content/uploads/2020/06/image.png?w=369&amp;ssl=1 369w, https://i0.wp.com/www.mhamzas.com/wp-content/uploads/2020/06/image.png?resize=300%2C35&amp;ssl=1 300w" sizes="(max-width: 369px) 100vw, 369px" /></figure></div>



<p>But using lightning:input or lightning-input, we&#8217;re not allowed to add HTML tags under LABEL attribute.</p>



<p>So here are the work-arounds for AURA and LWC,</p>



<h2 class="wp-block-heading">AURA</h2>



<p>Component:</p>



<pre class="wp-block-code"><code>&lt;aura:attribute name="chkTerms" type="Boolean"/>
&lt;div>
    &lt;input type="checkbox" id="terms" name="terms" value="{!v.chkTerms}" onchange="{!c.termsChanged}" >&lt;/input>
    &lt;label for="terms"> Yes, by creating an account I agree to the &lt;a href="#">Terms and Service.&lt;/a>&lt;/label>
&lt;/div></code></pre>



<p>JS</p>



<pre class="wp-block-code"><code>termsChanged : function(cmp, event, helper){
    cmp.set("v.chkTerms", document.getElementById("terms").checked );
    //console.log(event.getSource().get("v.checked"));
    // the above didn't work except for `ui:input` or `lightning:input`
    console.log(cmp.get("v.chkTerms") ); 
}</code></pre>



<h2 class="wp-block-heading">LWC</h2>



<p>HTML</p>



<pre class="wp-block-code"><code>&lt;div class="slds-p-around_medium lgc-bg">
    &lt;input type="checkbox" id="terms" name="authorize" onchange={handleCheckBoxChange} required="required">&lt;/input>
    &lt;label for="terms" style="display: inline;" class="slds-form-element__label"> Yes, by creating an account I agree to the &lt;a href="#">Terms and Service.&lt;/label>
&lt;/div></code></pre>



<p>JS</p>



<pre class="wp-block-code"><code>handleCheckBoxChange(event){        
    console.log('Authorized::'+event.target.checked);
    // Your Logic
}</code></pre>



<p>Source <br><a href="https://salesforce.stackexchange.com/questions/213749/lightninginput-checkbox-label-with-url">https://salesforce.stackexchange.com/questions/213749/lightninginput-checkbox-label-with-url</a></p>



<p></p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2020/06/05/checkbox-label-with-url-in-aura-lwc/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3134</post-id>	</item>
		<item>
		<title>Custom validation in Lightning web component</title>
		<link>https://www.mhamzas.com/blog/2020/01/17/custom-validation-in-lightning-web-component/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=custom-validation-in-lightning-web-component</link>
					<comments>https://www.mhamzas.com/blog/2020/01/17/custom-validation-in-lightning-web-component/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Fri, 17 Jan 2020 07:11:55 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[validation]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3066</guid>

					<description><![CDATA[As Lightning component is kinda new and I was struggling finding ways to add custom validation on any field (lightning-input specially) and even very little information is available all over internet (yet) and I assume others may be struggling for the same <br /><a href="https://www.mhamzas.com/blog/2020/01/17/custom-validation-in-lightning-web-component/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>As Lightning component is kinda new and I was struggling finding ways to add custom validation on any field (lightning-input specially) and even very little information is available all over internet (yet) and I assume others may be struggling for the same solution. Luckily, it worked out for me and I am sharing the JS method which will add custom error validation on any field.</p>



<p>In this method, I am getting the date value and checking if its empty then print some error on field and returning back the null value else remove the error message (if any) and return the entered value.</p>



<script src="https://gist.github.com/mhamzas/d0e965d725f8647cd4ba7978aee164e3.js"></script>



<p>Happy Coding !</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2020/01/17/custom-validation-in-lightning-web-component/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3066</post-id>	</item>
		<item>
		<title>Usage Of lightning-record-form</title>
		<link>https://www.mhamzas.com/blog/2019/11/18/usage-of-lightning-record-form/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=usage-of-lightning-record-form</link>
					<comments>https://www.mhamzas.com/blog/2019/11/18/usage-of-lightning-record-form/#respond</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Mon, 18 Nov 2019 11:58:36 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<category><![CDATA[sfdc]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=3015</guid>

					<description><![CDATA[Let us discuss&#160;here how&#160;to use the lightning-record-form . A&#160;lightning-record-form&#160;component enables you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with&#160;lightning-record-edit-form&#160;and&#160;lightning-record-view-form. However,&#160;lightning-record-form&#160;does not support client-side validation quite <br /><a href="https://www.mhamzas.com/blog/2019/11/18/usage-of-lightning-record-form/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>Let us discuss&nbsp;here how&nbsp;to use the lightning-record-form . A&nbsp;<code>lightning-record-form</code>&nbsp;component enables you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with&nbsp;<code>lightning-record-edit-form</code>&nbsp;and&nbsp;<code>lightning-record-view-form</code>. However,&nbsp;<code>lightning-record-form</code>&nbsp;does not support client-side validation quite the same as&nbsp;<code>lightning-record-edit-form</code>.The&nbsp;<code>object-api-name</code>&nbsp;attribute is always required, and the&nbsp;<code>record-id</code>&nbsp;is required unless you’re creating a record.</p>



<h2 class="wp-block-heading">Modes</h2>



<p>The component accepts a&nbsp;<code>mode</code>&nbsp;value that determines the user interaction allowed for the form. The value for&nbsp;<code>mode</code>&nbsp;can be one of the following:</p>



<ul class="wp-block-list"><li><code>edit</code>&nbsp;– Creates an editable form to add a record or update an existing one. When updating an existing record, specify the recordId. Edit mode is the default, and as such, can be omitted.</li><li><code>view</code>&nbsp;– Creates a form to display a record that the user can also edit. The record fields each have an edit button.</li><li><code>readonly</code>&nbsp;– Creates a form to display a record without enabling edits. The form doesn’t display any buttons.</li></ul>



<p>For all modes, the component expects the&nbsp;<code>fields</code>&nbsp;attribute, the&nbsp;<code>layout-type</code>&nbsp;attribute, or both. Use the&nbsp;<code>fields</code>&nbsp;attribute to specify a comma-separated list of record fields to load into the form. The fields load in the order you list them. Use the&nbsp;<code>layout-type</code>&nbsp;attribute to specify a&nbsp;<code>Full</code>&nbsp;or&nbsp;<code>Compact</code>&nbsp;layout. All fields that have been assigned to the layout are loaded into the form. This is the same behavior as the Lightning Data Service’s&nbsp;<code>force:recordData</code>&nbsp;object. Layouts are typically created or modified by administrators. Loading record data using&nbsp;<code>layout-type</code>&nbsp;allows the form to adapt to those layout definitions. If you provide the&nbsp;<code>fields</code>&nbsp;attribute and the&nbsp;<code>layout-type</code>&nbsp;attribute, the fields specified in the&nbsp;<code>fields</code>&nbsp;attribute are loaded before the layout fields.</p>



<p>This component takes care of field-level security and sharing for you, so users see only the data that they have access to.</p>



<h2 class="wp-block-heading">Creating a Record</h2>



<p>Use&nbsp;<code>mode="edit"</code>&nbsp;and pass in the object API name for the record to be created. Do not specify a recordId. Specify the fields using the&nbsp;<code>fields</code>&nbsp;attribute, or&nbsp;<code>layout-type="Full"</code>&nbsp;attribute to load all the fields defined on the full layout.The<em>&nbsp;compact layout cannot be used for creating records. If you&nbsp;</em>specify&nbsp;<em><code>layout-type="Compact"</code></em>,<em>&nbsp;the full layout is shown.</em>&nbsp;If you specify the&nbsp;<code>fields</code>&nbsp;attribute, be sure to include any fields that are designated as required for the object’s records. Because no recordId is passed, edit mode loads the form with input fields that aren’t populated with field data. The form displays Submit and Cancel buttons.This<em><strong>&nbsp;example creates an editable two-column form with the full layout and additional fields</strong></em>. The form is used for creating records in an Account object. The&nbsp;<code>onsubmit</code>&nbsp;attribute specifies an action to override the handler for the submit.</p>



<p>Create a Lightning web component&nbsp;using the below SFDX command</p>



<pre class="wp-block-code"><code>sfdx force:lightning:component:create --type lwc --componentname recordform --outputdir force-app\main\default\lwc</code></pre>



<p>Use the below recordform.html code</p>



<pre class="wp-block-code"><code>&lt;template>    
&lt;lightning-record-form object-api-name="Account" layout-type="Compact" columns="2" mode="edit"     onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>&lt;/template></code></pre>



<p>Use the below recordform.js code</p>



<pre class="wp-block-code"><code>import {LightningElement,api} from 'lwc'; 
export default class Recordform extends LightningElement {     
  handleSubmit(event) {        
   console.log(event.detail)    
  }    
  handleSuccess(event) {        
   console.log('Record iD' + event.detail.id);     
  }
}</code></pre>



<p>Use the below recordform.js-meta.xml code</p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="UTF-8"?>
&lt;LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">    &lt;apiVersion>45.0&lt;/apiVersion>    
&lt;isExposed>true&lt;/isExposed>    
&lt;targets>        
  &lt;target>lightning__RecordPage&lt;/target>    
&lt;/targets>
&lt;/LightningComponentBundle></code></pre>



<p>Push the changes and add this component to the record page layout.&nbsp;you can able to see the complete record create a form</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://i0.wp.com/rajvakati.com/wp-content/uploads/2019/02/Capture-36.png?resize=678%2C361&amp;ssl=1" alt="" class="wp-image-10355"/></figure></div>



<p>Now let’s see how to use create a record with specific fields. Now update the recordform.html code as shown below</p>



<pre class="wp-block-code"><code>&lt;template>    
&lt;lightning-record-form object-api-name={accountObject}  fields={myFields} mode="edit" onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>
&lt;/template></code></pre>



<p>Use the below recordform.js code which will be passed to the record form.</p>



<pre class="wp-block-code"><code>import {LightningElement,api} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';

export default class Recordform extends LightningElement {      
 accountObject = ACCOUNT_OBJECT;     
 myFields = &#091;NAME_FIELD, WEBSITE_FIELD];         
 handleSubmit(event) {        
  console.log(event.detail);    
 }    
 handleSuccess(event) {        
  console.log('Record iD' + event.detail.id);     
 }
}</code></pre>



<p>Push the changes and you can able to see the create form with two fields as shown below.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://i1.wp.com/rajvakati.com/wp-content/uploads/2019/02/Capture-37.png?resize=678%2C135&amp;ssl=1" alt="" class="wp-image-10357"/></figure></div>



<h2 class="wp-block-heading">Editing a Record</h2>



<p>If you do not specify the <code>mode</code> attribute, its default value is <code>edit</code>. To edit a record, pass the ID of the record and the corresponding object API name to be edited. Specify the fields using the <code>fields</code> attribute, or <code>layout-type</code> attribute to load all the fields defined on the Full or Compact layout. When <code>record-id</code> is passed, edit mode loads the form with input fields displaying the specified record’s field values. The form also displays Submit and Cancel buttons. This example creates an editable two-column form with a compact layout and additional fields. The form is used for editing records in an Account object. The <code>onsubmit</code> attribute specifies an action to override the handler for the submit. Update the recordform.html code as shown below.</p>



<pre class="wp-block-code"><code>&lt;template>    
&lt;lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full" columns="2" mode="edit" onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>
&lt;/template></code></pre>



<p>update the recordform.js code as shown below.</p>



<pre class="wp-block-code"><code>import {LightningElement, api} from 'lwc'; 
export default class Recordform extends LightningElement {    
 @api recordId;    
 handleSubmit(event) {      
  console.log(event.detail);  
 }    
 handleSuccess(event) {       
  console.log('Record iD' + event.detail.id);    
 }
}</code></pre>



<p>Use&nbsp;<code>mode="view"</code>&nbsp;and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the&nbsp;<code>fields</code>&nbsp;attribute, or&nbsp;<code>layout-type</code>&nbsp;attribute to display all the fields defined on the Full or Compact layout.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://i0.wp.com/rajvakati.com/wp-content/uploads/2019/02/Capture-38.png?resize=678%2C280&amp;ssl=1" alt="" class="wp-image-10360"/></figure></div>



<p>the following code shows the how to edit the specific fields instead of layouts.update the recordform.html code as below.</p>



<pre class="wp-block-code"><code>&lt;template>    
&lt;lightning-record-form object-api-name={accountObject} record-id={recordId}  fields={myFields} mode="edit"        
onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>&lt;/template></code></pre>



<p>update the recordform.js code as shown below.</p>



<pre class="wp-block-code"><code>import {    LightningElement,    api} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';

export default class Recordform extends LightningElement {     
@api recordId ;      
accountObject = ACCOUNT_OBJECT;     
myFields = &#091;NAME_FIELD, WEBSITE_FIELD];  
       
handleSubmit(event) {       
 console.log(event.detail);   
}    
handleSuccess(event) {       
 console.log('Record iD' + event.detail.id);    
 }
}</code></pre>



<p>Now you can able to see the changes as shown below with the specified fields.</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://i0.wp.com/rajvakati.com/wp-content/uploads/2019/02/Capture-40.png?resize=678%2C142&amp;ssl=1" alt="" class="wp-image-10362"/></figure></div>



<h2 class="wp-block-heading">Viewing a Record Read-Only</h2>



<p>The simplest way to display a record is to use the&nbsp;<code>lightning-record-form</code>. You can display a record in two modes.<code>view</code>Loads the form using output fields with inline editing enabled. Editable fields have edit icons. If a user clicks an edit icon, all fields in the form become editable, and the form displays Submit and Cancel buttons.<code>read-only</code>Read-only mode loads the form with output fields only. The form doesn’t include edit icons, Submit and Cancel buttons.</p>



<p>This code displays an account record in view mode using the compact layout, which includes fewer fields than the full layout.</p>



<p>Use <code>mode="readonly"</code> and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the <code>fields</code> attribute, or <code>layout-type</code> attribute to display all the fields defined on the Full or Compact layout. The read-only mode loads the form with output fields only, and without Submit or Cancel buttons.The following code specifis how to use the read-only mode. Use the below recordform.html code.</p>



<pre class="wp-block-code"><code>&lt;template>    
&lt;lightning-record-form record-id={recordId} object-api-name="Account"     
layout-type="Full" columns="2" mode="readonly"         
onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>
&lt;/template></code></pre>



<p>You can able to see the record with read-only data .</p>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://i2.wp.com/rajvakati.com/wp-content/uploads/2019/02/Capture-41.png?resize=678%2C283&amp;ssl=1" alt="" class="wp-image-10364"/></figure></div>



<p>Let’s update the code with view mode as shown below.&nbsp;<code>view&nbsp;</code>Loads the form using output fields with inline editing enabled. Editable fields have edit icons. If a user clicks an edit icon, all fields in the form become editable, and the form displays Submit and Cancel buttons.</p>



<p>Update the code as shown below and you can able to see the edit icon</p>



<pre class="wp-block-code"><code>&lt;template>    
&lt;lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full"     columns="2" mode="View" onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>&lt;/template></code></pre>



<div class="wp-block-image"><figure class="aligncenter"><img decoding="async" src="https://i0.wp.com/rajvakati.com/wp-content/uploads/2019/02/Capture-42.png?resize=678%2C213&amp;ssl=1" alt="" class="wp-image-10366"/></figure></div>



<h2 class="wp-block-heading">Using Record types</h2>



<p>If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the <code>record-type-id</code> attribute if you have multiple record types on an object and you don’t have a default record type. Otherwise, the default record type ID is used. Display a record create a form based on a record type by providing the <code>record-type-id</code> attribute. This example shows a form that you can place on an account record page. The form displays fields, which include a picklist with values based on the given record type Id.</p>



<pre class="wp-block-code"><code>&lt;lightning-record-form object-api-name={objectApiName} record-type-id={recordTypeId}                 fields={fields}>&lt;/lightning-record-form></code></pre>



<h2 class="wp-block-heading">Error Message</h2>



<p>To enable automatic error handling, include the component <code>lightning-messages</code>.To customize the behavior of your form when it loads or when data is submitted, use the <code>onload</code> and <code>onsubmit</code> attributes to specify event handlers. Errors are automatically handled. To customize the behavior of the form when it encounters an error on submission or when data is submitted successfully, use the <code>onerror</code> and <code>onsuccess</code> attributes to specify event handlers</p>



<pre class="wp-block-code"><code>&lt;template>            
&lt;lightning-messages>&lt;/lightning-messages>     
&lt;lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full"     columns="2" mode="View" onsuccess={handleSuccess} onsubmit={handleSubmit}>    
&lt;/lightning-record-form>&lt;/template></code></pre>



<p>Source :  <a href="https://rajvakati.com/2019/02/16/lightning-record-form/">https://rajvakati.com/2019/02/16/lightning-record-form/</a> </p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2019/11/18/usage-of-lightning-record-form/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">3015</post-id>	</item>
		<item>
		<title>Apex Calling Methods In Lightning web components</title>
		<link>https://www.mhamzas.com/blog/2019/06/25/apex-calling-methods-in-lightning-web-components/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=apex-calling-methods-in-lightning-web-components</link>
					<comments>https://www.mhamzas.com/blog/2019/06/25/apex-calling-methods-in-lightning-web-components/#comments</comments>
		
		<dc:creator><![CDATA[hamza]]></dc:creator>
		<pubDate>Tue, 25 Jun 2019 10:48:37 +0000</pubDate>
				<category><![CDATA[Salesforce]]></category>
		<category><![CDATA[lightning]]></category>
		<category><![CDATA[lwc]]></category>
		<category><![CDATA[salesforce]]></category>
		<guid isPermaLink="false">https://www.mhamzas.com/?p=2883</guid>

					<description><![CDATA[Let’s discuss here how to call the apex class from the Lightning web components. Lightning web components can import methods from Apex classes into the JavaScript&#160;classes using ES6&#160;import. Once after importing the apex class method you can able call the apex methods <br /><a href="https://www.mhamzas.com/blog/2019/06/25/apex-calling-methods-in-lightning-web-components/" class="more-link btn btn-primary">Read More</a>]]></description>
										<content:encoded><![CDATA[
<p>Let’s discuss here how to call the apex class from the Lightning web components. Lightning web components can import methods from Apex classes into the JavaScript&nbsp;classes using ES6&nbsp;import. Once after importing the apex class method you can able call the apex methods as functions into the component by calling either via the wire service or imperatively. Before you use an Apex method, make sure that there isn’t an easier way to get the data. See whether a base Lightning component, like&nbsp;lightning-record-form,&nbsp;lightning-record-view-form, or&nbsp;lightning-record-edit-form&nbsp;works for your use case. If they don’t give you enough flexibility, use a wire adapter like&nbsp;getListUi&nbsp;or&nbsp;getRecordUi.&nbsp;</p>



<h4 class="wp-block-heading">Import Syntax&nbsp;</h4>



<p>You can able use&nbsp;default export&nbsp;syntax to import an Apex method via the&nbsp;@salesforce/apex&nbsp;scoped module into JavaScript&nbsp;controller class. The&nbsp;Syntax looks like below.Default</p>



<pre class="wp-block-code"><code>import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';</code></pre>



<p><em><strong>apexMethod</strong></em>—The imported symbol that identifies the Apex method.<br><em><strong>Namespace</strong></em>—The namespace of the Salesforce organization. Specify a namespace unless the organization uses the default namespace (c), in which case don’t specify it.<br><em><strong>Classname</strong></em>—The name of the Apex class.</p>



<h4 class="wp-block-heading">Create Apex Class&nbsp;</h4>



<p>In this example, we will be getting account data and show it into the UI. Create an apex class using SFDX create apex class command.Default</p>



<pre class="wp-block-code"><code>sfdx force:apex:class:create -n GetAccountData -d force-app/main/default/apex</code></pre>



<p>Here is the apex class. To expose an Apex method to a Lightning web component, the method must be static and either global or public. Annotate the method with @AuraEnabledDefault</p>



<pre class="wp-block-code"><code>public with sharing class GetAccountData {
   @AuraEnabled(cacheable=true)
    public static List&lt;Account&gt; getAccountList() {
        return &#091;SELECT Id, Name,Type,Rating,Phone FROM Account];
    }
}</code></pre>



<p>Now you can able to call the apex class in&nbsp; Lightning web component using these different&nbsp;ways.</p>



<ul class="wp-block-list">
<li>Wire a property</li>



<li>Wire a function</li>



<li>Call a method imperatively</li>
</ul>



<h4 class="wp-block-heading">Wire an Apex Method to a Property</h4>



<p>If an Apex method is annotated with @AuraEnabled(Cacheable=true), you can invoke it from a component via the wire service. You can @wire a property or a function. Here is the syntaxDefault</p>



<pre class="wp-block-code"><code>import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
@wire(apexMethod, { apexMethodParams })
propertyOrFunction;</code></pre>



<p>Create a Lightning web component&nbsp;using below SFDX commandsDefault</p>



<pre class="wp-block-code"><code>sfdx force:lightning:component:create --type lwc -n LWCWireEx -d force-app/main/default/lwc</code></pre>



<p>Here is the&nbsp;LWCWireEx.html markup for the lightning web components.Default</p>



<pre class="wp-block-code"><code>&lt;template&gt;
    &lt;lightning-card title="Apex Class Example" icon-name="custom:custom63"&gt;
            &lt;div class="slds-m-around_medium"&gt;
                &lt;template if:true={accounts.data}&gt;
                    &lt;template for:each={accounts.data} for:item="acc"&gt;
                        &lt;p key={acc.Id}&gt;{acc.Name}&lt;/p&gt;
                    &lt;/template&gt;
                &lt;/template&gt;
                
            &lt;/div&gt;
        &lt;/lightning-card&gt;
&lt;/template&gt;</code></pre>



<p>Here is the&nbsp;LWCWireEx.js classDefault</p>



<pre class="wp-block-code"><code>import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';

export default class LWCWireEx extends LightningElement {
    @wire(getAccountList) accounts;
}</code></pre>



<p>Here is the&nbsp;LWCWireEx.js-meta.xml markup.Default</p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"&gt;
    &lt;apiVersion&gt;45.0&lt;/apiVersion&gt;
    &lt;isExposed&gt;false&lt;/isExposed&gt;
    &lt;targets&gt;
        &lt;target&gt;lightning__RecordPage&lt;/target&gt;
       &lt;/targets&gt;
&lt;/LightningComponentBundle&gt;</code></pre>



<p>Push the changes to scratch org and add the lightning web component to the record page. You can able to see the result like below.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://i2.wp.com/rajvakati.com/wp-content/uploads/2018/12/Capture-59.png?resize=612%2C322&amp;ssl=1" alt="" class="wp-image-8980"/></figure>
</div>


<h4 class="wp-block-heading">Wire an Apex Method to a Function</h4>



<p>Now let’s look at how to wire an apex method to function.we will be updating&nbsp;the same code here to operate the apex method as function.</p>



<p>Update the LWCWireEx.js class as shown&nbsp;belowDefault</p>



<pre class="wp-block-code"><code>import { LightningElement, wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';

export default class LWCWireEx extends LightningElement {
    @track accounts;
    @track error;
    @wire(getAccountList)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.log(error);
            this.error = error;
        }
    }
}</code></pre>



<p>update the&nbsp;LWCWireEx.html markup as shown belowDefault</p>



<pre class="wp-block-code"><code>&lt;template&gt;

    &lt;lightning-card title="Apex Wire To Function Example" icon-name="custom:custom63"&gt;

        &lt;div class="slds-m-around_medium"&gt;
            &lt;template if:true={accounts}&gt;
                 &lt;ul&gt;
                &lt;template for:each={accounts} for:item="account"&gt;
                    &lt;li key={account.Id}&gt; {account.Name} &lt;/li&gt;
                &lt;/template&gt;
             &lt;/ul&gt;
            &lt;/template&gt;
            &lt;template if:true={error}&gt;
                {error}
            &lt;/template&gt;                
        &lt;/div&gt;
    &lt;/lightning-card&gt;
&lt;/template&gt;</code></pre>



<p>Push the changes to scratch org and add the lightning web component to the record page. You can able to see the result like below.</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://i1.wp.com/rajvakati.com/wp-content/uploads/2018/12/Capture-60.png?resize=607%2C324&amp;ssl=1" alt="" class="wp-image-8984"/></figure>
</div>


<h4 class="wp-block-heading">Call an Apex Method Imperatively</h4>



<p>Now let’s see here how to call apex method&nbsp;imperatively. Create a new Lightning web component using the below SFDX commandDefault</p>



<pre class="wp-block-code"><code>sfdx force:lightning:component:create --type lwc -n ImperativEx -d force-app/main/default/lwc</code></pre>



<p>Use the below ImperativEx.html codeDefault</p>



<pre class="wp-block-code"><code>&lt;template&gt;
        &lt;lightning-card title="Apex Imperative Method Example"&gt;
            &lt;div class="slds-m-around_medium"&gt;
                &lt;p class="slds-m-bottom_small"&gt;
                    &lt;lightning-button label="Load Accounts" onclick={handleLoad}&gt;&lt;/lightning-button&gt;
                &lt;/p&gt;
                &lt;template if:true={accounts}&gt;
                    &lt;template for:each={accounts} for:item="account"&gt;
                        &lt;p key={account.Id}&gt;{account.Name}&lt;/p&gt;
                    &lt;/template&gt;
                &lt;/template&gt;
                &lt;template if:true={error}&gt;
                   {error}
                &lt;/template&gt;
            &lt;/div&gt;
        &lt;/lightning-card&gt;
    &lt;/template&gt;</code></pre>



<p>Use the below ImperativEx.js class codeDefault</p>



<pre class="wp-block-code"><code>import { LightningElement, wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';


export default class ImperativEx extends LightningElement {
    @track accounts;
    @track error;
    handleLoad() {
        getAccountList()
            .then(result =&gt; {
                this.accounts = result;
            })
            .catch(error =&gt; {
                this.error = error;
            });
    }
}</code></pre>



<p>Use the below ImperativEx.js-meta.xml class codeDefault</p>



<pre class="wp-block-code"><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="hello"&gt;
    &lt;apiVersion&gt;45.0&lt;/apiVersion&gt;
    &lt;isExposed&gt;false&lt;/isExposed&gt;
     &lt;targets&gt;
        &lt;target&gt;lightning__RecordPage&lt;/target&gt;
    &lt;/targets&gt;
&lt;/LightningComponentBundle&gt;</code></pre>



<p>push the changes to scratch org and add the lightning web component to the record page and you can able to see the below result when you click on the button .</p>


<div class="wp-block-image">
<figure class="aligncenter"><img decoding="async" src="https://i0.wp.com/rajvakati.com/wp-content/uploads/2018/12/Capture-61.png?resize=560%2C375&amp;ssl=1" alt="" class="wp-image-8987"/></figure>
</div>


<h2 class="wp-block-heading">Call an Apex Method with Parameters</h2>



<p>Pass parameters values to an Apex method in an object whose properties match the parameters of the Apex method. For example, if the Apex method takes a string parameter, don’t pass a string directly. Instead, pass an object that contains a property whose value is a string.</p>



<figure class="wp-block-image"><img data-recalc-dims="1" decoding="async" src="https://i0.wp.com/resources.docs.salesforce.com/images/28232961511d39db2ddf9b5a0110df79.png?w=640&#038;ssl=1" alt="Enter characters in a seach field and click Search to return a list of contacts."/></figure>



<pre class="wp-block-code"><code><em>// apexImperativeMethodWithParams.js</em>

import { LightningElement } from 'lwc';
import findContacts from '@salesforce/apex/ContactController.findContacts';

export default class ApexImperativeMethodWithParams extends LightningElement {
    searchKey = '';
    contacts;
    error;

    handleKeyChange(event) {
        this.searchKey = event.target.value;
    }

    handleSearch() {
        findContacts({ searchKey: this.searchKey })
            .then((result) =&gt; {
                this.contacts = result;
                this.error = undefined;
            })
            .catch((error) =&gt; {
                this.error = error;
                this.contacts = undefined;
            });
    }
}</code></pre>



<pre class="wp-block-code"><code>public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List&lt;Contact&gt; findContacts(String searchKey) {
        String key = '%' + searchKey + '%';
        return &#091;
            SELECT Id, Name, Title, Phone, Email, Picture__c
            FROM Contact
            WHERE Name LIKE :key AND Picture__c != NULL
            WITH SECURITY_ENFORCED
            LIMIT 10
        ];
    }
}</code></pre>
]]></content:encoded>
					
					<wfw:commentRss>https://www.mhamzas.com/blog/2019/06/25/apex-calling-methods-in-lightning-web-components/feed/</wfw:commentRss>
			<slash:comments>6</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2883</post-id>	</item>
	</channel>
</rss>
