I have changed salesorder entity and create a new status reason in Submitted.
I have added a status reason named PreTransport in submitted state, with value 100000004.
I can go from Active state(pending status reason) to Submitted state(In-Progress status reason) via this request :
var request = ""
request += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
request += " <s:Body>";
request += " <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
request += " <request i:type=\"b:SetStateRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
request += " <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
request += " <a:KeyValuePairOfstringanyType>";
request += " <c:key>EntityMoniker</c:key>";
request += " <c:value i:type=\"a:EntityReference\">";
request += " <a:Id>" +recordGuid+ "</a:Id>";
request += " <a:LogicalName>salesorder</a:LogicalName>";
request += " <a:Name i:nil=\"true\" />";
request += " </c:value>";
request += " </a:KeyValuePairOfstringanyType>";
request += " <a:KeyValuePairOfstringanyType>";
request += " <c:key>State</c:key>";
request += " <c:value i:type=\"a:OptionSetValue\">";
request += " <a:Value>"+stateCode+"</a:Value>";
request += " </c:value>";
request += " </a:KeyValuePairOfstringanyType>";
request += " <a:KeyValuePairOfstringanyType>";
request += " <c:key>Status</c:key>";
request += " <c:value i:type=\"a:OptionSetValue\">";
request += " <a:Value>"+statusCode+"</a:Value>";
request += " </c:value>";
request += " </a:KeyValuePairOfstringanyType>";
request += " </a:Parameters>";
request += " <a:RequestId i:nil=\"true\" />";
request += " <a:RequestName>SetState</a:RequestName>";
request += " </request>";
request += " </Execute>";
request += " </s:Body>";
request += "</s:Envelope>";
//send set state request
var req = new XMLHttpRequest();
req.open("POST", Xrm.Page.context.getClientUrl() + "/XRMServices/2011/Organization.svc/web", true)
// Responses will return XML. It isn't possible to return JSON.
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
var successCallback = null;
var errorCallback = null;
req.send(request );
But it does not work from In-Progress to PreTransport that are in the same state.
I suppose that it because of permission. Should I set Permission on this new status reason?
If yes How can I do this?
Note that I have CRM 2011 on-premise.
Note: I have tried this code also, but no success.
XrmServiceToolkit.Soap.SetState("salesorder", Xrm.Page.data.entity.getId(), 1, 100000004,false);
Sorry I don't have access to 2011 version. But I tested this below snippet in CRM Rest builder, It works perfectly.
I have created a custom status reason (StatusCode) of value 100000000 : Shipping ready under status (StateCode) of 1 : Submitted. Make sure you are flowing through the allowed transitions like answered here.
var entity = {};
entity.StateCode = {
Value: 1
};
entity.StatusCode = {
Value: 100000000
};
XrmServiceToolkit.Rest.Update("B4B625A1-3789-E811-A967-000D3A1A9407", entity, "SalesOrderSet", function() {
//Success - No Return Data - Do Something
}, function(error) {
Xrm.Utility.alertDialog(error.message);
}, true);
Related
I try to parse WSDL information from http://rates.kazpost.kz/postratesprodv2/postratesws.wsdl
But when I try it, I have nothing.
xmlhttp.readyState == 4, but xmlhttp.status == 0.
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://rates.kazpost.kz/postratesprodv2/postratesws.wsdl', true);
// build SOAP request
var sr =
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pos="http://webservices.kazpost.kz/postratesws">' +
'<soapenv:Header/>' +
'<soapenv:Body>' +
'<pos:GetPostRateRequest>' +
'<pos:GetPostRateInfo>' +
'<pos:SndrCtg>1</pos:SndrCtg>' +
'<pos:Product>P102</pos:Product>' +
'<pos:MailCat>1</pos:MailCat>' +
'<pos:SendMethod>2</pos:SendMethod>' +
'<pos:Weight>750</pos:Weight>' +
'<pos:Dimension>s</pos:Dimension>' +
'<pos:Value>100</pos:Value>' +
'<pos:From>050031</pos:From>' +
'<pos:To>010001</pos:To>' +
'<pos:ToCountry>au</pos:ToCountry>' +
'</pos:GetPostRateInfo>' +
'</pos:GetPostRateRequest>' +
'</soapenv:Body>' +
'</soapenv:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
alert('done. use firebug/console to see network response');
} else {
alert('ERROR. Status: ' + xmlhttp.status + " " + xmlhttp.statusText);
}
}
}
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.send(sr);
// send request
// alert("Ready.");
Seems like you're trying to make http request under https connection, so request is blocked by browser for security reasons.
HTTP Ajax Request via HTTPS Page for more details
I'm try to integrate Netsuite to Salesforce using SalesForce SOAP API(Partner WSDL).
In Netsuite Side i'm using the 'N/https' Module to send request and getting response.
First i'm Sending Login request to Salesforce and it is giving the Unique Session Id.
Now I'm trying to send create request to create an accounts record in salesforce using the obtained session id. While constructing the XML SOAP Message,
i'm adding the Session Id value in "urn : SessionId tag" . While sending the HTTPS request is showing the following SOAP Fault Code:
ERROR Message :
<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode>soapenv:Client</faultcode><faultstring>Unexpected element {}sessionId during simple type deserialization</faultstring></soapenv:Fault></soapenv:Body></soapenv:Envelope>"
}
My Code :
Suite Script Version:2.0 , Type : User Event, Method : After Submit,Module : 'N/https'
function afterSubmit(scriptContext) {
var customerRec = scriptContext.newRecord ;
var customerName = customerRec.getText('entityid');
log.debug('customerName : ',customerName);
//SOAP Login Request
var postData = '';
var header=[];
var apiURL = '';
var response = '';
var strSOAPLoginRequest="";
strSOAPLoginRequest += "<soapenv:Envelope xmlns:soapenv=\"http:\/\/schemas.xmlsoap.org\/soap\/envelope\/\" xmlns:urn=\"urn:partner.soap.sforce.com\">";
strSOAPLoginRequest += " <soapenv:Header>";
strSOAPLoginRequest += " <\/soapenv:Header>";
strSOAPLoginRequest += " <soapenv:Body>";
strSOAPLoginRequest += " <urn:login>";
strSOAPLoginRequest += " <urn:username>myloginid<\/urn:username>";
strSOAPLoginRequest += " <urn:password>mypwd<\/urn:password>";
strSOAPLoginRequest += " <\/urn:login>";
strSOAPLoginRequest += " <\/soapenv:Body>";
strSOAPLoginRequest += "<\/soapenv:Envelope>";
postData = strSOAPLoginRequest;
header['Content-Type']='text/xml';
header['SOAPAction']='https://login.salesforce.com/services/Soap/u/41.0';
apiURL='https://login.salesforce.com/services/Soap/u/41.0';
try{
response=https.post({
url:apiURL,
headers:header,
body:postData
});
response = JSON.stringify(response);
log.debug("Login-Respone:", response+ ', Type:'+typeof response);
var getSessionIdStartIndex = response.indexOf("<sessionId>");
log.debug('getSessionIdStartIndex:',getSessionIdStartIndex);
var getSessionIdEndIndex = response.indexOf("</sessionId>");
log.debug('getSessionIdEndIndex:',getSessionIdEndIndex);
var ressessionValue= response.substring(getSessionIdStartIndex, getSessionIdEndIndex);
ressessionValue = ressessionValue.replace(/^\s+|\s+$/g, "");
log.debug('resSessionId:',ressessionValue + 'Type:'+typeof ressessionValue);
header = [];
// SOAP CREATE ACTION REQUEST
header['Content-Type']='text/xml';
header['SOAPAction']= 'https://ap5.salesforce.com/services/Soap/u/41.0/00D7F0xxxx';
apiURL='https://ap5.salesforce.com/services/Soap/u/41.0/'+'007xxxx';
//apiURL=res_serverUrl;
var strSOAPCreateActionXml="";
strSOAPCreateActionXml += "<soapenv:Envelope xmlns:soapenv=\"http:\/\/schemas.xmlsoap.org\/soap\/envelope\/\" xmlns:urn=\"urn:partner.soap.sforce.com\" xmlns:urn1=\"urn:sobject.partner.soap.sforce.com\" xmlns:xsi=\"http:\/\/www.w3.org\/2001\/XMLSchema-instance\">";
strSOAPCreateActionXml += " <soapenv:Header>";
strSOAPCreateActionXml += " <urn:SessionHeader>";
strSOAPCreateActionXml += "<urn:sessionId>"+ressessionValue+"<\/urn:sessionId>";
strSOAPCreateActionXml += "<\/urn:sessionId>";
strSOAPCreateActionXml += " <\/urn:SessionHeader>";
strSOAPCreateActionXml += " <\/soapenv:Header>";
strSOAPCreateActionXml += " <soapenv:Body>";
strSOAPCreateActionXml += " <urn:create>";
strSOAPCreateActionXml += " <urn:sObjects xsi:type=\"urn1:Account\">";
strSOAPCreateActionXml += " <Name>"+customerName+"<\/Name>";
strSOAPCreateActionXml += " <AccountNumber>4567<\/AccountNumber>";
strSOAPCreateActionXml += " <\/urn:sObjects>";
strSOAPCreateActionXml += " <\/urn:create>";
strSOAPCreateActionXml += " <\/soapenv:Body>";
strSOAPCreateActionXml += "<\/soapenv:Envelope>";
postData = strSOAPCreateActionXml;
var responseCreate = https.post({
url:apiURL,
headers:header,
body:postData
});
responseCreate = JSON.stringify(responseCreate);
log.debug("CreateAction-Respone:", responseCreate+ ', Type:'+typeof responseCreate);
}catch(err){
log.error('ERROR',err.message);
}
}
Instead of assigning sessionId value as in the above code block. if i replace sessionId value line as in below code block means it working correctly
var strVar="";
strVar += " <urn:sessionId>AQ8AQJCeR3ViMdN48UXWfDD0SiMbW5K6JOz3a0K6DhXt63pp54PsKOpoiMh.8mnw7bJxe0hQoyrCbRZtk0kmliNFfIntRAQb<\/urn:sessionId>";
Wondering what is the mistake in place the value for urn: sessionId tag in my first code block.
My question is how to construct the dynamically obtained session value in the Constructing XML SOAP Message
Thanks in Advance.
Looks like you need:
var getSessionIdStartIndex = response.indexOf("<sessionId>") + “<sessionId>”.length;
The session Id starts at the end of <sessionId>.
I've created an Action under Process for a custom entity new_enrollment. I've created no I/O argument for that action. Now, by using following code snippet I want to run that custom action so that when action is executed a plugin get fired and create a phone call.
But it seems that action is not get executed. Any suggestion or help so that I can get action executed.
function emailOrderDetails(){
var entityId = Xrm.Page.data.entity.getId();
var entityName = "new_enrollment";
var requestName = "new_sendemail";
RunAction(entityId, entityName, requestName);
window.location.reload(true);
}
function RunAction(entityId, entityName, requestName) {
try{
// Creating the request XML for calling the Action
var requestXML = ""
requestXML += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
requestXML += " <s:Body>";
requestXML += " <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
requestXML += " <request xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\">";
requestXML += " <a:Parameters xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
requestXML += " <a:KeyValuePairOfstringanyType>";
requestXML += " <b:key>Target</b:key>";
requestXML += " <b:value i:type=\"a:EntityReference\">";
requestXML += " <a:Id>" + entityId + "</a:Id>";
requestXML += " <a:LogicalName>" + entityName + "</a:LogicalName>";
requestXML += " <a:Name i:nil=\"true\" />";
requestXML += " </b:value>";
requestXML += " </a:KeyValuePairOfstringanyType>";
requestXML += " </a:Parameters>";
requestXML += " <a:RequestId i:nil=\"true\" />";
requestXML += " <a:RequestName>" + requestName + "</a:RequestName>";
requestXML += " </request>";
requestXML += " </Execute>";
requestXML += " </s:Body>";
requestXML += "</s:Envelope>";
var req = new XMLHttpRequest();
req.open("POST", GetClientUrl(), false)
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(requestXML);
//Get the Response from the CRM Execute method
//var response = req.responseXML.xml;
}
catch(e){
alert(e.Message);
}
}
function GetClientUrl() {
if (typeof Xrm.Page.context == "object") {
clientUrl = Xrm.Page.context.getClientUrl();
}
var ServicePath = "/XRMServices/2011/Organization.svc/web";
return clientUrl + ServicePath;
}
you are using 2016 which supports WebAPI and its very easy using WebAPI. Below is the working example of calling custom action using JS. I have 2 output variables, one get set by custom action and the other one "ptext" by plugin which i have registered on this Action.
Hope it will solve your problem.
function CallCAction(context) {
var Credit_Limit = Xrm.Page.getAttribute("creditlimit").getValue();
var Credit_hold = Xrm.Page.getAttribute("creditonhold").getValue();
if(Credit_hold !=null && Credit_Limit!=null){
var actionName = "new_Preferred_Check";
var inputParam = {
"Credit_Limit": Credit_Limit,
"Credit_hold": Credit_hold
};
Xrm.Page.ui.setFormNotification("Processing...","INFO","processingFId");
var actionResponse = callPreferredCust(actionName, inputParam);
if (actionResponse != null) {
Xrm.Page.getAttribute("new_preferredcust").setValue(actionResponse.Preferred_Cust);
alert(actionResponse.ptext);
Xrm.Page.ui.clearFormNotification("processingFId");
}
}
}
function callPreferredCust(actionName, inputParam) {
var result = null;
var req = new XMLHttpRequest();
var uri = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/";
try {
req.open("POST",encodeURI(uri+actionName),false);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function () {
if(this.readyState==4){
req.onreadystatechange = null;
if(this.status==200){
result = JSON.parse(this.response);
}else{
var err = JSON.parse(this.response).error;
alert(err.message);
}
}
};
req.send(JSON.stringify(inputParam));
return result;
}catch(err){
alert(err.message);
}
}
I am trying to update multiple records in Share Point using jQuery and CAML. I can update a single record easily with this code but for this project, I need to update 20 Products at a time. I suppose I could loop and call this function 20 times, but I figure there must be a more elegant solution that would hopefully complete the task in a single request.
There are 20 Select boxes for each survey named "Prod_1", "Prod_2", ... , "Prod_20".
function saveProducts() {
var sList = "ProductData"
var i = 1;
var sQry = "";
sQry += "<Batch OnError='Continue'>";
sQry += " <Method ID='1' Cmd='Update'>";
sQry += " <Field Name='ID'>" + $("#uniqueID").val() + "</Field>";
sQry += " <Field Name='Offered'>" + $("#Prod_1").val() + "</Field>";
sQry += " </Method>";
sQry += "</Batch>";
var request = "";
request += "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'";
request += " xmlns:xsd='http://www.w3.org/2001/XMLSchema'";
request += " xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
request += " <soap:Body>";
request += " <UpdateListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
request += " <listName>" + sList + "</listName>";
request += " <updates>" + sQry + "</updates>";
request += " </UpdateListItems>";
request += " </soap:Body>";
request += "</soap:Envelope>";
$.ajax({
async: false, url: sURL, type: "POST", dataType: "xml", data: request, contentType: "text/xml; charset=\"utf-8\"",
beforeSend: function (xhr) { xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/UpdateListItems"); },
complete: function processSaveProducts(xData, status) {
//alert("Save Status: " + status);
}
});
}
Is there a way to do this with a single update instead of running this code 20 times? Thanks!
You can nest multiple <Method> nodes within the same <Batch>:
<Batch OnError="Continue" ListVersion="1"
ViewName="270C0508-A54F-4387-8AD0-49686D685EB2">
<Method ID="1" Cmd="Update">
<Field Name="ID">4<Field>
<Field Name="Field_Name">Value</Field>
</Method>
<Method ID="2" Cmd="Update">
<Field Name="ID" >6</Field>
<Field Name="Field_Name">Value</Field>
</Method>
</Batch>
More info:
https://msdn.microsoft.com/en-us/library/lists.lists.updatelistitems(v=office.12).aspx
I've checked through the forum and cant seem to get what i need to work.
On the lead entity, when a user creates a new lead a Workflow runs just before to change some lead fields.
I found out this is only possible through javascript and onload in the entity settings.
I've created the Workflow and a JavaScript file and set it to run onload. The Javascript i have used is:
function callworkfow(workflowId, entityId) {
var request =
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<Execute xmlns="http://schemas.microsoft.com/xrm/2011/Contracts/Services"
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<request i:type="b:ExecuteWorkflowRequest" xmlns:a="http://schemas.microsoft.com/xrm/2011 /Contracts" xmlns:b="http://schemas.microsoft.com/crm/2011/Contracts">
<a:Parameters xmlns:c="http://schemas.datacontract.org/2004/07/System.Collections.Generic">
<a:KeyValuePairOfstringanyType>
<c:key>B3D77337-D5FD-E211-BB05-005056AF0003</c:key>
<c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/">EntityIdValue</c:value>
</a:KeyValuePairOfstringanyType>
<a:KeyValuePairOfstringanyType>
<c:key>2EF8C158-182B-444A-A9DF-FF2DC5E44514</c:key>
<c:value i:type="d:guid" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization /">WorkflowIdValue</c:value>
</a:KeyValuePairOfstringanyType>
</a:Parameters>
<a:RequestId i:nil="true" />
<a:RequestName>ExecuteWorkflow</a:RequestName>
</request>
</Execute>
</s:Body>
</s:Envelope>
var xhr = new XMLHttpRequest();
xhr.open('POST', '/XRMServices/2011/Organization.svc/web', true);
xhr.setRequestHeader('Accept', 'application/xml, text/xml, */*');
xhr.setRequestHeader('Content-Type', 'text/xml; charset=utf-8');
xhr.setRequestHeader('SOAPAction', 'http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute');
xhr.onreadystatechange = function () { alert(xhr.status); };
xhr.send(request);
}
However this fails to load.
If anyone could help me i would be very grateful. Just need the JavaScript to simply load a Workflow. Oh and with cross platform compatibility.
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}
var ExistingCase = curentUserId = Xrm.Page.context.getUserId();
if (ExistingCase.getValue() != null) {
var ExistingCaseGUID = ExistingCase.getValue()[0].id;
var ExistingCaseName = ExistingCase.getValue()[0].name;
SetLookupValue("new_accountmanager", ExistingCaseGUID, ExistingCaseName, "incident");
}
please check following code, it worked fine for me last time i used it:
if (typeof (SDK) == "undefined")
{ SDK = { __namespace: true }; }
//This will establish a more unique namespace for functions in this library. This will reduce the
// potential for functions to be overwritten due to a duplicate name when the library is loaded.
SDK.Workflow = {
_getServerUrl: function () {
///<summary>
/// Returns the URL for the SOAP endpoint using the context information available in the form
/// or HTML Web resource.
///</summary>
var ServicePath = "/XRMServices/2011/Organization.svc/web";
var serverUrl = "";
if (typeof GetGlobalContext == "function") {
var context = GetGlobalContext();
serverUrl = context.getServerUrl();
}
else {
if (typeof Xrm.Page.context == "object") {
serverUrl = Xrm.Page.context.getServerUrl();
}
else
{ throw new Error("Unable to access the server URL"); }
}
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
return serverUrl + ServicePath;
},
ExecuteRequest: function () {
var requestMain = ""
requestMain += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
requestMain += " <s:Body>";
requestMain += " <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
requestMain += " <request i:type=\"b:ExecuteWorkflowRequest\" xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
requestMain += " <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
requestMain += " <a:KeyValuePairOfstringanyType>";
requestMain += " <c:key>EntityId</c:key>";
requestMain += " <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">267d4790-e41a-e311-b6a7-3c4a92db481b</c:value>";
requestMain += " </a:KeyValuePairOfstringanyType>";
requestMain += " <a:KeyValuePairOfstringanyType>";
requestMain += " <c:key>WorkflowId</c:key>";
requestMain += " <c:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">a6832cc5-1d82-48f5-a940-e41269726204</c:value>";
requestMain += " </a:KeyValuePairOfstringanyType>";
requestMain += " </a:Parameters>";
requestMain += " <a:RequestId i:nil=\"true\" />";
requestMain += " <a:RequestName>ExecuteWorkflow</a:RequestName>";
requestMain += " </request>";
requestMain += " </Execute>";
requestMain += " </s:Body>";
requestMain += "</s:Envelope>";
var req = new XMLHttpRequest();
req.open("POST", SDK.Workflow._getServerUrl(), false)
req.setRequestHeader("Accept", "application/xml, text/xml, */*");
req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
req.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute");
req.send(requestMain);
//work with the response here
var strResponse = req.responseXML.xml;
alert(strResponse.toString());
},
__namespace: true
};
UPDATE:--------------
My previous answer was direct to question. Now providing new answer due to question comments. As it's said in comments workflows can be run only over existing records, but as you said you want to change some field on creation form: record is not saved yet. To do that you must use Xrm object as it is shown below:
function OnLoadingForm() {
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
switch (FormType) {
case 1:
// It's a "create" form
var test = "Mr.";
Xrm.Page.getAttribute("salutation").setValue(test);
break;
case 2:
// It's a "update" form
break;
case 3:
// It's a "readonly" form
break;
case 4:
// It's a "disabled" form
break;
case 6:
// It's a "bulkedit" form
break;
default:
break;
}
}
}
This code works on classic CRM forms (Information forms in customizations). New release may change this. "salutation" is name of field from customizations. Notice that this field change is only on form and will be saved to CRM DB after user clicks Save button.
UPDATE 2:-----------
Due to new circumstances new code snippet:
function OnLoadingForm() {
// Get the current FormType
var FormType = Xrm.Page.ui.getFormType();
if (FormType != null) {
switch (FormType) {
case 1:
// It's a "create" form
var curentUserId = Xrm.Page.context.getUserId();
var serverUrl;
if (Xrm.Page.context.getClientUrl !== undefined) {
serverUrl = Xrm.Page.context.getClientUrl();
} else {
serverUrl = Xrm.Page.context.getServerUrl();
}
var ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var userRequest = new XMLHttpRequest();
userRequest.open("GET", ODataPath + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')", false);
userRequest.setRequestHeader("Accept", "application/json");
userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");
userRequest.send();
if (userRequest.status === 200) {
var retrievedUser = JSON.parse(userRequest.responseText).d;
var userFullName = retrievedUser.FullName;
SetLookupValue("new_accountmanager", curentUserId, userFullName, "systemuser");
}
else {
return "error";
}
break;
case 2:
// It's a "update" form
break;
case 3:
// It's a "readonly" form
break;
case 4:
// It's a "disabled" form
break;
case 6:
// It's a "bulkedit" form
break;
default:
break;
}
}
}
function SetLookupValue(fieldName, id, name, entityType) {
if (fieldName != null) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = id;
lookupValue[0].name = name;
lookupValue[0].entityType = entityType;
Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
}
}