Get all business recommended fields in subgrid - dynamics-crm

How do I check if a particular field or column of a subgrid is business recommend or not? I want to do this using a web resource. Also due to some requirements, I will have to use the execution context of the form where the subgrid is present and not of the subgrid itself.

It is a little tricky because at the time that the form loads, the subgrid does not have data. So you have to use the Form's load event to attach a load event to the subgrid.
This is described in this MS Docs Page. You can do this like
function attachGridEvent(executionContext)
{
var formContext = executionContext.getFormContext();
var gridContext = formContext.getControl("gridCategories");
// We have the grid, now add a "load" event handler
gridContext.addOnLoad(MyGridLoadedEvent);
}
Now you've got a 'load' event for your grid so you can iterate through its rows and examine its data
I haven't been able to get this to work for subgrids that don't contain data
I get the first row in the sub grid. Once I have that we can loop through each of the row's attributes. Each attribute has the following methods:
getName Returns the logical name of the attribute of a selected grid
row.
getRequiredLevel Returns a string value indicating whether a
value for the attribute is required or recommended.
setRequiredLevel Sets whether data is required or recommended for the
attribute of a selected grid row before the record can be saved.
getValue Retrieves the data value for an attribute.
setValue Sets the
data value for an attribute.
MS Docs Page
I'm using some modern browser features (map, =>) but this code should work for you
function MyGridLoadedEvent(evt)
{
var gridContext = evt.getEventSource();
var rows = gridContext.getGrid().getRows();
if (rows.getLength() > 0)
{
let rowAttributes = rows.getByIndex(0).getAttribute();
let mappedResults = rowAttributes.map(x => x.getName() + " : " + x.getRequiredLevel());
alert(mappedResults);
}
}

Related

how to pass softcoded element to crm web resource script

I'm having trouble passing in the name of an element into a Dyanamics CRM web Resource javacript.
This code works:
function OnFormLoad()
{
var subGrid = window.parent.document.getElementById("Claims")
// do work
}
This code doesn't:
function OnFormLoad(GridName)
{
var subGrid = window.parent.document.getElementById(GridName)
// do work
}
How do I pass in the name of the element I want to work with?
Please refrain from using document.getElementById in Dynamics as it is not supported.
I believe you are trying to get GridContext and get Data from that Grid.
For Example on Account entity we have Contacts as Grid and then you wish to get data from that Grid.
I replicated the same on Account Entity (OnLoad) and get tried to get data from Contacts Grid.
When adding OnLoad event I have passed Grid name as Parameter as below.
I have added below onLoad Js on Account entity and was able to retrieve data from grid.
Note: I have added timeout because directly firing onload was not able to load complete page and then grid Name was not available.
function onLoad(executionContext,gridName){
setTimeout(function(){ getGridDatat(executionContext,gridName); }, 3000);
}
function getGridDatat(executionContext,gridName){
debugger
var formContext = executionContext.getFormContext();
var gridContext = formContext.getControl("Contacts"); // get the grid context
var myRows = gridContext.getGrid().getRows();
/*var myRow = myRows.get(arg);
var gridRowData = myRow.getData();*/
var firstRow =myRows.get(0).getData();
var firstRowAllAttributes = firstrow.entity.attributes.getAll()
var firstRowfirstAttributeValue = firstrow.entity.attributes.get(0).getValue()
}
If you want to perform some operation on change of data formGird then there is one more way to achieve this. Make your grid as Editable and then you can find Events for that gird as below and could perform your operations.

Filling MVC DropdownList with AJAX source and bind selected value

