Wednesday, January 26, 2011

Creating records in CRM 2011 using JavaScript

Using the CRM Web Service, you can create new entity records, just using JavaScript. The following code demonstrates this:

// Make Struct
function MakeStruct(names) {
var names = names.split(' ');
var count = names.length;
function constructor() {
for (var i = 0; i < count; i++) {
this[names[i]] = arguments[i];
}
}
return constructor;
}


// CRM Field Struct
var CRMField = MakeStruct("SchemaName Value");

// Call Crm Service
function CallCrmService(soapBody, method)
{
try {
var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", '/mscrmservices/2007/CrmService.asmx', false);
xmlHttpRequest.setRequestHeader("SOAPAction", 'http://schemas.microsoft.com/crm/2007/WebServices/' + method);
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
var xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"
<soap:Envelope xmlns:soap=\'http://schemas.xmlsoap.org/soap/envelope/\' xmlns:xsi=\'http://www.w3.org/2001/XMLSchema-instance\' xmlns:xsd=\'http://www.w3.org/2001/XMLSchema\'>" +
GenerateAuthenticationHeader() + "<soap:Body>" + soapBody + "</soap:Body></soap:Envelope>";
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
xmlHttpRequest.send(xml);

var resultXml = xmlHttpRequest.responseXML;
var errorCount = resultXml.selectNodes('//error').length;

if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);

return null;
}

return resultXml;
}
catch(err) {
}

return null;
}

// Create Record
function CreateRecord(entityName, fields)
{
try {
var resultArray = new Array();
var attributesList = '';

for(var i = 0; i < fields.length; i++)
attributesList += "<" +
fields[i].SchemaName + ">" + fields[i].Value + "</"+fields[i].SchemaName+">";
}

var xml = "
<Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'><entity xsi:type='"+entityName+"'>" + attributesList + "</entity></Create>";
var resultXml = CallCrmService(xml, 'Create');

if (resultXml) {
var newid = resultXml.selectSingleNode('//CreateResult').nodeTypedValue;
return newid;
}
}
catch(err) {
}

return null;

}

// USE
// Create new Contact
function CreateContact()
{
var fields = [new CRMField('firstname', 'Cornel'), new CRMField('lastname, 'Croitoriu')];
return CreateRecord('contact', fields); // return new contact id
}

// Create new Annotation
function CreateAnnotation(parentEntityName, parentEntityId, title, text)
{
var fields = [new CRMField('objecttypecode', parentEntityName), new CRMField('objectid', parentEntityId), new CRMField('subject', title), new CRMField('notetext', text), new CRMField('isdocument', false), new CRMField("mimetype", "text/html")];
return CreateRecord('annotation', fields); // return new note id
}

// Example
CreateAnnotation('opportunity', 'FD140AAF-4DF4-11DD-BD17-0019B9312238', 'dynamic generated note', 'text goes here...');

0 comentarii: