Get Parent Id when overriding standard actions with a Lightning Component in salesforce1 app

How to Get Parent Id when overriding standard actions with a Lightning Component in salesforce1 app ?


In this blog I will explain how you can get Parent Id when overriding standard actions with a lightning component.

For example I have changed my Opportunity New button action with a custom Lightning Component. 

Let's create a new account and from the related tab try creating the new Opportunity. Have you noticed any change in URL ?

Let me share the URL with you : 
_________________________________________________________________________
https://kapilbatra1-dev-ed.lightning.force.com/lightning/o/Opportunity/new?recordTypeId=0127F000000htlpQAA&additionalParams=accid%3D0017F00002S6g9H%26&inContextOfRef=1.eyJ0eXBlIjoic3RhbmRhcmRfX3JlY29yZFBhZ2UiLCJhdHRyaWJ1dGVzIjp7Im9iamVjdEFwaU5hbWUiOiJBY2NvdW50IiwicmVjb3JkSWQiOiIwMDE3RjAwMDAyUzZnOUhRQVIiLCJhY3Rpb25OYW1lIjoidmlldyJ9LCJzdGF0ZSI6e319&count=3
_________________________________________________________________________

In above URL you can notice an "additionalParams" parameter containing the Parent ID.  But in the Ssalesforce1 App the scenario is completely different. In Salesforce1 App you have to perform some additional steps.

Let's check the URL first in the Salesforce1 App

_________________________________________________________________________
https://kapilbatra1-dev-ed.lightning.force.com/lightning/o/Opportunity/new?recordTypeId=0127F000000htlp&inContextOfRef=1.eyJ0eXBlIjoic3RhbmRhcmRfX2RpcmVjdENtcFJlZmVyZW5jZSIsImF0dHJpYnV0ZXMiOnsibmFtZSI6Im9uZTphbG9oYVBhZ2UiLCJhdHRyaWJ1dGVzIjp7ImFkZHJlc3MiOiIvc2V0dXAvdWkvcmVjb3JkdHlwZXNlbGVjdC5qc3A%2FZW50PU9wcG9ydHVuaXR5JnNhdmVfbmV3X3VybD0lMkYwMDYlMkZlJTNGYWNjaWQlM0QwMDE3RjAwMDAyUzZnOUgmbmF2aWdhdGlvbkxvY2F0aW9uPVJFTEFURURfTElTVCJ9fSwic3RhdGUiOnt9fQ%3D%3D
_________________________________________________________________________

In above URL you will notice that the "Additionalparam" parameter is missing and we are just getting an encoded URL.

To get the parent Id from URL of Lightning Component & Salesforce1 App  here is the code below : 

OpportunityPage.cmp

1
2
3
4
5
6
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,lightning:actionOverride,lightning:isUrlAddressable" access="global" >
 <aura:attribute name="recordId" type="String"/>
 <aura:attribute name="accId" type="string"/>
    <aura:handler name="init" action="{!c.doInit}" value="{!this}" />
    <p style="font-size:40px">Parent ID : {!v.accId}</p> 
</aura:component>


OpportunityPageController.js


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
({
 doInit : function(component, event, helper) {
        //Get Parent Id from URL start 
        //
        //
        var pageReference = component.get("v.pageReference");
        console.log('###RecordId : '+pageReference.state.recordTypeId);
        var getAccId = pageReference.state.additionalParams;
        if(typeof getAccId !== 'undefined') {
            console.log('###GetAccID : '+getAccId);
            getAccId = getAccId.replace('accid=','');
            getAccId = getAccId.substring(0,15);
            console.log('###AccId : '+getAccId);
            component.set("v.accId", getAccId);
        }
        //
        //
        //Get Parent ID from URL end
        //
        //
        //Get Parent ID from URL in Salesforce1 App Start
        //
        //
        //
        var value = helper.getParameterByName(component , event, 'inContextOfRef');
        console.log('###Value='+value);
        var context = JSON.parse(window.atob(value));
        console.log('###context='+context);
        var newContext = JSON.stringify(context);
        console.log('###newContext : '+newContext);
        if(newContext.indexOf("address")>0){
            console.log('###Context : '+context.attributes.attributes.address);
            var url =context.attributes.attributes.address;
            console.log('###URL='+url);
            var n = url.indexOf("accid%3D");
            var subStr = url.substring(n+8);
            console.log('###Sub Str='+subStr);
            var accId = subStr.substring(0,15);
            console.log('###AccId : '+accId);
            component.set("v.accId", accId);
        }
        else{
            console.log('##Its not a Salesforce1 App');
        }
        //
        //
        //Get Parent ID from URL in Salesforce1 App end
        
 }
})