I have view for showing Member details. Inside there is an EditorFor element which represents subjects taken by the member.
#Html.EditorFor(m => m.Subject)
Inside the editor template there is a Html.DropDownListFor() which shows the selected subject and button to delete that subject
I am using an Html.DropDownListFor element as :
#Html.DropDownListFor(m => m.SubjectID, Enumerable.Empty<SelectListItem>(), "Select Subject",
new { #class = "form-control subjects" })
The second parameter(source) is set empty since I want to load the source from an AJAX request; like below:
$.getJSON(url, function (response) {
$.each(response.Subjects, function (index, item) {
$('.subjects').append($('<option></option>').text(item.Text).val(item.ID));
});
// code to fill other dropdowns
});
Currently the html loads before the dropdowns are filled. So the values of all subject dropdowns are set to the default "Select Subject". Is there a way around this or is it the wrong approach?
Note: There are a number of dropdowns in this page. That's why I would prefer to load them an AJAX request and cache it instead of putting in viewModel and filling it for each request.
** EDIT **
In AJAX call, the action returns a json object containing dropdowns used across all pages. This action is decorated with [Output Cache] to avoid frequent trips to server. Changed the code in $.each to reflect this.
You can initially assign the value of the property to a javascript variable, and use that to set the value of the selected option in the ajax callback after the options have been appended.
// Store initial value
var selectedId = #Html.Raw(Json.Encode(Model.Subject.SubjectID))
var subjects = $('.subjects'); // cache it
$.getJSON(url, function (response) {
$.each(response, function (index, item) {
subjects.append($('<option></option>').text(item.Text).val(item.ID));
});
// Set selected option
subjects.val(selectedId);
});
However its not clear why you are making an ajax call, unless you are generating cascading dropdownlists which does not appear to be the case. What you doing is basically saying to the client - here is some data, but I forgot to send what you need, so waste some more time and resources establishing another connection to get the rest of the data. And you are not caching anything despite what you think.
If on the other hand your Subject property is actually a collection of objects (in which case, it should be Subjects - plural), then the correct approach using an EditorTemplate is explained in Option 1 of this answer.
Note also if Subject is a collection, then the var selectedId = .. code above would need to be modified to generate an array of the SubjectID values, for example
var selectedIds = #Html.Raw(Json.Encode(Model.Subject.Select(x => x.SubjectID)))
and then the each dropdownlist value will need to be set in a loop
$.each(subjects, function(index, item) {
$(this).val(selectedIds[index]);
});
If your JSON tells you what option they have selected you can simply do the following after you have populated your dropdown:
$('.form-control.subjects').get(0).selectedIndex = [SELECTED_INDEX];
Where [SELECTED_INDEX] is the index of the element you want to select inside the dropdown.

need to get value of dropdown menu without using onChange callback - (material-ui reactjs)

i am using material UI dropdown component and trying to run a callback function only when user fills all the form and submits the form. On the call back function i intend to collect all the form field and generate url to call to api.
My problem is that i can not use onChange as stated solution in #560 as i want to collect all the detail only when user clicks the submit button. It is also weird that at the moment, i am able to get value of all the other form element like slider, textfield which uses material-ui but only dropdown does not seem to be working.
My call back function:
handleFilter: function(event){
event.preventDefault();
var location = this.refs.location.getValue();
var posted_date = this.refs.posted_date.getValue();
var radius = this.refs.distance.getValue();
var salary = this.refs.salary.getValue();
var jobtype = this.refs.jobtype.getValue();
console.log(jobtype);
}
In the above function "location, posted_date, radius, salary" returns value but "jobtype" which happens to be dropdown does not seem to return any value. It returns this error in console:
"Uncaught TypeError: this.refs.jobtype.getValue is not a function"
Here is my dropdown component :
<DropDownMenu menuItems={menuItems} ref="jobtype" />
May not be the right way but i figured out that
console.log(this.refs.jobtype) (jobtype is the refs value of dropdown in my case)
was giving the following result.
R…s.c…s.Constructor {props: Object, context: Object, state: Object, refs: Object, _reactInternalInstance: ReactCompositeComponentWrapper}
Inpecting it i found value of payload index (index number of selected item) inside state object within "selectedIndex" property. I used following code to access the selected index:
var jobtype = this.refs.jobtype.state.selectedIndex;
If there is a better way to do this please suggest.

Populating a grid via autocomplete and posting the results

I have a view where I create a new company.
The company has a number of trades, or which 1 is a primary trade.
So when I enter the trades for that company, I select a trade via autocomplete, and this trade is added to a grid of trades underneath the autocomplete textbox. The grid contains the tradeId as a hidden field, the trade, and a radio button to indicate whether the trade is a primary trade and a remove button.
This is part of a form that contains other company details such as address.
Now I am wondering if I can use knockout and (maybe) jsrender to populate the grid without posting to the server?
When I have filled in the grid AND the other company details, I then want to submit the data to the controller post method.
Normally I use the Html helpers to post values to the controller, but I don't see how I can do that using knockout.
Yes you can use Knockout for this. If you have not checked the tutorials out yet then try this Knockout List and Collections tutorial. This should point you in the right direction. What you'll need to do is create a Trade object with observable properties and in a separate knockout view model create an observableArray to store trade objects. For information on posting to the server there are other tutorials in the same location.
function Trade(item) {
var self = this;
self.tradeId = ko.observable(item.tradeId);
self.tradeName = ko.observable(item.tradeName);
self.isPrimary = ko.observable(item.isPrimary);
}
function TradesViewModel() {
var self = this;
// Editable data
self.trades = ko.observableArray([]);
self.removeTrade = function(trade) { self.trades.remove(trades) }
self.save = function() {
$.post("/controller/action", self.trades);
}
}
ko.applyBindings(new TradesViewModel());

How to set default field values for add form in jqgrid from current row

Add toolbar button is used to add new row to jqgrid.
Add form which appears contains all filed vlaues empty.
How to set add form field values from column values from row which was current/selected when add command was issued ?
json remote data is used. Or if this is simpler, how to call server method passing current/selected row to retrieve default values for add form from server ?
jqgrid contains also hidden columns. If possible values from hidden columns from current row should also sent to add controller if add form is saved.
Update
I tried to use Oleg great suggestion by using
afterShowForm: function(formID) {
var selRowData,
rowid = grid.jqGrid('getGridParam', 'selrow');
if (rowid === null) {
// todo: how to cancel add command here
alert('Please select row');
return;
}
selRowData = grid.jqGrid('getRowData', rowid);
if (selRowData === null) {
alert('something unexpected happened');
return;
}
$('#' + 'Baas' + '.FormElement', formID).val(selRowData.Baas);
}
Application keeps add form open after saving. After first save Baas field is empty. It looks like afterShowForm event runs only once, not after every save. How to fix this so that multiple rows with default values can added without closing add form?
How to cancel or not allow Add command if there is no selected row ?
If you need to make some initialization actions only for Add form you can use at least two approaches:
the usage of defaultValue property as function inside of editoptions. The callback function defaultValue can provide the value for the corresponding field of the Add form based of the data from selected row. For optimization purpose you can read the data from the current selected row once in the beforeInitData callback/event. You can just read the data which you need or make an synchronous call to the server to get the information which you need. The only disadvantage of the usage of defaultValue property is that it uses jQuery.val method to set the default value for all fields of Add form with exception 'checkbox' edittype. For the checkboxs jqGrid set checked property of the checkbox of false, 0, no, off or undefined are not found in the value returned by defaultValue property. So the approach will not work for other edittypes. For example it can fail for the custom edittype.
the usage of beforeShowForm or afterShowForm. Inside of the callback functions you can set any value of the form. You can find the filed of the corresponding column of the grid by id of the field which is the same as the value of name property of the corresponding column.
Like you already knows you can get the id of the current selected row with respect of getGridParam and get the data from the selected row
var selRowData, rowid = grid.jqGrid('getGridParam', 'selrow');
if (rowid !== null) {
// a row of grid is selected and we can get the data from the row
// which includes the data from all visible and hidden columns
selRowData= grid.jqGrid('getGridParam', 'selrow');
}
where grid is jQuery object like $('#list') which selects the main <table> element of the grid.
In the demo you can see how works the first approach described above.

Resources