Thursday, April 23, 2020

Add event in LWC and Listen in Visualforce page

While reading this, you might have an idea how it should works and why ? In order to make it easy, I narrow down problem statement so I can write simple, short solution for future reference. All comments, ideas except spams are welcome.

Problem Statement

  • Now how do I redirect page ?

Solution 

Adding create event in LWC and add the listener to visualforce page

Technical Implementation


In LWC javascript , create event on function that handles redirection. For example maybe you want user to go to different page when the button is clicked.


 //function to redirect to opportunity detail
   handleOnOppLink(){
        this.showLoadingSpinner = false;
  //create new Event with any meaningful name, in my case 'redirectFromLWC'
        this.dispatchEvent(new CustomEvent('redirectFromLWC', 
           {
               detail: { recordId: this.opportunityId,recordMode:"detail"},
               bubbles: true,
               composed: false,
          
           }));

      }

In Aura app, ensure you define EVENT

<aura:application access="GLOBAL" extends="ltng:outApp" >
 <aura:dependency resource="myCustom_lwc"/>
 <aura:dependency resource="markup://force:*" type="EVENT"/>
</aura:application>

In Visualforce page, add the listener to listen to the event. Ensure the event name is matched.


<script>  
document.addEventListener("redirectFromLWC", function(event){
           console.log('vf event data window listener => ', event.detail);
    
    //here is just code to get the details that passed from the event
           var detail =JSON.stringify(event.detail);
           console.log('data => '+detail);
           var data =JSON.parse(detail);
           console.log('data.recordId => '+data.recordId);
           var recordId =data.recordId;
           var recordMode =data.recordMode;
     
     
          //here the code is to handle navigation, as you can see I have to condition one in go to details
    // and another is go to edit.
           if(recordMode=='detail'){
               if(recordId===''){
                console.log('data.recordId 1=> '+ '{!oppId}');
                recordId='{!CustomObject__c.Opportunity__c}';
               }
            sforce.one.navigateToSObject(recordId, recordMode); 
            }
         else if(recordMode=='edit'){
            sforce.one.editRecord(recordId);
         
          }
 
        
        });

//other code
</script>

No comments:

Post a Comment