When invoking Javascript, its behavior may vary depending on whether it is being called from a custom

Currently, I am in the process of implementing versioning capabilities to a custom entity called MFAs. However, I have encountered a peculiar issue. The problem arises from having a JavaScript web resource that is being invoked from two different locations: an onSave event on the form and as the action of a custom ribbon button. More specifically, the onSave event triggers the captureSave function, while the ribbon button triggers the makeARevision function.

When triggered by the save button/event, everything functions as expected; all data, including new changes, are transferred to a new record and saved there. Simultaneously, the original record is closed without saving any changes, and no prompt for saving appears. On the other hand, when activated via the custom ribbon button, any unsaved modifications do not get carried over to the new record, and the old record prompts for saving. Even if the user opts to save the alterations to the old record, the changes do not persist, and the form does not automatically close.

The JavaScript code below represents the web resource in question. company_MFASaveOrRevise is simply an HTML page that requests the user whether they wish to save the record or create a new revision. Any insights into what might be causing these discrepancies or how to address them would be greatly appreciated.

function captureSave(executionContext) {
    if (Xrm.Page.ui.getFormType() != 1 && Xrm.Page.data.entity.getIsDirty()) {
        var retVal = showModalDialog(Xrm.Page.context.getServerUrl() + '/Webresources/company_MFASaveOrRevise', null, 'dialogWidth: 300px; dialogHeight: 100px');
        if (retVal == "Revise") {
            executionContext.getEventArgs().preventDefault();
            makeARevision();
        }
        else if (retVal == "Save") {
        }
    }
}

function createLookupValue(oldLookup) {
    var lookupVal = new Object();
    lookupVal.Id = oldLookup.id;
    lookupVal.LogicalName = oldLookup.entityName;
    lookupVal.Name = oldLookup.Name;
    return lookupVal;
}

function makeARevision() {
    var revisedMFA = {};
    revisedMFA['company_mfaname'] = Xrm.Page.data.entity.attributes.get('company_mfaname').getValue();
    revisedMFA['company_mfadate'] = Xrm.Page.data.entity.attributes.get('company_mfadate').getValue();
    revisedMFA['company_estimatedliqdate'] = Xrm.Page.data.entity.attributes.get('company_estimatedliqdate').getValue();
    revisedMFA['company_actualliqdate'] = Xrm.Page.data.entity.attributes.get('company_actualliqdate').getValue();
    revisedMFA['company_mfanumber'] = Xrm.Page.data.entity.attributes.get('company_mfanumber').getValue();
    revisedMFA['company_revisionno'] = Xrm.Page.data.entity.attributes.get('company_revisionno') == null ? 0 : Xrm.Page.data.entity.attributes.get('company_revisionno').getValue() + 1;
    revisedMFA['company_requester'] = createLookupValue(Xrm.Page.data.entity.attributes.get('company_requester').getValue()[0]);
    revisedMFA['company_mfapreviousrev'] = Xrm.Page.data.entity.attributes.get('company_totalmfatodate').getValue();
    revisedMFA['company_contract'] = createLookupValue(Xrm.Page.data.entity.attributes.get('company_contract').getValue()[0]);

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        datatype: 'json',
        url: getODataUrl() + '/' + 'company_mfaSet',
        data: JSON.stringify(revisedMFA),
        beforeSend: function (XMLHttpRequest) {
            XMLHttpRequest.setRequestHeader('Accept', 'application/json');
        },
        success: function (data, textStatus, request) {
            Xrm.Utility.openEntityForm("company_mfa", data.d.company_mfaId.toUpperCase());
            var attributes = Xrm.Page.data.entity.attributes.get();
            for (var i in attributes) {
                attributes[i].setSubmitMode('never');
            }
            Xrm.Page.ui.close();
        },
        error: function (request, textStatus, errorThrown) {
            alert(errorThrown);
        }
    });
}

Edit: After inserting 'debugger;' in various places and utilizing VS2012 debugger, it was discovered that the attributes were being correctly set to not submit. Despite this, the confirmation dialog continued to appear (even though it worked with the save button). Additionally, when calling Xrm.Page.data.entity.attributes.get(attributeName), it retrieves post-change values during onSave events but pre-change values when triggered from the ribbon. The reason behind this discrepancy remains unknown. Is there any other aspect I should investigate?

Answer №1

When working with code called from the ribbon, remember to utilize F12 for debugging purposes. Keep in mind that your javascript code will be contained within a dynamic script or script block due to its placement in the ribbon.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The tooltip function is not functioning properly on Internet Explorer when the button is disabled

I have been utilizing a similar solution found at http://jsfiddle.net/cSSUA/209/ to add tooltips to disabled buttons. However, I am encountering an issue specifically in Internet Explorer (IE11). The workaround involves wrapping the button within a span: ...

