How to Access Parameters in New Form - dynamics-crm

I have a custom button that I have the below JavaScript attached to that opens an entity form and I am trying to pass viewName to it.
function sendContextToQC(selectedControl) {
var entityFormOptions = {};
entityFormOptions["entityName"] = "new_qrecipemasteritem";
entityFormOptions["useQuickCreateForm"] = true;
var currentView = selectedControl.getViewSelector().getCurrentView().name;
var formParameters = {};
formParameters["viewName"] = currentView
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});
}
The form opens fine and I have the "Pass Execution Context as first parameter" checked, but I don't know how to access the formparameters object. Is it part of the executionContext? I even tried adding another parameter (formParameters), but that didn't work either.
2/14/23

You can access the form parameters from within the form by using the getFormContext() method. Here's an updated version of your code that shows how to access the formParameters object from within the form:
function sendContextToQC(selectedControl) {
var entityFormOptions = {};
entityFormOptions["entityName"] = "new_qrecipemasteritem";
entityFormOptions["useQuickCreateForm"] = true;
var currentView = selectedControl.getViewSelector().getCurrentView().name;
var formParameters = {};
formParameters["viewName"] = currentView;
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
var formContext = success.getFormContext();
var viewName = formContext.getAttribute("viewName").getValue();
console.log("View Name: " + viewName);
},
function (error) {
console.log(error);
});
}
In the success callback of the openForm method, you use getFormContext() to get a reference to the form context, and then use that reference to access the viewName attribute. You can then use the getValue() method on the attribute to retrieve its value.

In function Xrm.Navigation.openForm argument formParameters is an object holding field values. The function passes these values to the fields that are (should be) on the form opened by it.
It is possible to pass custom query string parameters to the form. These parameters can be retrieved accessing the window.location object.
See openForm - MS Learn and Configure a form to accept custom querystring parameters - MS Learn.
The (classic) Form Properties dialog has a Parameters tab where custom parameters can be declared. Custom parameters that have not been configured here can only be passed in a plain url by adding an extraqs parameter.

I figured it out. To send parameter:
function sendContextToQC(selectedControl) {
var entityFormOptions = {};
entityFormOptions["entityName"] = "new_qrecipemasteritem";
entityFormOptions["useQuickCreateForm"] = true;
var currentView = selectedControl.getViewSelector().getCurrentView().name;
var formParameters = {};
if (currentView.includes("Master") == true) {
formParameters["isMasterView"] = 1;
}
else {
formParameters["isMasterView"] = 0;
}
Xrm.Navigation.openForm(entityFormOptions, formParameters).then(
function (success) {
console.log(success);
},
function (error) {
console.log(error);
});
}
Then to pick it up onload:
this.hideUsedIn = function(executionContext) {
let formContext = executionContext.getFormContext();
let usedInAttribute = formContext.getAttribute("new_usedin");
let usedInControl = formContext.getControl("new_usedin");
let buttonData = {};
buttonData = Xrm.Utility.getPageContext().input.data;
let isMasterItem = buttonData.isMasterView;
if (isMasterItem === 1){
usedInAttribute.setRequiredLevel("none");
usedInControl.setVisible(false);
}
}

Related

multiple Async/await JS function

In my controller, the fn function executes return.suucess() before my variables are properly defined. In this case, the ytb object.
The sails.log of "items" is correct, but "ytb" did not return.
I also tried with Promise.then, and .all. Also, with async.each() and removing the await inside this function.
fn: async function (inputs, exits) {
var url = require('url');
var items = await Collection.find({});
_.each(items, async item => {
if (item.youtube_url) {
var ytbUrl = item.youtube_url;
var regexBaseUrlYtb = new RegExp('(https://www.youtube.com/channel/)');
if (regexBaseUrlYtb.test(ytbUrl)) {
var ytbIdChannel = ytbUrl.replace(regexBaseUrlYtb, '');
var ytbChannel = await sails.helpers.youtubeApi(ytbIdChannel);
item.ytb = {};
Object.assign(item.ytb, ytbChannel);
}
}
sails.log('items: ', item)
});
return exits.success({
items
});
}
I expect that the ytb object will also be passed with the object item at the view, but the items object is passed without the ytb object.
Also, in general, I expect the return exits.success() runs only once the function finished
Thanks.

