What are my mistakes, why do I get the "object expected" error, and, eventually, how does one debug jScript ?
I am new to Dynamics CRM and I would like to do a small customisation, which seem to require jScript. The instance (version 2011) is used mostly to manage client support.
There are 2 custom entities with relationships: FundLegalEntity --> SubFund
The Case (Incident) form is linked to the FundLegalEntity and the SubFund.
When user enters a SubFund I would like to have the FundLegalEntity filled automatically (if empty).
My question was: how do I code that ?
With the help of this great tutorial, and the very usefull oData Tool, and great help (below) from user #dub, here is my latest code:
function recalcParent()
{
var lookupValue = Xrm.Page.getAttribute("new_subfundid").getValue();
var subFundId= lookupValue[0].id;
// alert(subFundId);
var request = Xrm.Page.context.getServerUrl() +
"/xrmServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=new_LegalEntityId&" +
"$filter=new_subfundId eq guid'"+ subFundId+ "'";
// alert(request);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
alert(result);
var parentFundLookup = [{ entityType : "new_fund", id : result.LegalEntityId, name : result.FundLegalEntity}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
}
I have no more errors, the first 2 alerts (commente out) are giving me correct results.
THe 3rd alert displays "object Object", and the control I expect to update is not updated.
Any hint please ? I suppose the last problem is in the var parentFundLookup = line...
I am a bit confused by all these different names.
Thanks !
Edit:
It's nearly working now: when I modify the sub-fund in the Incident, the Legal Entity gets updated with the correct legal entity name, but the text box has a strange aspect, and the icon at the left of the text box is strange as well. Here is the latest bit of code:
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
//alert(result.new_LegalEntityId.Name);
var parentFundLookup = [{ entityType : "new_LegalEntity", id : result.new_LegalEntityId.Id, name : result.new_LegalEntityId.Name}];
Xrm.Page.getAttribute("new_fundlegalentityid").setValue(parentFundLookup);
},
I suspect that the problem lies in the entityType : "new_LegalEntity", but I don't know what to put in there. Any clue on this ? What does that represent ?
Here is a screenshot of the Legal Entity after the Sub-Fund is updated and the script has run.
You can use the Rest endpoint from your script to retrieve data from the organization service. Here's an example to get you started. You can also look at the SDK documentation there's a lot of useful information there.
var subfundid; // get the id from the lookup
var request =
Xrm.Page.context.getServerUrl() +
"/XRMServices/2011/OrganizationData.svc/new_subfundSet?" +
"$select=ParentId&" +
"$top=1&" +
"$filter=new_subfundId eq guid'"+ subfundid + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend:
function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success:
function (data, textStatus, XmlHttpRequest)
{
var result = data.d.results[0];
var parentFundLookup = [{ entityType : "new_fund", id : result.ParentId, name : result.FundName}];
// Set the value of the parent fund lookup
},
error:
function (XmlHttpRequest, textStatus, errorThrown)
{
alert('Failed');
}
});
Since this code uses JQuery, you'll need to add the JQuery library as a web resource and include it in your form. See CRM 2011 "$ is undefined"
Related
I would like to automatically deactivate and activate processes on Dynamics CRM so I can upload data in between. Processes include updating information and setting one field to be another when it is inputted by user.
Is it possible to do this through the API? The documentation I saw online was mainly about querying from CRM
Reading documentation, looking on forums
use PATCH operation
workflows table holds your Dynamics 365 workflows and actions and you need to find GUID of your particualr process
https://abc.crm.dynamics.com//api/data/v9.2/workflows(c92dca98-8a13-44b9-bd13-02da90c8a38d)
body as below
{
"statecode": 1,//state
"statuscode": 2 // status
}
just tested this on Postman.
below jquery code snippet
var record = {};
record.statecode = 1; // State
record.statuscode = 2; // Status
$.ajax({
type: "PATCH",
url: Xrm.Utility.getGlobalContext().getClientUrl() + "/api/data/v9.2/workflows(c92dca98-8a13-44b9-bd13-02da90c8a38d)",
async: true,
headers: {
"OData-MaxVersion": "4.0",
"OData-Version": "4.0",
"Content-Type": "application/json; charset=utf-8",
"Accept": "application/json",
"Prefer": "odata.include-annotations=*"
},
data: JSON.stringify(record),
success: function (data, textStatus, xhr) {
console.log("Record updated");
},
error: function (xhr, textStatus, errorThrown) {
console.log(xhr);
}
});
I have a ASP.net webform populated with data from a MS SQL DB, and allows you to edit values.
The web app uses a Harvest Chosen multiselect dropdown list (max=1) to select two different persons picked from the same list of information, but on two separate controls.
When I refresh the page, sometimes both controls are populated with the correct value, sometimes neither or one are. I tested in the console and it is definitely pulling the correct information from the DB, but I must be missing something relating to how these procedures are executed. I have done this work with VB.NET and ASP controllers in the past. This is my first time using AJAX and web method functions. I believe I am missing an update somewhere, or not understanding the order in which code is executed.
I tried explicitly stating the order of operations in the .aspx page, and then doing no update triggers until after all the code for the controller had been executed, but this appears to have broken both controllers (the both end up looking like normal select controllers). Apologies if my terminology is not on point, I am very self-taught. The current state of the code where I get inconsistent application
The .aspx page is as such. Each control has a set of different parameters that affect how it is populated, and what happens when it changes.
<select class="chosen-select" multiple data-placeholder="Assign a scientist" name="ChosenScientist" style="width:800px;" id="cmbChosenScientist">
<script type="text/javascript">
handleChosenControls("select#cmbChosenScientist.chosen-select");
</script>
</select>
<select class="chosen-select" multiple data-placeholder="Assign a supervisor" name="ChosenSupervisor" style="width:800px;" id="cmbChosenSupervisor">
<script type="text/javascript">
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
</script>
</select>
The aspx page passes the controller name to a function which first defines all of the parameters used by the controllers.
function defineChosenControls(controller) {
switch (controller) {
case "select#cmbChosenScientist.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studyScientist" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
case "select#cmbChosenSupervisor.chosen-select":
currentData = JSON.stringify({ sqlQueryName: "studySupervisor" + "/" + MainContent_txbStudy.value });
populateData = JSON.stringify({ sqlQueryName: "userList" });
changeData = JSON.stringify({ strControlName: controller, arrValues: JSON.stringify($(controller).val()), strArg1: MainContent_txbStudy.value });
break;
}
}
The function that handles the populating the options, setting the current value, and handling changes is as follows:
function handleChosenControls(controller) {
//Purpose: Any time a Chosen control is loaded, changed, etc., this is run.
defineChosenControls(controller);
$(controller).chosen({ max_selected_options: 1 });
//Script for populating the control
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: populateData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).append('<option value="' + line[Object.keys(line)[0]] + '">' + line[Object.keys(line)[0]] + '</option>');
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
//Script for determining current value during load
$.ajax({
type: "POST",
url: "ClientToServer.aspx/GetDT",
data: currentData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
for (line of JSON.parse(response.d)) {
$(controller).val(line[Object.keys(line)[0]]).trigger("liszt:updated");
console.log(line[Object.keys(line)[0]]);
}
$(controller).trigger("chosen:updated");
},
error: function (response) { console.log("ERROR: Unable to retrieve current value of " + controller + " from server-side."); }
});
//Script for when a value in the control is changed
$(controller).on('change', function (e) {
defineChosenControls(controller);
$.ajax({
type: "POST",
url: "ClientToServer.aspx/PassJqueryControlValue",
data: changeData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) { console.log("ERROR: Unable to pass changed values from controller " + controller + " to server-side."); }
});
});
}
I expect both controls to have the proper value in the DB, and those values are being written in the browser console properly, but the harvest chosen controls are inconsistent.
The solution was to call the code after load.
<script type="text/javascript">
$(window).bind("load", function() {
handleChosenControls("select#cmbChosenScientist.chosen-select");
handleChosenControls("select#cmbChosenSupervisor.chosen-select");
});
I want a section to like Facebook comment system. Users will communicate each other. A user can send a post, the others can send comments.
Post
Comment1
Comment2
Comment2.1
Comment2.2
Comment2.2.1
Comment3
Comment3.1
Comment3.1.1
Firstly, I created a web service that I can pull data from a database.
I use this web service with ajax to display my data.
For displaying data, I use table, but using table is not good solution. Because my all design is floating when I open the nested comments.
Is there another suggestion instead of <td><tr> <table>?
function GetComments(postid) {
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/arayuzService.asmx/GetComments",
data: '{"postid":"' + postid + '"}',
success: function (data) {
var received= jQuery.parseJSON(data.d);
var posts = received;
var strPosts = "";
$.each(posts, function (index, a) {
strPosts += '<tr><td>' + a.userId + '</td></tr>';
strPosts += "<tr><td><div id='Comment" + a.id + "'></div></td></tr>";
});
$("#postComment" + postid).html(strPosts);
},
error: function (error) {
debugger;
}
});
}
I'm having trouble with data formatting. I have several 3-D arrays (arrays of arrays of arrays for the sticklers) that I want to pass to a PHP function through an ajax POST. I've tried combining them into an object and then stringifying it with JSON.stringify:
var postFile = '/games/saveMap';
var postObj = {'mapTiles':mapArray,
'tileRots':rotations,
'ceilings':ceiling,
'floors':floor,
'pitDepth':depth,
'sections':sectionNames,
'mapName':$('#mapName').val()
}
var postData = JSON.stringify(postObj);
$.ajax({
type: 'POST',
url: postFile,
data: postObj,
success: function(data)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
Regardless of whether I send postObj or postData I get an error that the index is undefined for all of the indexes in the object. What is wrong with my format? What format does the POST need to detect my indexes?
EDIT: While I don't see a problem in the server side syntax, it is what is throwing the "undefined index" error:
$mapName=$_POST['mapName'];
$sectionNames=$_POST['sections'];
$mapArrays=$_POST['mapTiles'];
$rotations=$_POST['tileRots'];
$ceilings=$_POST['ceilings'];
$floors=$_POST['floors'];
$pitDepth=$_POST['pitDepth'];
Try this instead:
$.ajax({
type: 'POST',
url: '/games/saveMap',
data: {
'mapTiles':mapArray,
'tileRots':rotations,
'ceilings':ceiling,
'floors':floor,
'pitDepth':depth,
'sections':sectionNames,
'mapName':$('#mapName').val()
},
success: function(data)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
The problem was referencing the object on the PHP side. The correct syntax turned out to be
$mapName=$_POST->mapName;
$sectionNames=$_POST->sections;
$mapArrays=$_POST->mapTiles;
$rotations=$_POST->tileRots;
$ceilings=$_POST->ceilings;
$floors=$_POST->floors;
$pitDepth=$_POST->pitDepth;
Something I should have remembered from my Java/C++ days.
how come when I send ajax request like this everything works
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: ShowMsg("Song deleted successfully"),
error: ShowMsg("There was an error therefore song could not be deleted, please try again"),
dataType: "json"
});
});
But when I add the anonymous function to the success It always showes me the error message although the song is still deleted
$(".btnDeleteSong").click(function () {
var songId = $(this).attr('name');
$.ajax({
type: 'POST',
url: "/Home/DeleteSong/",
data: { id: songId },
success: function () { ShowMsg("Song deleted successfully"); },
error: function () {
ShowMsg("There was an error therefore song could not be deleted, please try again");
},
dataType: "json"
});
});
what if i wanted few things on success of the ajax call, I need to be able to use the anonymous function and I know that's how it should be done, but what am I doing wrong?
I want the success message to show not the error one.
function ShowMsg(parameter) {
$("#msg").find("span").replaceWith(parameter);
$("#msg").css("display", "inline");
$("#msg").fadeOut(2000);
return false;
}
Make sure your action is returning Json data.
"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
http://api.jquery.com/jQuery.ajax/
Your action method should surely return Json data. I have the similar code see if that helps.
public ActionResult GetAllByFilter(Student student)
{
return Json(new { data = this.RenderPartialViewToString("PartialStudentList", _studentViewModel.GetBySearchFilter(student).ToList()) });
}
$("#btnSearch").live('click',function () {
var student = {
Name: $("#txtSearchByName").val(),
CourseID: $("#txtSearchByCourseID").val()
};
$.ajax({
url: '/StudentRep/GetAllByFilter',
type: "POST",
data: JSON.stringify(student),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(result) {
$("#dialog-modal").dialog("close");
RefreshPartialView(result.data);
}
, error: function() { alert('some error occured!!'); }
});
});
Above code is used to reload a partial view. in your case it should be straight forward.
Thanks,
Praveen