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

 
 
Опции темы Поиск в этой теме Опции просмотра
Старый 11.10.2009, 05:23   #1  
Blog bot is offline
Blog bot
Участник
 
25,475 / 846 (79) +++++++
Регистрация: 28.10.2006
mscrm4ever: CRM 4.0 cloning using entity mapping
Источник: http://mscrm4ever.blogspot.com/2009/...y-mapping.html
==============






In the past I wrote a few posts about cloning an entity using client side scripting. Most of the posts implemented complex script especially to non developers. I wanted to show you a simple cloning technique that leverages CRM built in features and can also work for CRM online.


The benefits of using this technique are:
1. Gain full control over which attributes are cloned
2. Ability to change which attributes are cloned without adding / changing your code.
3. Usage of a very simple script that does not need to be changed when reused.
4. Ability to easily track the parent record from which the cloned entity originated.


Following is the list of built in CRM features I am going to utilize in the post:
1. Creation of CRM form toolbar button
2. Creation of entity relationship.
3. Creation of mapping between related entities.
4. Adding simple script to the cloned entity onload handler.


So how can we actually make the above features work to our advantage. The main feature that lies in the heart of this technique is the ability to create a self referencing relationship between the an entity to itself and use the mapping wizard to tell CRM which attributes we what to pass from the parent record. Once we have that all that remains is to understand how CRM uses the mapping on the client side much like when you create a child contact record from within an account from.


If you take a close look at the URL that is used by CRM when you create a child related record you’ll notice that the URL uses a specific format that tells CRM what is the parent record id and type. Once you learn how to replicate this behavior you’re half way implementing this solution.
The following script which you’ll eventually need to paste in the entity onload event handler shows how to construct the child record or in our case the cloned record url:



Clone = function()
{
var cloneUrl = location.pathname + "?";
cloneUrl += "_CreateFromType=" + crmForm.ObjectTypeCode +
cloneUrl += "&_CreateFromId=" + crmForm.ObjectId +
cloneUrl += "&etc=" + crmForm.ObjectTypeCode + "#";

var cloneFeatures = 'toolbars=0,status=1,width=' + document.body.offsetWidth + "height=" + document.body.offsetHeight;

window.open(cloneUrl,'',cloneFeatures);
}



Once we have the script in place we need to add a toolbar button that will fire the actual cloning process.
Following is a sample clone button xml which you should add to your isv.config



















Next you’ll need to create a self referencing relationship. To do that open the entity customization and select 1:N relationship. Then select create new relationship. Inside the relationship form choose the same entity on both sides of the relationship. You should select not to display the left navigation link. The bellow image encapsulates the process of creating the self referencing relationship.





Once the relationship is saved you’ll see a mapping link on the relationship form. Select the mapping link to open the mapping wizard.
Add as much mapping as required. Before you publish the entity consider the final step.





Finally, if you wish to track the originating record you only need to add the entity lookup (parent test in this case) that was created as a result of the self referencing relationship. You can also set the lookup field as read only so users can’t change it manually.





That’s it! publish your entity and you’re done.


Источник: http://mscrm4ever.blogspot.com/2009/...y-mapping.html
__________________
Расскажите о новых и интересных блогах по Microsoft Dynamics, напишите личное сообщение администратору.
Старый 12.10.2009, 12:10   #2  
Артем Enot Грунин is offline
Артем Enot Грунин
Moderator
Аватар для Артем Enot Грунин
MCBMSS
Злыдни
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,912 / 623 (28) +++++++
Регистрация: 16.08.2007
Адрес: Пермь!
Записей в блоге: 151
Круто. Просто. Гениально.
__________________
http://fixrm.wordpress.com, снятие/наведение порчи. Быстро, дорого, гарантия.

MS Certified Dirty Magic Professional
Старый 12.10.2009, 12:16   #3  
a33ik is offline
a33ik
Чайный пьяница
Аватар для a33ik
MCP
MCBMSS
Злыдни
Соотечественники
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,243 / 896 (36) +++++++
Регистрация: 02.07.2008
Адрес: Greenville, SC
За то MVP и дают. Ади порожняк не гонит
__________________
Эмо разработчик, сначала пишу код, потом плачу над его несовершенством.

