Monday 17 March 2014

Create Entity in Ms Dynamics CRM 2011/2013 using OData endpoint

This is really part of the brain dump series but haven't really had the time until now.

Two entities,  Author (dab_author) and Book (dab_book) with a 1:N relationship between them.

The challenge is to create an new book for a particular author, from the author form.


var createNewBook = function()
{
 url = Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/dab_bookSet";
 author = Xrm.Page.data.entity.getId();
 dab_book = {};
 dab_book.dab_name = "Odata entity creation test";
 dab_BooksId = {};
 dab_BooksId.Id = author;
 dab_BooksId.LogicalName = "dab_author";
 dab_book.dab_BooksId = dab_BooksId;
 book = window.JSON.stringify(dab_book);

 createBook(book, url).done(process)

}

var createBook = function(book, url)
{
 return $.ajax({
 type:"POST", 
 contentType:"application/json;charset=utf-8",
 datatype:"json",
 data:book,
 url:url,
 beforeSend:function(x){x.setRequestHeader("Accept","application/json")},
 });
}

var process = function(data){
 var entity = data.d; 
 alert("Created new Book. Id:" + entity.dab_bookId);
}

Do bear in mind that casing is a bit funny. The relationship name is dab_booksid, however it needs to be sort of title cased to dab_BooksId, in essence the prefix needs to be kept in lower case, the rest Title Cased.

Also, jquery needs to be loaded if you are using Dynamics CRM 2011

No comments:

Post a Comment