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 = "" +
		"" + GenerateAuthenticationHeader() + "" + soapBody + "";
		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 + "";
		}

		var xml = "" + attributesList + "";
		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…');

11 comments

  1. I’m trying to use this code, but on every time the call of

    xmlHttpRequest.send(xml);

    I get asking to enter my authentification. But even though I enter it, it does not work. No record is created.
    Can you help?

  2. This code works. Just put first letter in upper case for create, body,envelope. I did this and it helped.

  3. I can’t get it to work either. Always prompts for a password. Then fails anyway. Can you report working code? I’d really appreciate it as I do need this functionality. Thx

  4. This really does not work. Unfortunately I am not on Premise so I cannot even use trace for this.

    Does anyone have an alternative, workaround or a fix to this “An unexpected error occurred” error.

  5. The problem with authorization dissapears if you change the uppercase for create, body. Leave envelope lowercase.

    Additionally, in order to work it is neccesary to add close tags for field names, change line 61 to:
    attributesList += “” + fields[i].Value + “”;

  6. from rollup 11 CRM has new cross browser features
    and ActiveXObject does not works on other browsers.
    Is there some different way to create an entity using jscript?

Leave a comment

Your email address will not be published. Required fields are marked *