Nativescript - Pass array from home-view-model to home.js

I´m having a hard time understanding how to perform this action(as the title says), and maybe someone could help me understand the process, my code is below:
My home-view-model:
var Observable = require("data/observable").Observable;
var ObservableArray = require("data/observable-array").ObservableArray;
var http = require("http");
function createViewModel() {
http.getJSON("http://myJsonfile").then(function (r) {
var arrNoticias = new ObservableArray(r.data);
return arrNoticias;
}, function (e) {
});
}
exports.createViewModel = createViewModel;
I have done a console.log of the arrNoticias before i have putted it inside a callback function and it returns [object object] etc...and then i have done this:
console.log(arrNoticias.getItem(0).titulo);
and it returns the info i need!.
Then in my home.js file i have this:
var observableModule = require("data/observable")
var ObservableArray = require("data/observable-array").ObservableArray;
var arrNoticias = require('./home-view-model.js');
console.log(arrNoticias.getItem(0).titulo);
and the result in the console is:
TypeError: arrNoticias.getItem is not a function. (In 'arrNoticias.getItem(0)', 'arrNoticias.getItem' is undefined)
My question is, how does this action is perform? passing the data from view-model to the .js file?
Thanks for your time
Regards
As that function send a URL request so probably it's an async function, which is on hold while requesting so that's why you get undefined. Normally, you will want your function that sends a URL request to return a promise. Based on that promise, you will the result as expected after the request is done. So:
function createViewModel() {
return new Promise<>((resolve, reject) => {
http.getJSON("http://myJsonfile").then(function (r) {
var arrNoticias = new ObservableArray(r.data);
resolve(arrNoticias);
}, function(e) {
reject(e);
});
}), (e) => {
console.log(e);
})
}
In home.js:
var homeVM= require('./home-view-model.js');
var arrNoticias;
homeVM.createViewModel().then(function(r) {
arrNoticias = r;
});

How can I pass values loaded by ajax to components?

I'm passing a value as a parameter to a component.
<badge-button params="badge: oarBadge"></badge-button>
Here is the viewModel containing oarBadge:
function AppViewModel() {
var self = this;
self.oarBadge = ko.observable();
$.getJSON('/guy.json', function(data) {
var badge = new Badge('wood oar', data.badges.oar, false);
self.oarBadge(badge);
// self.oarBadge().has() returns true so the badge is being properly created with data
// returned by the ajax call
});
} // AppViewModel()
Here is the Badge constructor:
function Badge(name, has, active) {
var self = this;
self.name = ko.observable(name);
self.has = ko.observable(has);
self.active = ko.observable(active);
self.disabled = ko.computed(function() {
return self.has();
});
self.toggleActive = function() {
self.active(!self.active())
};
self.toggleHas = function() {
self.has(!self.has());
};
}
Here is the component's viewModel:
ko.components.register('badge-button', {
viewModel: function(params) {
var self = this;
self.badge = params.badge();
self.open = function() {
self.badge.toggleHas();
self.badge.toggleActive();
}
},
template:
'<img class="ui image" src="http://fakeimg.pl/300/" data-bind="click: open, css: { disabled: badge.disabled }" >'
});
When the page loads, I get an error telling me that badge is undefined.
Full example: https://gist.github.com/guyjacks/5a8763ff71f90e3fe8b4b153ed9a5283
Try setting a default object before the ajax call is completed, also you should assign the observable itself not the evaluation for the observable, so instead of doing this:
self.badge = params.badge();
You should do it like this:
self.badge = params.badge;
Otherwise your variable won't be updated once the ajax request is completed.
Here is a small example: https://jsfiddle.net/b0bdru1u/1/
Note: As far as I know the disable binding won't work in images

Knockout JS - update viewModel with AJAX Call

