Custom Record Type Selection Lightning Component with force:createRecord event

Custom Record Type Selection Lightning Component with force:createRecord event

Lightning Component

Hi Guys,

If you are thorough with lightning, you must have come across with force:createRecord event. NO? Don’t worry. We will discuss it here. 🙂

When you click on New button on any sObject [custom or standard] entity, It opens up a box (standard component) to create a record. If you want to leverage the same functionality in our custom components, you can use force:createRecord event.

Syntax of force:createRecord event:
var createRecordEvent = $A.get("e.force:createRecord");
	createRecordEvent.setParams({
	"entityApiName": "Account",  // sObject API Name [Required Parameter]
	"recordTypeId": "1234455566" // Optionally Specify Record Type Id
	});
	createRecordEvent.fire();
How to use force:createRecord ?

sample component:

Open the Developer Console, Create a new lightning component with below code:

Lightning Component Code:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    <lightning:button label="Create a contact" onclick="{!c.createRecord}" />
</aura:component>

Controller:

({
   createRecord: function(component, event, helper) {
      var createRecordEvent = $A.get("e.force:createRecord");
      createRecordEvent.setParams({
         "entityApiName": "Account" // using account standard object for this sample
      });
      createRecordEvent.fire();
   }
})

This force:createRecord event is handled by the one.app container. It’s supported in Lightning Experience and Salesforce1 only. This event presents a standard page to create a record.

That’s it. This is the easiest way of creating a record in custom components on the fly. Because we do not have to waste time to build the component for form.
This concept is quite similar to standard lightning functionality. Salesforce has provided an ability of using it in our custom component. We fire a force:createRecord event using the above syntax and this event will be handled by one.app container then it calls standard component form to create a record.

What if your object has multiple record types ?
How to Make Custom Record Type Selection Available for Users in Custom Components With force:createRecord ?

For do that we need to do 3 thing in our lightning component :
1. Get the all available Record Types for that object.
2. Make them available as a list for selection on component.
3. Pass the selected recordTypeId as second parameter to force:createRecord.

That’ it.

The following example explains how to do this.

Custom Record Type Selection Lightning Component with force:createRecord event
Output:

Apex Controller [server side] : 

public class recordtypeController {
    public static Map<Id, String> recordtypemap {get;set;}
    
   @AuraEnabled        
    public static List<String> fetchRecordTypeValues(){
        List<Schema.RecordTypeInfo> recordtypes = Account.SObjectType.getDescribe().getRecordTypeInfos();    
        recordtypemap = new Map<Id, String>();
        for(RecordTypeInfo rt : recordtypes){
            if(rt.getName() != 'Master')
            recordtypemap.put(rt.getRecordTypeId(), rt.getName());
        }        
        return recordtypemap.values();
    }
    
    @AuraEnabled
    public static Id getRecTypeId(String recordTypeLabel){
        Id recid = Schema.SObjectType.Account.getRecordTypeInfosByName().get(recordTypeLabel).getRecordTypeId();        
        return recid;
    }      
}

Note: There are some other ways of doing the same like getting the map of record type and Id and using it in the component. In this case we can avoid another server call. This post just to give an idea how you can do this.

Lightning Component :

<aura:component controller="recordtypeController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global">
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchListOfRecordTypes}"/>
    
    <aura:attribute name="lstOfRecordType" type="String[]" />
    <aura:attribute name="isOpen" type="boolean" default="false" />
 
  <div class="slds-m-around--x-large">
    <lightning:button label="Create a contact" onclick="{!c.openModal}" />
  </div>    
   <!-- Model Box Start -->    
    <aura:if isTrue="{!v.isOpen}">
        <div role="dialog" tabindex="-1" aria-labelledby="header43" class="slds-modal slds-fade-in-open">
            <div class="slds-modal__container">
                <div class="slds-modal__header">
                    <button class="slds-button slds-modal__close slds-button--icon-inverse" title="Close" onclick="{!c.closeModal}">
                        X<span class="slds-assistive-text">Cancel</span>
                    </button>
                    <h2 id="header43" class="slds-text-heading--medium">New Account</h2>
                </div>
                
                <div class="slds-modal__content slds-p-around--medium">
                    <div class="slds-grid slds-wrap">
                        <div class="slds-size--1-of-2 slds-large-size--1-of-2">
                             <div class="slds-align--absolute-center">Select a Record Type</div>                            
                        </div>
                        <div class="slds-size--1-of-2 slds-large-size--1-of-2">
                            <ui:inputSelect aura:id="selectid">
                                <aura:iteration items="{!v.lstOfRecordType}" var="contact">                            
                                    <ui:inputSelectOption text="{!contact}" label="{!contact}"  />
                                </aura:iteration>
                            </ui:inputSelect>
                        </div>&nbsp; &nbsp;
                    </div>                   
                </div>
                
                <div class="slds-modal__footer">
                    <lightning:button class="slds-button slds-button--neutral" onclick="{!c.closeModal}">Cancel</lightning:button>
                    <lightning:button class="slds-button slds-button--brand" onclick="{!c.createRecord}">Next</lightning:button>
                </div>
            </div>
        </div>
        <div class="slds-backdrop slds-backdrop--open"></div>
    </aura:if>
