Wednesday, 20 May 2015

InitializeFromRequest in CRM


When I was working some relationships and mappings, we got a requirement to create a child record in the plugin.

From UI, we have mapped the fields and the same fields we need to use for creating the record in the plugin. After some search I came to know that there is a SDK method available for this from CRM 4.0. i.e InitializeFromRequest

Let's have a look at it now.

I have some fields in the Account entity which I would like to map to Child entity (Student in my case). Here is the mappings for this.

Account Form

Student Form

Now tried creating student record form CRM UI. It automatically populated the mapped fields.

Let us see how can we achieve the same thing using SDK message.

Here is the C# code I have written for it

// Create the request object
InitializeFromRequest initializeFromRequest = new InitializeFromRequest();
// Set the properties of the request object
initializeFromRequest.TargetEntityName = "new_students";
// Create the EntityMoniker
initializeFromRequest.EntityMoniker = new EntityReference("account", new Guid("43A0F1C2-7CF5-E411-80D5-C4346BAC59E8"));
// fields to initialised from parent entity
initializeFromRequest.TargetFieldType = TargetFieldType.All;
// Execute the request
InitializeFromResponse initializeFromResponse = (InitializeFromResponse)objService.Execute(initializeFromRequest);
Entity entStudent = null;
if (initializeFromResponse.Entity != null)
     //get entity from the response
     entStudent = initializeFromResponse.Entity;
     // set the name for the Student entity
     entStudent.Attributes.Add("new_name", "Test");
     //create a new Student record
After I debug it this is what it gave. I just used the same and created a record

Points to be noted
  1. It can be used where we can 1:N relationships
  2. The request does not create a new record but the response can be used to create a new record.

Hope this helps.

Happy CRM'ing

No comments:

Post a Comment