there are some similar questions but didn't help me to solve my issue. I can't update my results on page / view after updating my viewModel with AJAX. I am getting valid AJAX response that updates the view if I reload the page, but not when I click btnAdvancedSearch
I have simple HTML:
<div>
<input type="button" id="btnAdvancedSearch" data-bind="click: refresh" />
</div>
<div id="resultslist1" data-bind="template: { name: 'rest-template', foreach: restaurants }">
</div>
And I bind in on document load:
$(document).ready(function () {
ko.applyBindings(new RestaurantsListViewModel());
});
My viewModel is like this, and in it I call refresh that is bound with button
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests;
self.refresh = function () {
updateRestaurantsList(); //Method executes AJAX and saves result to session.
var mappedRests2 = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants= mappedRests2;
}
}
What am I missing here?
Thanks
I have tried waiting for AJAX to finish like this:
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests;
self.refresh = function () {
var latitude = sessionStorage.getItem('latitude');
var longitude = sessionStorage.getItem('longitude');
var query = '{"Accepts_Reservations":"' + $('#chkReservation').is(":checked") + '","Accepts_Cards":' + $('#chkAcceptsCards').is(":checked") + '"}';
var searchResults = getRestaurantsAdvancedSearchAJAX(query, latitude, longitude, 40);
searchResults.success(function (data) {
var information = data.d;
var mappedRests2 = $.map($.parseJSON(information), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests2;
});
};
};
Edit 1
Once you have declared your observable like so:
self.restaurants = ko.observableArray([]);
When you want to update restaurants you cannot do this:
self.restaurants = mappedRests2;
Instead, you need to do this:
self.restaurants(mappedRests2);
updateRestaurantsList(); //Method executes AJAX and saves result to session.
The comment after the above line indicates that this method is making an asynchronous call. Therefore, it is likely that the line after it is executing before sessionStorage has been populated. Maybe consider having updateRestaurantsList return a promise. Then you could update your code to something like this:
updateRestaurantsList().then(function() {
var mappedRests2 = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants= mappedRests2;
});
This way the call to populate your mappedRests2 variable won't happen until after your updateRestaurantsList method has completed.
Edit 1
Be sure to never assign values to an observable using an equal sign.
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants(mappedRests);
self.refresh = function () {
var latitude = sessionStorage.getItem('latitude');
var longitude = sessionStorage.getItem('longitude');
var query = '{"Accepts_Reservations":"' + $('#chkReservation').is(":checked") + '","Accepts_Cards":' + $('#chkAcceptsCards').is(":checked") + '"}';
var searchResults = getRestaurantsAdvancedSearchAJAX(query, latitude, longitude, 40);
searchResults.success(function (data) {
var information = data.d;
var mappedRests2 = $.map($.parseJSON(information), function (item) { return new Restaurant(item) });
self.restaurants(mappedRests2);
});
};
};

queryformat and Railo

Apologies if I'm haven't found it in the documentation yet...
Q: How do you change the queryformat for an ajax call in Railo?
Here's my component:
component {
remote function Read() returnformat='json' {
svc = new Query();
svc.setSQL("SELECT * FROM INFORMATION_SCHEMA.TABLES");
obj = svc.execute();
local.result.Prefix = obj.getPrefix();
local.result.qry = obj.getResult();
url.queryFormat = "column";
return local.result;
}
}
and here's my JavaScript:
(function() {
var local = {};
local.type = 'POST';
local.url = 'AJAX.cfc';
local.dataType = 'json';
local.data = {};
local.data.method = 'Read';
local.Promise = $.ajax(local);
local.Promise.done(done);
local.Promise.fail(fail);
function done(response) {
console.log(response);
debugger;
}
function fail(xhr,status,response) {
debugger;
}
})();
What I'm getting back is:
response.qry.DATA[] // 57 arrays, each of length 4
But ColdFusion returns this, which I've grown fond of using (being able to use the column names instead of the array position):
response.qry.DATA.TABLE_CATALOG[] // An array of 57 elements
response.qry.DATA.TABLE_SCHEMA[]
response.qry.DATA.TABLE_NAME[]
response.qry.DATA.TABLE_TYPE[]
Use ReturnFormat="plain" on the function, and pass true for the 2nd argument of serializeJson()
serializeJson(Query, true)
That will give you a JSON object that is serialized by Column, so you can just return it.

Resources