</aura:component>
Create Modal/Popup Box In Lightning Component – Salesforce

JavaScript Controller [client side]:

({

   /* On the component Load this function call the apex class method, 
    * which is return the list of RecordTypes of object 
    * and set it to the lstOfRecordType attribute to display record Type values
    * on ui:inputSelect component. */

   fetchListOfRecordTypes: function(component, event, helper) {
      var action = component.get("c.fetchRecordTypeValues");
      action.setCallback(this, function(response) {
         component.set("v.lstOfRecordType", response.getReturnValue());
      });
      $A.enqueueAction(action);
   },

   /* In this "createRecord" function, first we have call apex class method 
    * and pass the selected RecordType values[label] and this "getRecTypeId"
    * apex method return the selected recordType ID.
    * When RecordType ID comes, we have call  "e.force:createRecord"
    * event and pass object API Name and 
    * set the record type ID in recordTypeId parameter. and fire this event
    * if response state is not equal = "SUCCESS" then display message on various situations.
    */
   createRecord: function(component, event, helper) {
      component.set("v.isOpen", true);

      var action = component.get("c.getRecTypeId");
      var recordTypeLabel = component.find("selectid").get("v.value");
      action.setParams({
         "recordTypeLabel": recordTypeLabel
      });
      action.setCallback(this, function(response) {
         var state = response.getState();
         if (state === "SUCCESS") {
            var createRecordEvent = $A.get("e.force:createRecord");
            var RecTypeID  = response.getReturnValue();
            createRecordEvent.setParams({
               "entityApiName": 'Account',
               "recordTypeId": RecTypeID
            });
            createRecordEvent.fire();
             
         } else if (state == "INCOMPLETE") {
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
               "title": "Oops!",
               "message": "No Internet Connection"
            });
            toastEvent.fire();
             
         } else if (state == "ERROR") {
            var toastEvent = $A.get("e.force:showToast");
            toastEvent.setParams({
               "title": "Error!",
               "message": "Please contact your administrator"
            });
            toastEvent.fire();
         }
      });
      $A.enqueueAction(action);
   },

   closeModal: function(component, event, helper) {
      // set "isOpen" attribute to false for hide/close model box 
      component.set("v.isOpen", false);
   },

   openModal: function(component, event, helper) {
      // set "isOpen" attribute to true to show model box
      component.set("v.isOpen", true);
   },
})
  • See Code Comments.
Add Above Component In Lightning  Experience Tabs To See The Output:
  • From setup >> Enter “tabs” in Quick Find box and select Tabs.
  • In the Lightning Component Tabs selection click on the new button.

Custom Record Type Selection Lightning Component add component to tabs

  • Next, select your lightning component from drop-down, Enter tab label select tab style icon and click on the next button and click on the save.

Custom Record Type Selection Lightning Component create new lightning component tabs

Now you can access your lightning component from App Launcher.

Custom Record Type Selection Lightning Component with force:createRecord event

Output : 

Custom Record Type Selection Lightning Component with force:createRecord event

Seems to be quite a lot ? Actually not. We just played with the things we learnt in our earlier posts.

Please note, SLDS Modal is not compatible with S1 mobile.

Hope it helps. Happy coding.!

Useful Resources:

Like our facebook page for new post updates.? & Don’t forget to bookmark this site for your future reference. ?

if you have any suggestions or issue with it, you can post in comment box 🙂

About The contributor: 

