Lightning-Web-Components – Overriding New Button with LWC Wrapped in Aura and Fixing Additional Tab Issue

aurabutton-overrideslightning-web-components

I'm trying to override a New button (from List view) with LWC wrapped in Aura. The thing is, I want the New button redirect to a record page, meaning – the New button should create the record and navigate to the newly created record page. So, in my LWC I'm creating that record and navigating to it. That works fine, but 1 additional tab keeps opening as soon as you click on the New button and I cannot close it from LWC, since WorkspaceAPI is not working from LWC when it is wrapped in Aura. It works if I try it in Aura, but then I either close everything and LWC doesn't do its job or I again cannot close that additional tab, but the focused one instead – and I want to leave the focused one and close the other one which is opened by default.

I tried calling the LWC from Aura's doInit function, but then I get the Loading tab as well. So, it works well when I add the LWC to the Aura component, but I'm stuck with removing that extra tab (in the screenshot tab 'New My Object').

Aura:

<aura:component implements="lightning:actionOverride,force:hasRecordId,force:hasSObjectName">
    <c:myLWC/>
</aura:component>

LWC:

import { LightningElement, wire, track, api } from 'lwc';
import { getObjectInfo} from 'lightning/uiObjectInfoApi';
import { createRecord} from 'lightning/uiRecordApi';
import { NavigationMixin } from 'lightning/navigation';

import MY_OBJECT from '@salesforce/schema/MyObject';

const MY_OBJECT_NAME = 'MyObject';
const MY_OBJECT_RECORD_TYPE_NAME = 'MyObject RT Name';


export default class myLWC extends NavigationMixin(LightningElement) { 
    @track recordTypeId;
    myObjectId;

    @wire(getObjectInfo, { objectApiName: MY_OBJECT_NAME})
    wiredObjectInfo({error, data}) {
        if (error) {
            this.displayError(error);
        } else if (data) {
            const rtis = data.recordTypeInfos;
            const matchingRTid = Object.keys(rtis).find(rti => rtis[rti].name === MY_OBJECT_RECORD_TYPE_NAME);
            if(matchingRTid) this.recordTypeId = matchingRTid;
        }
    };


    connectedCallback(){
        let recordObj = {
            apiName: MY_OBJECT.objectApiName,
            fields: {
                RecordTypeId : this.recordTypeId
            }
        };

        createRecord(recordObj)
            .then((record) => {
                this.myObjectId= record.id;
                this.navigateToRecordPage();  
              })
            .catch(error => {
                console.error(error);
            });
    }

    navigateToRecordPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.myObjectId,
                objectApiName: 'myObject',
                actionName: 'view'
            }
        });
    }

}

Extra Tab

enter image description here

Best Answer

I suggest that you manage the navigation in the Aura wrapper instead of the LWC.

  1. On Aura component loading you can retrieve the tab Id and save it in a variable.

  2. When you create your record from the LWC you can dispatch an event to inform the Aura that the new record was created providing the new recordId.

  3. You can have Aura open the new tab showing the record and closing the original tab.

In the Aura wrapper you could have something like

Aura.cmp

<aura:component implements="lightning:actionOverride,force:hasRecordId,force:hasSObjectName">
  <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  <aura:attribute name="newMOTabId" type="String"/>
  <lightning:workspaceAPI aura:id="workspace"/>
  <c:myLWC onmyobjectcreated="{!c.handleMyObjectCreated}"/>
</aura:component>

AuraController.js

({
  doInit: function(component, event, helper){
    const workspaceAPI = component.find("workspace");
    workspaceAPI.getFocusedTabInfo()
    .then((response) => {
        const newMOTabId = response.tabId;
        component.set('v.newMOTabId', newMOTabId);
    })
    .catch(function(error) {
        console.log(error);
    });
  },
  
  handleMyObjectCreated: function(component, event, helper){
   const workspaceAPI = component.find("workspace");
    workspaceAPI.openTab({
        pageReference: {
            "type": "standard__recordPage",
            "attributes": {
                "recordId": event.getParam('myObjectId'),
                "actionName":"view"
            },
            "state": {}
        },
        focus: true
    }).then((response) => {
        if(response){
            workspaceAPI.closeTab({tabId: component.get('v.newMOTabId')});
        }
    }).catch(function(error) {
        console.log(error);
    });

  
  }
})

LWC:

import { LightningElement, wire, track, api } from 'lwc';
import { getObjectInfo} from 'lightning/uiObjectInfoApi';
import { createRecord} from 'lightning/uiRecordApi';
import { NavigationMixin } from 'lightning/navigation';
import MY_OBJECT from '@salesforce/schema/MyObject';
const MY_OBJECT_NAME = 'MyObject';
const MY_OBJECT_RECORD_TYPE_NAME = 'MyObject RT Name';

export default class myLWC extends NavigationMixin(LightningElement) { 
@track recordTypeId;
myObjectId;

@wire(getObjectInfo, { objectApiName: MY_OBJECT_NAME})
wiredObjectInfo({error, data}) {
    if (error) {
        this.displayError(error);
    } else if (data) {
        const rtis = data.recordTypeInfos;
        const matchingRTid = Object.keys(rtis).find(rti => rtis[rti].name === MY_OBJECT_RECORD_TYPE_NAME);
        if(matchingRTid) this.recordTypeId = matchingRTid;
    }
};


connectedCallback(){
    let recordObj = {
        apiName: MY_OBJECT.objectApiName,
        fields: {
            RecordTypeId : this.recordTypeId
        }
    };

    createRecord(recordObj)
        .then((record) => {
            this.myObjectId= record.id;
            this.dispatchEvent(new CustomEvent('myobjectcreated', 
                                               {detail: {myObjectId: this.myObjectId}}));  
          })
        .catch(error => {
            console.error(error);
        });
} 
Related Topic