Implementing a watcher property in JavaScript to dynamically add a class to an element

I'm currently facing an issue where I need to apply a class to an element when a certain data property changes. My approach involves using a watcher to monitor the value change and adding a class through JavaScript, as demonstrated in the code snippet ...

Implementing optimistic updates with React-query mutations

Hello everyone! I'm a newcomer to react-query and I've been experimenting with making an optimistic update using the mutation function. However, I've encountered a problem where I'm unable to retrieve the previous value from the query. ...

Securing JSON-based RESTful services

I am in the process of developing a web application, where I have established a clear separation between my "frontend" server using Lighttpd to serve index.html and javascript. My frontend, powered by Backbone.js, is connected to my Node.js backend webser ...

Transfer the data in the columns of Sheet1 to Sheet2 and eliminate any duplicates using Google App Script

Is there a way to transfer only unique rows from a SOURCE Spreadsheet to a DESTINATION spreadsheet? Spreadsheet #1 (SOURCE) - This sheet contains ID's and Names, but has duplicate rows. There are over 500k rows in this sheet and it is view-only. Spre ...

How can I conceal the element that came before in JavaScript?

<div onclick="toggleContent(this)" class="iptv"><div class="triangle"></div><b>LUZ HD</b> - 98 channels (including 32 HD channels) <div class="iptv_price"><b><img src="img/rj45.png" class="icon_ofert ...

invoke a function upon successful completion of an ajax call in a datatable

Can we trigger a JavaScript function after a successful AJAX call in a datatable? Here is the code I am attempting to use: var dataTable = $('#app-config').dataTable( { "bAutoWidth": false, ...

HTML Elements for Displaying Undefined JSON Information

Hey there, I'm new to programming and I'm looking to display JSON data in an HTML table using jQuery. The issue I'm facing is that the output from the server shows up as 'undefined'. My goal is to have a constantly updated list of ...

How can jQuery help me load a lengthy webpage with various backgrounds that change according to the vertical scroll value?

I have been given a design that is 960px wide and approximately 7000px tall, divided into five segments stacked vertically at random points. There is a fixed sidebar that scrolls to each segment when a navigation link is clicked. The layout includes slider ...

Creating an interactive dropdown menu in React JS on click

My goal is to display a select tag when a text or div element is clicked. I'm unsure of the correct method and location to render it. Therefore, I decided to create a handler function that sets a variable, isItClick, to true in order to show the sele ...

Advantages of choosing between the <NextLink/> and the <Button href="/somePage"/> components in the powerful Mui React UI libraries

Currently engaged in a project, I am wondering if there exists a substantial disparity in the utilization of these two components. Prior to this change, the return button was implemented as follows: <NextLink href="/settings" ...

What are the signs that an element was visible on screen prior to navigation?

Recently, I incorporated SlideUp and SlideDown jquery animations into my website. You can check it out by visiting (click the >>>). However, I noticed a small issue where when users navigate to a new page, they have to re-SlideUp the element that was sl ...

Access a webpage whose URL has been dynamically assigned using JavaScript

I have a website that consists of a single page and features four tabs. Whenever a tab is clicked, it displays the corresponding content in a div while hiding the other three divs along with their respective content. To ensure a smooth user experience, I u ...

Determining when all promises have either been rejected or resolved using vanilla JavaScript promises

In an effort to transition to loading all resources in my web application asynchronously using basic JS promises, I have implemented a ScriptLoader function. Below is the code snippet for the ScriptLoader used to load .js files: function ScriptLoader() { ...

Discover the steps to retrieve a fresh array in PHP after utilizing sortable.js

Hi there! I am currently utilizing the sortable javascript feature found on Although the script is working perfectly fine for me, being a non-expert in javascript poses a challenge when it comes to generating the necessary code to retrieve an array in php ...

Discovering the Javascript Code Executing on a <span> element with the Help of Chrome Inspector or Firebug

I have encountered a situation where a website is dynamically generating information into <span></span> tags using jQuery. The span has a class of "Price" and an id corresponding to a Product Code, with the data being pulled from a JSON data sh ...

Tips for incorporating a Forgot/Reset password option into your #Firebase platform

In the project I'm working on, I am utilizing #AngularFire2. My goal is to incorporate a Reset / Forgot password link into the login page. Does anyone have suggestions on how to accomplish this task? I'm looking to get some insights from #AskFi ...

What is the process for transferring ng-model values to a table in Angular?

My goal is to populate a table with JSON data using ng-repeat by clicking a button. I need to input either a first name or last name in order to display the results in the table. Is this the correct JavaScript function for achieving this? JavaScript Funct ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

Ways to showcase INPUT TYPE when making a Selection?

I've been struggling with a simple issue and despite trying multiple solutions, I can't seem to get it right. I have a form where I'm using the <select> tag with two options: coo and uh. What I want is for an additional input type fiel ...