Подписывайтесь на мой блог, twitter и YouTube канал.
Пользуйтесь моим Ultimate Workflow Toolkit
Старый 23.08.2010, 16:47   #4  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
Что-то фокус не удался.. Я так понял что фокус основан на базовой возможности клонировать сущность.. Хотя я не слышал о стандартной функции клонироваия((. Я взял стандартную сущность account.. Сделал кнопку клоне.. На неё повесил скрипт.. Немного подрадактировал его...
Код:
var cloneUrl  = location.pathname + "?";  
cloneUrl += "_CreateFromType=" + crmForm.ObjectTypeCode ;   
cloneUrl += "&_CreateFromId=" + crmForm.ObjectId ;   
cloneUrl += "&etc=" + crmForm.ObjectTypeCode + "#";  
          
    var cloneFeatures = "toolbars=0,status=1,width=" + document.body.offsetWidth + "height=" + document.body.offsetHeight;   
      
    window.open(cloneUrl,'',cloneFeatures);
Потому как не правльный синтаксис был.
Дальнейшие действия вообще не понятны. Зачем создавать это отношение к самому себе? В общем создал я это отношение... В приложении рисунок.. Потом мапинг..я так понял для переноса данных.
В общем результат этого ошибка


Exception of type 'System.Web.HttpUnhandledException' was thrown.

Full Stack:
[InvalidOperationException: CRM Parameter Filter - Invalid parameter 'etc=1' in Request.QueryString on page /MicrosoftCRM/sfa/accts/edit.aspx
The raw request was 'GET /MicrosoftCRM/sfa/accts/edit.aspx?_CreateFromType=1&_CreateFromId={D84D44AD-36D0-DC11-AA32-0003FF33509E}&etc=1' called from .]
at Microsoft.Crm.Application.ParameterFilter.ValidateParameter(Page page, ArrayList parameterCollection, String key, String value, String collectionName, EntityType pageEntityType)
at Microsoft.Crm.Application.ParameterFilter.ValidateParameters(Page page, EntityType pageEntityType, Boolean alwaysEnableParameterChecking)
at Microsoft.Crm.Application.ParameterFilter.ValidateParameters(Page page, EntityType pageEntityType)
at Microsoft.Crm.Application.Controls.AppPage.ValidatePageParameters()
at Microsoft.Crm.Application.Controls.AppPage.OnInit(EventArgs e)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

[HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown.]
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context)
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at ASP.microsoftcrm_sfa_accts_edit_aspx.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)



Other Message:

Error Number:

Source File:
Not available

Line Number:
Not available


Date: 08-23-2010

Time: 05:45:24

Server: localhost


Request URL:
http://localhost:5555/MicrosoftCRM/sfa/accts/edit.aspx?_CreateFromType=1&_CreateFromId={D84D44AD-36D0-DC11-AA32-0003FF33509E}&etc=1
Миниатюры
Нажмите на изображение для увеличения
Название: ffff.jpg
Просмотров: 445
Размер:	71.6 Кб
ID:	6069  
Старый 23.08.2010, 17:23   #5  
Kipetcoff is offline
Kipetcoff
Участник
 
136 / 16 (1) ++
Регистрация: 20.05.2009
Адрес: Санкт-Петербург
До меня кажется дошло..это из-за того что я использую account, я попробовал на кустомной своей сущности и рабтает. Только я думал он будет создавать сразу сущность, так это не мой случай, мне нужно сразу создавать копию.
Старый 23.08.2010, 18:53   #6  
Артем Enot Грунин is offline
Артем Enot Грунин
Moderator
Аватар для Артем Enot Грунин
MCBMSS
Злыдни
Most Valuable Professional
Лучший по профессии 2017
Лучший по профессии 2015
Лучший по профессии 2014
Лучший по профессии AXAWARD 2013
Лучший по профессии 2011
Лучший по профессии 2009
 
3,912 / 623 (28) +++++++
Регистрация: 16.08.2007
Адрес: Пермь!
Записей в блоге: 151
В этом подходе используется так называемое "сопоставление" отношений. Когда дочерняя сущность создается в контексте родительской (например из связанного представления на форме), то система автоматически заполняет некоторые поля - те которые участвуют в мапировании. Автоматического сохранения записи при этом не происходит (хотя это можно исправить одной лишней строчной кода).
Вообще этот механизм используется для облегчения ввода данных, однако нашлось и вот такое нетривиальное его применение. Автор поста не из тех людей, кто может позволить себе публиковать что-то неработающее, так что внимательнее ищите ошибки у себя, а не у него. С системными объектами данный подход тоже работает.
__________________
http://fixrm.wordpress.com, снятие/наведение порчи. Быстро, дорого, гарантия.

MS Certified Dirty Magic Professional
 

Похожие темы
Тема Автор Раздел Ответов Посл. сообщение
CRM DE LA CREME! Configuring Microsoft Dynamics CRM 4.0 for Internet-facing deployment Blog bot Dynamics CRM: Blogs 0 18.08.2009 11:05
CRMScape: MS CRM 4.0 Entity Mapping and Hidden Mappings Blog bot Dynamics CRM: Blogs 0 13.08.2009 15:05
mscrm4ever: CRM 4.0 Finding Entity URL Blog bot Dynamics CRM: Blogs 1 30.05.2009 18:59
mscrm4ever: CRM 4.0 Using attribute mapping in code Blog bot Dynamics CRM: Blogs 0 03.05.2009 16:05
Microsoft Dynamics CRM Team Blog: List Web Part for Microsoft Dynamics CRM 4.0 Deployment Scenarios Blog bot Dynamics CRM: Blogs 0 30.01.2009 22:05
Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

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

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

Рейтинг@Mail.ru
Часовой пояс GMT +3, время: 10:12.
Powered by vBulletin® v3.8.5. Перевод: zCarot
Контактная информация, Реклама.