OpportunityPageHelper.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
({
 getParameterByName: function(component, event, name, url) {
        name = name.replace(/[\[\]]/g, "\\$&");
        var url = window.location.href;
        var regex = new RegExp("[?&]" + name + "(=1\.([^&#]*)|&|#|$)");
        var results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
})


Note : Please open the console in your browser and check the logs carefully to understand it better.

Check the video below to understand it better






Please check below links also and subscribe if you like the content : 
If you have any question please leave a comment below.
If you would like to add something to this post please leave a comment below.
Share this blog with your friends if you find it helpful somehow !

Thanks
Keep Coding 😊

Post a Comment

37 Comments

  1. Hi,

    Thanks for posting this, but I am getting below error. I'm overriding the button with VF page:

    Invalid 'X-Frame-Options' header encountered when loading 'https://motorolasolutions--uat.my.salesforce.com/setup/ui/recordtypeselect.jsp?ent=Opportunity&save_new_url=%2F006%2Fe%3Faccid%3D0018000000rFekD&navigationLocation=RELATED_LIST&lexiSObjectName=Opportunity&lexiActionName=new&tour=&isdtp=p1&sfdcIFrameOrigin=https://motorolasolutions--uat.lightning.force.com&nonce=299579a9d082d249f00787a947b0abe347bad71414ba233cff4a7930c42ff402&clc=0&sfdcIFrameHost=web&ltn_app_id=': 'ALLOW-FROM https://motorolasolutions--uat.lightning.force.com' is not a recognized directive. The header will be ignored.

    ReplyDelete
    Replies
    1. Hi Gurditta Garg,

      You can bypass the above error by disabling CORS in chrome. It seems like a browser related issue to me.
      Please check below link for reference
      https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options

      Delete
  2. hi we got parent id how to bind that into child filed if you have any idea please kindly help me out .

    ReplyDelete
    Replies
    1. Hello, please check link below :
      https://www.salesforcebolt.com/2020/05/pass-variables-parent-child-lightning-component.html

      Delete
  3. Hi,

    I don't think the above senerio works for all objects. I created a custom object and whenever I create the object in Salesforce below is the URL: https://*.force.com/lightning/o/Quote__c/new . How can I get the parent ID then?

    ReplyDelete
    Replies
    1. Hi,

      No it won't work as the scenario will only work when you override a standard action with your custom Lightning Component.

      Delete
  4. Hi,

    I don't think the above senerio works for all objects. I created a custom object and whenever I create the object in Salesforce below is the URL: https://*.force.com/lightning/o/Quote__c/new . How can I get the parent ID then?

    ReplyDelete
    Replies
    1. Hi,

      No it won't work as the scenario will only work when you override a standard action with your custom Lightning Component.

      Delete
  5. Hi

    I'm getting error ''Action failed: c:CA_InternalSupportNewCaseButton$controller$doInit [address is not defined]''.

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Getting error ''Action failed: c:CA_InternalSupportNewCaseButton$controller$doInit [address is not defined]'' at below line.
      if(newContext.indexOf("address")>0)

      Delete
    3. The reason is you are not getting address parameter in your url. Please check your parameter name and pass it instead of address.

      Delete
    4. Cool, Thanks its working now.

      Delete
  6. HI, I am unable to see adidtionalParam attribute from lightning for the child object related list from parent for both opportunity and custom objects. Please help me out here

    ReplyDelete
    Replies
    1. Please check your URL again, if the additionalParam parameter is not available then there must be some other parameters in the URL.

      Delete
  7. Hi, this code is working fine for desktop but in mobile app I am getting error for JSON parser. It seems that window.location.href URL is completely different on mobile. it has /native/bridge.app/... in the URL.

    ReplyDelete
    Replies
    1. Hello, the functionality is only for when you override standard action with your custom component. Are you having the same scenario ? If yes, could you please share complete URL here so I could help.

      Delete
    2. Hi, yes I am overriding Opportunity New button . When triggered from Account related list it hsa following window.location.ref: http:///native/bridge.app?maxLayoutcachesize=5&eventTransalator=1.0#/lightning/o/Opportunity/new

      Delete
    3. On further looking it seems that i am getting the destination details rather than source. In v.pageReference also I am getting the Opportunity details.

      Delete
    4. Thanks for sharing the details. I am not sure about it why you are not getting the source url.
      I will ping you back here if I get some solution for it.

      Delete
  8. Hey Kapil, I am trying to use your logic to override View Action on the related list. Will this work for it as well?

    ReplyDelete
    Replies
    1. Hello, yes it will work but URL parameters will be changed in the case of View Action. Kindly modify the code accordingly.

      Delete
  9. Hi Kapil, great post. I'm running into same issue where when standard action is overridden by a component the parent id is not getting pre-populated on a related list. It works as a quick action.

    I'm trying to implement your solution but running into issues. I'm using virtual device builds for iOS simulator. How do you debug your mobile code? I mean how to see console.log statements when running on mobile as Chrome tools mobile UI is broken after Summer 2020 release. Thanks.

    ReplyDelete
    Replies
    1. Hi, to debug the code you can also try alert() in JavaScript instead of console.log
      Let me know if that works for you.

      Delete
  10. Hi kapil,

    Thanks for post, but Actually i am trying to get the standard page layout of contact.
    when i click new button from related list at that movement account name is not populating .
    the code i refereed is https://gist.github.com/sfcure/845a0e75815f7c0d6c92baebcce5bc3d(if any other alternative is also fine for me)

    Thanks in Advance.

    ReplyDelete
    Replies
    1. Hi sfdcdev, I didn't understand your query. Whenever you will click on the new button Contact from Account's related list, it will redirect you to the standard page itself automatically. There is no need to get parameters from URL.

      Delete
    2. Hi Kapil,

      I am overriding the standard page with my custom component.
      Actually in jscontroller i am using the below code but code is working fine for desktop version when i login from mobile it is not working.







      doInit : function(component,event,helper){
      //alert(component.get("v.recordId"));
      var pageRef = component.get("v.pageReference");
      console.log(JSON.stringify(pageRef));
      var state = pageRef.state; // state holds any query params
      console.log('state = '+JSON.stringify(state));
      var base64Context = state.inContextOfRef;
      console.log('base64Context = '+base64Context);
      if (base64Context.startsWith("1\.")) {
      base64Context = base64Context.substring(2);
      console.log('base64Context = '+base64Context);
      }
      var addressableContext = JSON.parse(window.atob(base64Context));
      console.log('addressableContext = '+JSON.stringify(addressableContext));
      component.set("v.recordId", addressableContext.attributes.recordId);
      },



      Delete
    3. Hi sfdcdev, are you receiving any error ? Could you please check console once ? There must be some logs as in above code.

      Delete
  11. i referred the below link:
    https://sfdclesson.com/2019/11/23/get-parent-record-id-from-lightning-url/

    ReplyDelete
  12. yes i am getting error in mobile device
    uncaught Action failed:c: compname $init[cannot read property ' startwith' of undefined]callbackfailed:aura://componentcontroller/ACTION$getComponent

    ReplyDelete
    Replies
    1. Hi sfdcdev : as per above error I think you are using subString and the starting index is not available in that. To trace the error you could print console after each line in your doInit function and track the line number of error.
      Let me know if that helps !

      Delete
  13. Very thanks for your response

    ReplyDelete
  14. Hi, this code is working fine in desktop version but when i try to create a opportunity record from account's related list page in mobile app there is a component error "Uncaught Action failed: c:newOppMobile$controller$doInit [Unexpected token ž in JSON at position 0] ".

    So, kindly help me to resolve this issue.

    ReplyDelete
    Replies
    1. Hi, salesforce has stopped the mobile browser version from it's last release. The code was meant to be run on mobile browser version & Salesforce1 app as well. But now due to mobile version is not available we can not debug the logs.

      Delete
  15. Thanks for your response can u suggest me any other way to achieve this.

    ReplyDelete