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

ReactJs CSS - This file type requires a specific loader for processing. There are currently no loaders configured to handle this file

I've noticed that this issue has been raised multiple times before. Despite going through all the questions, I still can't seem to resolve it. The transition from Typescript to Javascript went smoothly until I reached the implementation of CSS. U ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

Having trouble with moving the svg:svg element?

I'm struggling to move an svg element that is nested within another svg. I am trying to directly manipulate the x and y values, but I keep encountering a "read-only" error. I attempted to use transform instead, but it doesn't seem to have any eff ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

I'm unsure of my recollection on how to utilize the /* syntax in JavaScript

Hey there, I'm facing a little issue. Can someone remind me how to correctly use the /* in JavaScript when dealing with URLs? For instance: if(URL == "www.thing.com/"){} I can't quite remember where to insert the /* so that it applies not just ...

Divide JSON information into distinct pieces utilizing JQuery

$.ajax({ type: 'POST', url: 'url', data: val, async: false, dataType: 'json', success: function (max) { console.log(max.origin); } ...

Occasionally, the view fails to update following an $http request

Although this question has been posed multiple times before, none of the solutions seem to be effective for my issue. Controller app.controller('HomeController', function ($scope, $timeout, $http) { $scope.eventData = { heading: ...

The MUI Autocomplete filterOptions is not effectively filtering out all options as expected

Hey there! I'm facing an unusual situation with my Autocomplete feature, which has been heavily customized to meet certain restrictions and requirements. The issue I am encountering is related to filtering. Despite successfully filtering the results ...

Struggling with determining the perfect transition speed for the sidemenu display

I'm a newcomer to web development and facing an issue with setting the transition speed for opening and closing this side menu. Despite adding transitions in the CSS and specifying duration in the Javascript, the menu continues to open instantly. I di ...

What is the best method for binding variables in Vue.JS using moustache syntax and passing parameters to them?

If I have an HTML structure like this: <div> {{ CUSTOM_MESSAGE }} </div> And in my data: data() { return { CUSTOM_MESSAGE: 'Hey there! This message is for {{name}} from {{location}}' } } Is there a way to dynamically p ...

Different ways to conditionally set the expanded prop for the Material UI TreeView component

I am currently working on implementing a tree select feature similar to the one found in antd's tree-select using material ui components. Specifically, I have a TextField and TreeView components from Material-UI stacked vertically. Initially, I want t ...

Show the Vue.js template in a Laravel Blade view

I have been struggling to integrate a Vue.js component into a Laravel blade file. Despite researching tutorials and Stack Overflow solutions, I have not been able to resolve the issue. Below is the template that I want to display: <template> < ...

jQuery animation not executing as expected due to transition issues

I'm looking to create a cool effect where the previous quote disappears and a new one appears when I click on a button, all with a smooth transition effect. In my attempt below using jQuery .animate and opacity property, I'm struggling to make i ...

Displaying an image with a JavaScript variable is a common task in web

I have a Javascript code snippet below where the image name "samson decosta" is stored in a MySQL database. I am retrieving this image and trying to display it as a background_image in a div. document.getElementById("image_chk").style.backgroundImage="url ...

conceal a division beneath a YouTube video frame upon clicking

I need to hide the 'div .blind' element when a YouTube video (inside 'div #player') is clicked. How can I achieve this? Here's an example: JS: ... var player; function onYouTubeIframeAPIReady() { player = new YT.Player('pl ...

The node module.exports in promise function may result in an undefined return value

When attempting to log the Promise in routes.js, it returns as undefined. However, if logged in queries.js, it works fine. What changes should be made to the promise in order to properly return a response to routes.js? In queries.js: const rsClient = req ...

What is the best approach to transforming my jQuery function into CSS to ensure responsiveness?

I have created a jQuery animation with four functions named ani1(), ani2(), ani3(), and ani4(). Everything is working fine on desktop, but now I am facing the challenge of making it responsive for mobile devices. I am looking for CSS code to replicate the ...

Show the time in hours and minutes (00:00) while rounding off seconds to the nearest minute

I need the time to always display with leading zeros when less than 10. For example, if a task took 3 hours, 7 minutes, and 33 seconds, it should be shown as 03:08. Currently, I have the buttons disabled after they are clicked to prevent restarting the ti ...

Converting HTML tables into arrays

I have JSON content that needs to be transformed into an array, specifically from a HTML table with cell values. Those cells should be combined into a single array for further use in the project. Struggling with the conversion of cell values into an arra ...

Sending a variable to a VueJS component

I'm looking to pass a variable down to a component in my current setup. Here's the structure: Main: Meet.vue <html> <div class="carousel-cell"> <Category :searchTerm="woman"></Category> </div> <div cla ...