33 comments

      • it worked for me but when i am first time selecting first record type it is throwing below error could you please help me thanks in advance

        Error!
        Please contact your administrator

    • I am changing this requirement to our requirement instead of account to case obj.
      “How to Make Custom Record Type Selection Available for Users in Custom Components With force:createRecord ?”
      As your requirement same as ours,but we did in case object i should get this error:

      This page has an error. You might just need to refresh it.
      Error in $A.getCallback() [Unable to get property ‘setParams’ of undefined or null reference]
      Callback failed: apex://HVHCRTIR_TicketCreationWithRecTypeCon/ACTION$getRecTypeId
      Failing descriptor: {markup://c:HVHCRTIR_TicketCreationWithRecTypeCom}

  • Hi Brahmaji,
    Do we have an event to handle “Successful Record Save” to perform any other custom actions.
    Event “force:recordSaveSuccess” is working for Component “force:recordEdit” but I could see no such component for creating record, I just found an event “force:createRecord”.

    • Hi Sriram,

      As per my knowledge, we do not have any such event supporting force:createRecord result. Also we cannot customize much in force:createRecord.

      Thanks
      Brahma

  • Trying to write a test class for the server side controller and having issues. Point me in the right direction?

  • Thanks for sharing such a great content. As winter 18 is rolled out and “e.force:createRecord” has stopped working in winter 18. Has anyone else also faced it.

  • Hi,

    thanks for the awesome tutorial – I did follow your example and tried to save the new object, but I get an error like that:

    ==> Record Type ID: this ID value isn’t valid for the user: 0129E0000000sYZQAY

    The ID is the one from the RecordType and I’ve no change to change it’s value (like shorten it, suggested on other websites while googling this topic). It still appears in full length and just disappears if I don’t set this value completely.

    In this case (without the ID) it also works with saving the item.

    Do you have any ideas for that?

    Thanks for your help!

    Best,

    Martin

    • Make sure that user has access to that record type. Go to profile of that user and verify access to that record type.

  • Hi,

    I am trying to create something like this. and i want to populate default values from another object here. e.g. i am adding this component as a quick action on my case record page and i want to pass some of case fields value in new form of my custom object. so how can we do that here?

     

    Thanks

    Neeru

  • Hi,

    great work. Could you please tell me how to hide save & new button which redirects the user back to standard record type selection page.

    Thanks,
    Nithin

  • Hi,

    Great Work !!!.

    Could you please tell me how to hide Save & New button which is redirecting user to back to standard record type selection page.

    Thanks,

    Nithin C.H

  • Great post, really helped out with showing how to create records within Lightning. I am bypassing the modal selection of the recordType and using the controller to get a recordType based on additional criteria. I made the component a quick action, take a record id of a project, and get a task record type id back and then run the createRecord method. Three questions:

    How can we add some values to the record after the createRecordEvent.fire() method, like RelatedTo
    Is it possible to keep user on the original page rather than go to the newly created record
    How can we close the pop-up from the forceRecord form if we hit cancel; image link

    Thanks again for the post!

  • Hi Bramaji,

    I have used above code for Leads Object and overridden standard ‘New’ button.

    Once I create a Lead I will be redirected to Lead Detail page.

    But the problem is when I retry to create a New Lead(by clicking on New button). I get a pre filled data of the Lead which I created previously. Ideally it should land to Record type selection page.

    Could you please suggest what can be done here.

  • May i know how to populate standard lookup field like account on contact page. I used above approach, everything is working fine except lookup field on standard lookup field not pre populating

  • Some how I am not able to save the record, I have implemented this for creating contact from department, all the required fields are pre populating after selection of record type, but when i click on save button, i get error:- please review error on this page, though no error found on the page. Please help.

  • Hi Brahmaji,

    Thank for the post, it is very helpful.

    Currently this is component is launching form custom lightning tab. But I have requirement like launch this functionality from quick action button. I tried by simply removing force:appHostable.

    Please help me how can we achieve this from quick action  button?

     

    Thank In Advance.

  • I tried this “Create Record” in my dev org and facing the below issue wrt controller:

    This page has an error. You might just need to refresh it. Action failed: c:myFirstLightComp$controller$createRecord [Cannot read property ‘setParams’ of undefined] Failing descriptor: {c:myFirstLightComp$controller$createRecord}

    Please help in resolving this error.

  • I am facing the  problem in handling ‘Save & New’ here. It redirects me to standard record type pagfe and that is not working when i click next after selecting record type. Any suggestions are most welcome !

  • I am also facing problem with save & new which takes me to standard record type selection page and tkaes to incorrect URL when user clicks ‘Next’ to proceed.

     

    /s/a00/e?retURL=%2Fsfsites%2Faura%3Fr%3D27%26ui-force-components-controllers-createRecordTypeChecker.CreateRecordTypeChecker.doRecordTypeCheck%3D1&_CONFIRMATIONTOKEN=VmpFPSxNakF4T0Mwd09DMHhORlF3T0RveU5UbzBNUzQ1TURsYSw0aEZnQ1NnRUtSMWVyMkI3MC1JdXNjLFl6Z3pOR0l6&common.udd.actions.ActionsUtilORIG_URI=%2Fa00%2Fe&RecordType=012L00000000SBXIA2

    • Hi Kumaresan,

      I have the same issue.
      Found this solution, but expose a new problem, how to distinguish between Save & New vs Save and to only display this on Save & New. I’ve still yet to find a solution. With how this is written, both record type selection windows shows.

      createRecordEvent.setParams({
      “entityApiName”: ‘Library__c’,
      “defaultFieldValues”: sdefaultvalues,
      “recordTypeId”: recordTypeId,
      “panelOnDestroyCallback”: function(event) {
      //calling the function for the customized record types window modal
      var a = component.get(‘c.createNewLibraryRecord’);
      $A.enqueueAction(a);
      }
      });

  • Hi,

    The code is working but when I select a record type it says you dont have access too that record type But I do have, please help me.

    Thanks

     

  • While using this for my custom object, it says
    Looks like there’s a problem.
    INVALID_TYPE: record type 012C0000000Bm5y doesn’t belong to Organization

  • I am trying the same and it works fine and the modal shows correct fields based on report type but the modal header is not dynamic. Could you please help on how to achieve that?

Leave a Reply