Search code examples
salesforceapexlwcsalesforce-communities

Call lightning Web Component from URL and capture parameter from URL


I want to redirect user from one LWC to another by clicking on URL in experience cloud. Basically, on my first LWC I am showing the list of records retrieved from Apex and then when any row is clicked, I want to pass recordId of that row and redirect to second LWC which will show the record details page. How can I achieve this?


Solution

  • Do you have a Community... sorry, Experience Builder page with that target LWC dropped?

    You could use NavigationMixin although documentation says communities don't support the state property.

    On source side try something like

    /* Assumes the link/button clicked looks like
        <button data-id={acc.Id} onclick={handleClick}>Get details</button>
    */
    handleClick(event){
        if(event.currentTarget.dataset.id){
            this[NavigationMixin.Navigate]({
                type: 'comm__namedPage',
                attributes: {
                    name: 'MyTargetCommunityPage__c'
                },
                state: {
                    id: event.currentTarget.dataset.id
                }
            });
        }
    }
    

    And then on target page's LWC it should be accessible as

    connectedCallback() {
        if(window.location.href){
            try{
                let url = new URL(window.location.href);
                var id = url.searchParams.get('id');
                if(id){
                    this.myId = id;
                }
            } catch(e){
                if(console){
                    console.log(JSON.stringify(e));
                }
            }
        }
    }
    

    If Navigation gives you hard time you can ditch it and go straight for window.open('/pagename?id=123', _self); or something. It's bit annoying that you have 1 set of rules for core Salesforce, 1 for community.

    (if you have a namespace - you might need to use myns__id in the state instead of id)