ship
SalesForce Simplified

Your Go-To Resource for Streamlined Solutions and Expert Guidance

mountains
Empower Your Business
Dive deep into the world of CRM excellence, where innovation meets practicality, and transform your Salesforce experience with Forceshark's comprehensive resources

How to Build Dynamic Modal Windows in LWC for Enhanced User Experiences

Modal windows are a crucial component in user interfaces, providing a way to display content or gather input while maintaining focus on the current task. In Lightning Web Components (LWC), modals offer a clean and effective solution for various scenarios, including displaying alerts, confirming actions, or presenting forms.<br><h3>Creating a Modal Component</h3><p>To create a modal in LWC, begin by structuring a Lightning Web Component. Consider a real-world business use case, such as an Error Handling Modal. Below is a simplified example of how the HTML and JavaScript files for the modal component might look.</p><h3>Expense Report Submission with Error Handling Modal</h3><p>Employees regularly submit expense reports for reimbursement in a corporate expense management system built on Salesforce. A Lightning Web Component (LWC) is developed to streamline the process for submitting expense reports. However, to enhance user experience, an Error Handling Modal LWC is implemented to address validation errors that may occur during the submission process.</p><h4>HTML Template</h4><pre><code class="language-markup">&lt;template&gt;
    &lt;lightning-modal-header label="Error"&gt;&lt;/lightning-modal-header&gt;
    &lt;lightning-modal-body&gt;
        &lt;!-- Display the error message from the parent component --&gt;
        &lt;!-- Include additional details or instructions for the user --&gt;
        {errorMessage}
    &lt;/lightning-modal-body&gt;
    &lt;lightning-modal-footer&gt;
        &lt;!-- Close button for the modal --&gt;
        &lt;lightning-button label="Close" onclick={closeModal}&gt;&lt;/lightning-button&gt;
    &lt;/lightning-modal-footer&gt;
&lt;/template&gt;</code></pre><h4>JS Controller</h4><p></p><pre><code class="language-apex">export default class FsrkExpenseReportForm extends LightningElement {
&nbsp; &nbsp; expenseAmount;
&nbsp; &nbsp; expenseDescription;
&nbsp; &nbsp; async submitExpenseReport() {
&nbsp; &nbsp; &nbsp; &nbsp; // Validate form fields
&nbsp; &nbsp; &nbsp; &nbsp; if (!this.expenseAmount || !this.expenseDescription) {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Show the error handling modal
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const result = await errorHandlingModal.open({
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // The title of for the modal
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label: 'Error',
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Indicates the portion of the viewport width the modal occupies: 'small' | 'medium' | 'large'
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; size: 'small',
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // A string providing an accessible description for the modal
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; description: '',
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // 'true' | 'false' A boolean flag that hinders the modal from being closed
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; disableClose: false,
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Custom error message, refer to the @errorMessage in fsrk_ErrorHandlingModal
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errorMessage: "Please fill in all required fields.",
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // result contains a promise that is fulfilled with the outcome of the user's interaction with the modal.
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log('FsrkExpenseReportForm::result', result);
&nbsp; &nbsp; &nbsp; &nbsp; } else {
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // Logic for submitting the expense report goes here
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // If successful, navigate to a success page or display a success modal
&nbsp; &nbsp; &nbsp; &nbsp; }
&nbsp; &nbsp; }
}</code></pre><p></p><p>In this scenario, the fsrk_ExpenseReportForm LWC contains a form for submitting expense reports. The submitExpenseReport method performs basic validation, and if any errors are detected (such as missing required fields), it opens a custom modal window with an error message.</p><h3>Second LWC: Error Handling Modal</h3><h4>HTML Template</h4><pre><code class="language-markup">&lt;template&gt;
    &lt;lightning-modal-header label="Error"&gt;&lt;/lightning-modal-header&gt;
    &lt;lightning-modal-body&gt;
        &lt;!-- Display the error message from the parent component --&gt;
        &lt;!-- Include additional details or instructions for the user --&gt;
        {errorMessage}
    &lt;/lightning-modal-body&gt;
    &lt;lightning-modal-footer&gt;
        &lt;!-- Close button for the modal --&gt;
        &lt;lightning-button label="Close" onclick={closeModal}&gt;&lt;/lightning-button&gt;
    &lt;/lightning-modal-footer&gt;
&lt;/template&gt;</code></pre><h4>JS Controller</h4><p></p><pre><code class="language-apex">export default class FsrkErrorHandlingModal extends LightningModal {
&nbsp; &nbsp; @api errorMessage;
&nbsp; &nbsp; closeModal() {
&nbsp; &nbsp; &nbsp; &nbsp; // Close the modal
&nbsp; &nbsp; &nbsp; &nbsp; // When calling the this.close method, you can pass not only a string (e.g. 'ok') as a parameter,
&nbsp; &nbsp; &nbsp; &nbsp; // but also any other data, such as an object.
&nbsp; &nbsp; &nbsp; &nbsp; // The passed value will be returned to the calling LWC component.
&nbsp; &nbsp; &nbsp; &nbsp; this.close('ok');
&nbsp; &nbsp; }
}</code></pre><p></p><p>The fsrk_ErrorHandlingModal LWC is designed to receive this event, display the error message, and provide a button for users to close the modal. The modal can be styled to ensure it stands out, and it helps users understand and address issues during the expense report submission process.<br></p><h3>Passing Data to the Modal</h3><p>Make your modal component dynamic by passing data into it. Use properties or attributes to achieve this. For instance, if you want to display different error messages, modify the component's JS as follows:</p><p></p><pre><code class="language-apex">const result = await errorHandlingModal.open({
&nbsp; &nbsp; ...
&nbsp; &nbsp; errorMessage: "&lt;MESSAGE&gt;",
});</code></pre><p></p><h3>Event Handling and Closing the Modal</h3><p>Handling events within the modal component is crucial for user interactions. Implement logic based on user actions, such as button clicks. In the example above, the closeModal method handles the button click event, allowing you to perform the necessary action and close the modal.</p><h3>Conclusion</h3><p>This article explored how to implement modal windows in Lightning Web Components (LWC). We discussed creating a modal component, passing data into the modal, handling events within the modal, and closing the modal. By following these guidelines, developers can enhance user experiences in their LWC applications with dynamic and versatile modal functionality.</p>