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

  • ccnwo Profile Picture
    5 on at
    RE: Custom button on Command Bar

    Thanks to all that replied.  I was able to finally resolve the exact syntax that I needed for the final field.

    I had forgotten to mark this thread as complete/answered.

  • Suggested answer
    Vipin J Profile Picture
    1,583 on at
    RE: Custom button on Command Bar

    Here is a short article to create a custom button and call a JavaScript method.

    https://vjcity.blogspot.com/2019/06/how-to-create-custom-button-in-dynamic.html

  • Community Member Profile Picture
    on at
    RE: Custom button on Command Bar

    AA...Try these out:

    www.youtube.com/watch

    neilparkhurst.com/.../adding-buttons-to-ribbons

  • Michel van den Brink Profile Picture
    4,697 on at
    RE: Custom button on Command Bar

    Hello Bryan,

    Because we've had a few back and forths and you mentioned different field names, can you please double-check what the exact field name is of your Lookup to the Project Report entity, on the Lead entity?

    It is important that you specify the exact field name when passing parameters.

  • ccnwo Profile Picture
    5 on at
    RE: Custom button on Command Bar

    Michel,

    Again, thanks for all of the assistance.

    I can get the lead form to open perfectly as long as I do not reference the lookup field.  If I do, the form starts open, then displays an error dialog box.

    I tried using the line that you provided: parameters["new_projectreportfield"] = prid;

    I also tried the following based on other posts that I have seen:

    parameters["new_projectreportId"] = projectID;

    parameters["new_projectreportType"] = Xrm.Page.data.entity.getEntityName();

    parameters["new_projectreportName"] = title;

    It gives me this error information:

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #3D49D6D6Detail:

    <OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance&quot; xmlns="schemas.microsoft.com/.../Contracts&quot;>

     <ActivityId>b03fb714-4194-45a3-9368-b2c85a98da45</ActivityId>

     <ErrorCode>-2147220970</ErrorCode>

     <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic&quot; />

     <Message>System.Web.HttpUnhandledException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #3D49D6D6</Message>

     <Timestamp>2018-03-18T19:29:30.2484864Z</Timestamp>

     <ExceptionRetriable>false</ExceptionRetriable>

     <ExceptionSource i:nil="true" />

     <InnerFault>

       <ActivityId>b03fb714-4194-45a3-9368-b2c85a98da45</ActivityId>

       <ErrorCode>-2147220970</ErrorCode>

       <ErrorDetails xmlns:d3p1="schemas.datacontract.org/.../System.Collections.Generic&quot; />

       <Message>System.InvalidOperationException: Microsoft Dynamics CRM has experienced an error. Reference number for administrators or support: #3BAA3123</Message>

       <Timestamp>2018-03-18T19:29:30.2484864Z</Timestamp>

       <ExceptionRetriable>false</ExceptionRetriable>

       <ExceptionSource i:nil="true" />

       <InnerFault i:nil="true" />

       <OriginalException i:nil="true" />

       <TraceText i:nil="true" />

     </InnerFault>

     <OriginalException i:nil="true" />

     <TraceText i:nil="true" />

    </OrganizationServiceFault>

    What else can I try here?

    Thanks.

    Bryan Hunt

  • Verified answer
    Michel van den Brink Profile Picture
    4,697 on at
    RE: Custom button on Command Bar

    Hello Bryan,

    Yes, opening the lead form with  Xrm.Utility.openEntityForm is an option.

    For this though, the way you pass a lookup value is a little different:

    var windowOptions =
        {
            openInNewWindow: true
        };
    var parameters = {};
    parameters["subject"] = title;
    parameters["firstname"] = "CC";
    parameters["lastname"] = "Project";
    parameters["fullname"] = "CC Project";
    parameters["new_projectreportfield"] = prid;
    
    Xrm.Utility.openEntityForm("lead", null, parameters, windowOptions);


    Make sure ALL fields you pass as parameters exist on your Lead form, with exactly those names you enter, otherwise the system will continue to give you an error.

  • ccnwo Profile Picture
    5 on at
    RE: Custom button on Command Bar

    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

  • Suggested answer
    Michel van den Brink Profile Picture
    4,697 on at
    RE: Custom button on Command Bar

    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
    RE: Custom button on Command Bar

    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
    RE: Custom button on Command Bar

    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);
    }

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

Daivat Vartak – Community Spotlight

We are honored to recognize Daivat Vartak as our March 2025 Community…

Announcing Our 2025 Season 1 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Kudos to the February Top 10 Community Stars!

Thanks for all your good work in the Community!

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 293,001 Super User 2025 Season 1

#2
Martin Dráb Profile Picture

Martin Dráb 231,837 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156 Moderator

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans