web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Custom button on Command Bar

(0) ShareShare
ReportReport
Posted on by 5

Hello,

Working with online Dynamics 365.

I am working on my first attempt to add a button to a command bar.  The ultimate goal is to put a button on a form of a custom entity.  When the button is pressed, I will open up a new window with a new related entity (a Lead for example), with some of the data fields pre-filled (from the originating entity record).

I have successfully added the button to the form using the Ribbon Workbench tool.

Now I need run some code from it to open the new window.  There seems to be a *lot* of ways to accomplish this.  I am not sure which method is easiest?

I saw a reference to Xrm.Utility.openEntityForm.  That seemed to have exactly what I needed, but appeared that it need to be wrapped in some Javascript code?

If that is the case, where do I store the js code?  In Webresources?  If so, how to I create a command in Ribbon Workbench to call it?

Or, is it possible to call that method directly from a Ribbon Workbench command without any Javascript?

Thanks for any guidance that you can give.

Bryan Hunt

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hello,

    Yes, you store your javascript code in a WebResource. You can create a .js file on your local machine and put the code in it you need to call, wrapped in a function with a name of your choosing, and upload it under 'Customization' for example: 

    function MyButtonAction()
    {
      // Your code here
    }


    In the Ribbon Workbench you create a Command, which contains a Javascript action.

    In your JavaScript action, pick the WebResource you uploaded and then type the name of your function: "MyButtonAction"

    Then attach the Command to the Button.

      

    Be sure to check out this great article by community champ Aric Levin:
    https://community.dynamics.com/crm/b/briteglobalsolutions/archive/2017/10/22/creating-a-ribbon-button-using-ribbon-workbench-to-call-a-javascript-action 

      

    Hope this helps you get started. If you have any other questions, please let me know! :-)

  • ccnwo Profile Picture
    5 on at

    Michel,

    Thanks for the response.

    To upload, Settings/Customize the System/Web Resources?  Is that the correct place?

    There is no option there to upload?

    Thanks.

    Bryan Hunt

  • Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Hi brhunt,

    That is the right location.

    There is no upload button. You need to use the New button.

    There you will specify the name and display name of the Web Resource, the type, and browser to the location of the physical file to upload it as a web resource.

    Hope this helps.

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi ,

    You are right , here is the step what you need to do.

    1) Create an JavaScript WebResource.

    2) Add a function in the Javascript file like below

    function CallRibbonOpenEntityForm()
    {
       //Get lookup value from Form to open the entity form
        var leadid = Xrm.Page.data.entity.attributes.get("new_leadlookup").getValue()[0].id;
        var windowOptions = {
            openInNewWindow: true
        };
       //Pass paramenter
        var parameters = {};
        parameters["leadid"] = leadid;    //Pass primary key of the enity to open with prepopulated data 
        parameters["formid"] = "0dce1685-3735-4618-90ab-c91f7347798a"; //You can pass form id which you want to display 
    	
        Xrm.Utility.openEntityForm("lead", null, parameters, windowOptions);
        
    }

    2) Create a test solution add the JavaScript file and  the entity where you want to display the button.

    3) Go to  Ribbon Workbench and select the solution.

    4) Create New button in the Entity where you need the button.

    5) If button in the form then you should have some field of lead ID where you get the GUID to open entity form.

    6) Pass the GUID of lead in the in the OpenEnityForm method.

    Please note this is an example scenario I have provided.

    Hope this helps

  • Suggested answer
    Shahbaaz Ansari Profile Picture
    6,211 on at

    Step 1: Create a custom button on Account using ribbon workbench and call javascript from that

    Link for creating and calling javascript is below : mahenderpal.wordpress.com/.../calling-java-script-on-click-of-command-button-ms-crm-2015-step-by-step

    Step 2: Write javascript that will be called from button click which will open HTML page like below code :

    function OpenHTML() {

    if(Xrm.Page.data.entity.getEntityName()=="account")

    {

    var accoutid = Xrm.Page.getAttribute("new_axaccountid").getValue();

    if(accoutid)

    {

                            var customParameters = encodeURIComponent("AccountId="+accoutid);

    Xrm.Utility.openWebResource("new_GetInvoice", customParameters);

    }

    else

    {

    alert("Record not found !!!!!!")

    }

    }

    }  

    Hope this helps,

    Shahbaaz

  • ccnwo Profile Picture
    5 on at

    Wow, all answers extremely helpful, thanks.

    I was able to get the command bar button to open up a new Lead from and populate the first name, last name, full name and subject fields.

    I have one last field that I need to populate, and I am struggling to get the correct syntax.

    The form that the button is on is a custom entity called Project Report.  The entity name (with prefix) is new_project_report.  

    The Lead entity has a lookup field in it that relates to Project Reports.

    My new Lead needs to have that lookup field set to point to the Project Report on screen when the button is pressed.

    I am trying to get the record id of the current project report.  I have tried a myriad of permutations to get the id, including these variations:

    var prid = Xrm.Page.getAttribute("new_projectreport").getValue();
    var prid = Xrm.Page.getAttribute("new_project_report").getValue()[0].id;
    var prid = Xrm.Page.data.entity.attributes.get("new_project_report").getValue()[0].id;

    I can't seem to find the correct command syntax.  Can anyone help here?

    This spawns a second question as well:  When my javascript fails, basically nothing happens.  No errors are visible, my new Lead window simply doesn't appear.  How can I see any error messages about why my javascript has failed?

    Thanks again for all of your help.

    Bryan Hunt

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hello,

    Any error messages in your JavaScript would show up in the development console. Press F12 in your browser to show it.

    Your most recent example features multiple field names, please make sure you are using the field name as it is created in the Customization area.

      

    You are in the right direction, you use Xrm.Page.getAttribute(...) to retrieve the attribute from the form

    You can call getValue(...) on an attribute to get it's value.

    And a lookup will return an array, so you need to apply [0] to it to get the first item

    Each entry in the lookup array contains a property named 'id'

      

    On an Entity Form, to read the ID value from a record selected in a lookup field named "new_projectreport" you can try this code:

    var projectReportId = null,
         projectReportLookupValue = Xrm.Page.getAttribute("new_projectreport").getValue();
    
    // Check if the field is not empty
    // Check if the field contains a not empty array by checking it's length
    if (projectReportLookupValue && projectReportLookupValue.length)
    { // Read the ID from the first item in the array projectReportId = projectReportLookupValue[0].id; // TODO: Add your logic here, and read projectReportId // Example: var customParameters = encodeURIComponent("ProjectReportId="+projectReportId); Xrm.Utility.openWebResource("new_WebResourcePage", customParameters);
    }
  • ccnwo Profile Picture
    5 on at

    Michel,

    Thanks for the reply.  I think that I need something slightly different.

    The process is this:  

    - I am on the form screen of a Project Report.

    - I want to create a new Lead record that is linked to the Project Report I am looking at.  This is done via the new button I have created.

    I have picked up first name, last name, full name and project-report-title, and have been able to get those fields to transfer to the new Lead.

    What I need to do is get the record id of the Project Report I am currently viewing in the form.  That will be another field to transfer to the new Lead record.

    Thanks.

    Bryan Hunt

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at

    Hello,

    To get the ID of the current record, use this:

    var projectReportId = Xrm.Page.data.entity.getId()

      
    Based on the scenario you described, I think you are looking for a script like this. It reads some details from the current entity, the creates a Lead and opens it.

    function OnClickOfRibbonButton() {
    
        // Gets primary id of Form we are currently on and quickly remove the brackets
        var projectReportId = Xrm.Page.data.entity.getId().replace('{','').replace('}', '');
    
        // Read values from fields you need from the Form
        var firstName = Xrm.Page.getAttribute("new_firstname").getValue(),
            lastName = Xrm.Page.getAttribute("new_lastname").getValue(),
            projectTitle = Xrm.Page.getAttribute("new_projecttitle").getValue()
    
        // Call createRecord to create a lead
        Xrm.WebApi.createRecord('lead', {
            // pass the record details
            'firstname': firstName,
            'lastname': lastName,
            'topic': projectTitle,
            // On the Lead form if your field is called 'new_projectreportfield' and your entity is called 'new_projectreport':
            'new_projectreportfield@odata.bind': '/new_projectreports(' + projectReportId + ')' // Note that the entity name has to be plural here
        }).then(function (result) {
            // Opening it after creation:
            Xrm.Navigation.openForm({
                'entityName': 'lead',
                'entityId': result.id,
                'openInNewWindow': true
            });
            }, function (error) {
                console.log(error.message);// handle error
            }
         );
    }

      

    Alternatively, if you're looking for a no-script solution, perhaps you can take a look at entity mappings. This allows you to automatically take data from one entity to another when a new one is created. This is for example how the system copies Opportunity details to Quote when you create a Quote, or how it copies the Account address when you create a Contact from the Account Form.

    https://docs.microsoft.com/en-us/dynamics365/customer-engagement/customize/map-entity-fields 

  • ccnwo Profile Picture
    5 on at

    Michel,

    Beautiful.  Thanks for that information.

    I would like, if possible, to open a new Lead form with fields populated without having first saved the Lead.  That would give the user the options to cancel before creating the Lead.

    That was working for me before I tried to add the link to Project Report.

    Here is what I am trying now:

    var windowOptions =

     {

       openInNewWindow: true

     };

      var parameters = {};

      parameters["subject"] = title;

      parameters["firstname"] = "CC";

      parameters["lastname"] = "Project";

      parameters["fullname"] = "CC Project";

      parameters["new_projectreportfield@odata.bind"] = "/new_projectreports(" + prid + ")";

       Xrm.Utility.openEntityForm("lead", null, parameters, windowOptions);

    It starts to open the Lead form, but then throws an error.

    Is it possible to pass that linkage as a parameter?

    Thanks.

    Bryan Hunt

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > 🔒一 Microsoft Dynamics CRM (Archived)

#1
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans