AXForum  
Вернуться   AXForum > Microsoft Dynamics CRM > Dynamics CRM: Blogs
All
Забыли пароль?
Зарегистрироваться Правила Справка Пользователи Сообщения за день Поиск

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 23.08.2011, 12:11   #1  
Blog bot is offline
Blog bot
Участник
 
25,643 / 848 (80) +++++++
Регистрация: 28.10.2006
Gareth Tucker: Defaulting a Lookup field via a REST query at Form Load
Источник: http://gtcrm.wordpress.com/2011/08/2...-at-form-load/
==============

Here’s some sample code that demonstrates how to dynamically determine the GUID of a related record and use that to default a lookup field on a CRM form on form load.

In this example I have a dummy Contact record called “new contact” which I want to default onto the Phone Call form each time a new Phone Call record is created. 

i.e when I click New Phone Call on the ribbon…



…. I want to see this:



note: I have also re-configured the Phone Call entity’s Direction field so that “Incoming” is the default.  The idea being that the user is launching the Phone Call form to record an incoming call from an unknown caller.

Defaulting in a dummy Contact may some an unusual scenario but it is not uncommon to utilise a dummy record when dealing with anonymous callers or when wanting to defer the collection of contact details until later in the process.   In a Call Centre environment for example you will not achieve desired efficiencies if you except having to manually create new Contact records before being able to create Phone Calls, Cases, Opportunities, etc or before being able to convert Phone Calls to Cases or Opportunities (I expand on this Call Centre scenario in my next post).

Anyway, here’s how to make this work…

There are 2 parts to this.  Firstly, we need to find out the GUID of the Contact record that we want to default on to our Phone Call.   You could figure this out manually and then hardcode the GUID but then your code will not be transportable across environments.   Instead in this example I have hardcoded only the name of the contact (we can easily create this Contact in each environment, it’s just data).  My dummy Contact is called “new contact” and I use the REST oData endpoint to locate that record’s GUID by searching on that name (An alternative approach would be to  store the GUID in a configuration entity and then use REST to query for the GUID from there, however the same coding approach applies).   And  then secondly, once we know the GUID it’s a relatively simple matter of doing a SetValue to populate the field on the form.

Here’s the jscript:

// Set lookup value of a field

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);

}

}

 

function GetDefaultContactGUID() {

 

if (Xrm.Page.ui.getFormType() == 1) {

// Get the CRM URL

var serverUrl = Xrm.Page.context.getServerUrl();

 

// Cater for URL differences between on premise and online

if (serverUrl.match(/\/$/)) {

serverUrl = serverUrl.substring(0, serverUrl.length - 1);

}

 

// Specify the ODATA end point (this is the same for all CRM 2011 implementations)

var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

 

// Specify the ODATA entity collection (this needs to be specific to your entity)

var ODATA_EntityCollection = "/ContactSet";

 

// Specify the ODATA filter

var ODATA_Query = "?$select=ContactId&$filter=FullName%20eq%20\'new%20contact\'&$top=1";

 

// Build the URL

var ODATA_Final_url = serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + ODATA_Query;

 

//Calls the REST endpoint

$.ajax({

type: "GET",

contentType: "application/json; charset=utf-8",

datatype: "json",

url: ODATA_Final_url,

 

beforeSend: function (XMLHttpRequest) {

//Specifying this header ensures that the results will be returned as JSON.

XMLHttpRequest.setRequestHeader("Accept", "application/json");

},

success: function (data, textStatus, XmlHttpRequest) {

//This function will trigger asynchronously if the Retrieve was successful

SetLookupValue("from", data.d.results[0].ContactId, "new contact", "contact");

},

error: function (XmlHttpRequest, textStatus, errorThrown) {

//This function will trigger asynchronously if the Retrieve returned an error

alert("ajax call failed");

}

});

}

}
The code snippet above contains 2 functions.  The “SetLookupValue” function is used to default the lookup field.  It is called by the 2nd function “GetDefaultContactGUID” which is where the REST query is constructed.

To deploy the above you need to load it into a jscript web resource and then reference that web resource on the Phone Call form and add a call in the Phone Call’s On Load event to the GetDefaultContactGUID function.   You will also need to upload json and jquery supporting  web resources and make sure they are specified in the order shown below:

 

If you’re not sure what I’m talking about when I mention json and jquery web resources have a read of this earlier post.

That’s it, the code is well commented so have a read of that to understand the syntax. 

A solution file containing the above web resources and minor change to the Phone Call entity is available here for download.   Hope this helps someone.

G.





Источник: http://gtcrm.wordpress.com/2011/08/2...-at-form-load/
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
Gareth Tucker: Quick Create Contact from the Phone Call Form Blog bot Dynamics CRM: Blogs 0 23.08.2011 12:11
Preston.Larimer: Adding a custom lookup to a form control Blog bot DAX Blogs 0 15.06.2011 03:25
Gareth Tucker: ‘Sharing’ Secured Fields in CRM 2011 Blog bot Dynamics CRM: Blogs 0 19.05.2011 23:13
CRM DE LA CREME! Some more useful javascripts for MS CRM Blog bot Dynamics CRM: Blogs 0 04.05.2010 11:05
Kashperuk Ivan: Lookup form returning more than one value Blog bot DAX Blogs 0 29.01.2010 18:05

Ваши права в разделе
Вы не можете создавать новые темы
Вы не можете отвечать в темах
Вы не можете прикреплять вложения
Вы не можете редактировать свои сообщения

BB коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 13:38.