Reputation: 1305
I have the following js script that works in ms crm on FormLoad event.
function showForm() {
if (Xrm.Page.ui.getFormType() == 2) {
Xrm.Page.ui.controls.get("pcrm_contactfield").setDisabled(true);
Xrm.Page.ui.controls.get("pcrm_privatefield").setDisabled(true);
return;
}
processField("contact", "pcrm_contactfield");
processField("pcrm_userconnection", "pcrm_privatefield");
var userName = '';
var lblUser = parent.document.getElementById('lblUserName');
if (lblUser != null)
if (typeof lblUser.innerText != "undefined")
userName = lblUser.innerText;
else
userName = lblUser.innerHTML;
else
userName = Xrm.Page.context.getUserName();
if (!Xrm.Page.data.entity.getId()) {
var userControl = Xrm.Page.getControl("pcrm_userid");
if (userControl) {
if (XrmServiceToolkit.Soap.IsCurrentUserRole("PCRM Connections Manager")) {
userControl.setDisabled(false);
} else {
var userAttribute = Xrm.Page.getAttribute("pcrm_userid");
var lookupValue = {
id: Xrm.Page.context.getUserId(),
entityType: "systemuser",
name: userName
};
userAttribute.setValue([lookupValue]);
userAttribute.setSubmitMode("always");
}
}
}
}
function processField(entityName, field)
{
SDK.Metadata.RetrieveEntity(SDK.Metadata.EntityFilters.Attributes, entityName, null, false,
function (entityMetadata) {
entityMetadata.Attributes.sort(function (a, b) {
if (a.LogicalName < b.LogicalName)
return -1;
if (a.LogicalName > b.LogicalName)
return 1;
return 0;
});
applySelect(field, entityMetadata.Attributes);
},
function () {
});
}
function applySelect(id, attributes) {
if (parent.document.getElementById(id + "_container"))
parent.document.getElementById(id + "_container").style.display = "none";
else if (parent.document.getElementById(id)) {
parent.document.getElementById(id).style.display = "none";
parent.document.getElementById(id + "_d").style.display.paddingLeft = "23px";
}
var selectControl = "<select style='width: 100%' id ='" + id + "_select' onchange='onChange(this, \"" + id + "\")'><option></option>";
var value = Xrm.Page.data.entity.attributes.get(id).getValue();
for (var i = 0; i < attributes.length; i++) {
if (attributes[i].IsPrimaryId || attributes[i].AttributeType == "Lookup" || attributes[i].DisplayName.LocalizedLabels.length == 0)
continue;
var logicalName = attributes[i].LogicalName;
if (logicalName == "createdon" || logicalName == "modifiedon" || logicalName == "importsequencenumber" ||
logicalName == "overriddencreatedon" || logicalName == "ownerid" || logicalName == "statecode" || logicalName == "statuscode" ||
logicalName == "timezoneruleversionnumber" || logicalName == "utcconversiontimezonecode")
continue;
selectControl += "<option" + (value == logicalName ? " selected" : "") + " value='" + logicalName + "'>" + logicalName + " (" + attributes[i].DisplayName.LocalizedLabels[0].Label + ")</option>";
}
selectControl += "</select>";
parent.document.getElementById(id + "_d").innerHTML += selectControl;
}
parent.onChange = function (control, field) {
Xrm.Page.data.entity.attributes.get(field).setValue(control.value);
}
Now I explain what he is doing. I have form and this js-code creates dynamically two <select>
elements. Also this code binds elements with some data. This functionality works in applySelect method.
It works without error. I can select some options, click "save" and create new record. This works asynchronously.
But an js error occurs when invoked another event that redirect to another page or refresh current page. This reproduced only in IE and I don't think that's it is feature or bug in MS CRM. Message from CRM looks like:
Microsoft Dynamics CRM Error Report Contents
<CrmScriptErrorReport>
<ReportVersion>1.0</ReportVersion>
<ScriptErrorDetails>
<Message>Unexpected call to method or property access.</Message>
<Line>0</Line>
<URL>/form/page.aspx?lcid=1033&themeId=f499443d-2082-4938-8842-e7ee62de9a23&tstamp=513281&updateTimeStamp=636096333533056238&userts=131191056966436445&ver=-703338019#etc=10007&extraqs=%3fetc%3d10007&pagemode=iframe&pagetype=entityrecord&counter=1474641000171</URL>
<PageURL>/form/page.aspx?lcid=1033&themeId=f499443d-2082-4938-8842-e7ee62de9a23&tstamp=513281&updateTimeStamp=636096333533056238&userts=131191056966436445&ver=-703338019#etc=10007&extraqs=%3fetc%3d10007&pagemode=iframe&pagetype=entityrecord&counter=1474641000171</PageURL>
<Function>anonymous(dirtyVisiblePropertyData){var$v_0=dirtyVisiblePropertyData.getKeys();for(var$v_1=0;$v_1<$v_0.length;$v_1++){var$v_2=$v_0[$v_1];if(IsNull(this.get_viewMap().get_item($v_2))){}else{try{this.get_viewMap().get_item($v_2).update(dirtyVisiblePropertyD</Function>
<FunctionRaw>function(dirtyVisiblePropertyData) {
var $v_0 = dirtyVisiblePropertyData.getKeys();
for (var $v_1 = 0; $v_1 < $v_0.length; $v_1++) {
var $v_2 = $v_0[$v_1];
if (IsNull(this.get_viewMap().get_item($v_2))) {
</FunctionRaw>
<CallStack>
<Function>anonymous(dirtyVisiblePropertyData){var$v_0=dirtyVisiblePropertyData.getKeys();for(var$v_1=0;$v_1<$v_0.length;$v_1++){var$v_2=$v_0[$v_1];if(IsNull(this.get_viewMap().get_item($v_2))){}else{try{this.get_viewMap().get_item($v_2).update(dirtyVisiblePropertyData.get_item($v_2));}catch($v_3){Mscrm.CrmDebug.fail(String.format('ExceptionencounteredupdatingUIelement{0}:{1}',$v_2,$v_3.message));catchError($v_3.message,window.location.href,0,true);}}}}</Function>
<Function>anonymous(){if(this.$9i_1){var$v_0=this.$4M_1;this.$4M_1=new(Mscrm.TurboForm.Control.TypedDictionary$1.$$(Mscrm.TurboForm.Control.PropertyBag))();this.ui.updateUI($v_0);}}</Function>
<Function>anonymous(){this.$AC_1++;var$v_0=null;if(!this.$9V_1){$v_0=Xrm.Internal.startMetricsStopwatch(String.format('UIUpdate{0}',this.$AC_1));$v_0.start();}this.$8M_1=false;for(var$v_1=0;$v_1<this.$1w_1.length;$v_1++){var$v_2=this.$1w_1[$v_1];if(!IsNull($v_2)){$v_2.flushVisibilityChanges();}}if($v_0){$v_0.stop();}}</Function>
<Function>tryCommitActiveControl(keepFocus)</Function>
<Function>anonymous(action,isAutoSave,sync,shouldPromptOnDataLoss,saveOptions,saveAsCompleted){var$v_0=jQueryApi.jQueryDeferredFactory.Deferred(Mscrm.TurboForm.Control.EntityDataDescriptor,Mscrm.ErrorInformation);if(this.$7C_1){$v_0.reject(Mscrm.ErrorInformation.createErrorInfo((-1).toString(),Mscrm.TurboForm.Control.ErrorCode.toString(-1),null));return$v_0.promise();}this.$7C_1=true;if(!isAutoSave){tryCommitActiveControl(true);}var$v_1=this.$F1_1(action,isAutoSave);sync=(IsNull(sync))?false:sync;sync=(IsNullOrEmptyString(action))?sync:true;shouldPromptOnDataLoss=(IsNull(shouldPromptOnDataLoss))?true:shouldPromptOnDataLoss;var$v_2=newMscrm.TurboForm.Control.Data.EntitySaveEventArgs($v_1);if(IsNull(isAutoSave)){isAutoSave=false;}var$v_3=this.get_isNew();this.$8n_1=isAutoSave;var$v_4=this.$JO_1(isAutoSave,$v_2);if($v_4.$14_0){var$v_5=Mscrm.TurboForm.Control.CommandService.get_instance().handleSaveForScheduledEntities(Xrm.Page.data.entity.getEntityName(),saveOptions,$v_1,$v_0);if($v_5){this.$7C_1=false;return$v_0.promise();}var$$t_H=this;var$v_6=function($p1_0){$$t_H.$II_1($p1_0,$v_3);$v_0.resolve($p1_0);$$t_H.$An_1(action,$v_2,isAutoSave,shouldPromptOnDataLoss);$$t_H.$Hx_1();};var$$t_I=this;var$v_7=function($p1_0){if(isGlobalQuickCreate()){var$v_8=newXrm.SaveErrorResponse($p1_0.get_errorCode(),$p1_0.get_description(),$p1_0.get_serializedException());Mscrm.GlobalQuickCreate.GlobalQuickCreateBehavior.executeCallbacksAssociatedWithGlobalQuickCreate('savefailure',$v_8);}$v_0.reject($p1_0);};this.$L_1.$8_1.removeState(16);if(this.$L_1.$8_1===Mscrm.TurboForm.Control.PageManager.get_instance().$M_1){Mscrm.TurboForm.Control.CommandService.get_instance().save(this,sync,action).then($v_6,$v_7);}else{Mscrm.TurboForm.Control.CommandService.get_instance().quickFormSave(this,saveAsCompleted).then($v_6,$v_7);}}else{if(isAutoSave){Mscrm.TurboForm.Control.CommandService.get_instance().handleAutoSaveInvalid();}if($v_4.$3w_0===14){$v_0.resolve();this.$An_1(action,$v_2,isAutoSave,shouldPromptOnDataLoss);}elseif($v_4.$3w_0===13){$v_0.reject(Mscrm.ErrorInformation.createErrorInfo(saveCanceledErrorCodeAsString(),'',''));this.$An_1(action,$v_2,isAutoSave,shouldPromptOnDataLoss);}else{$v_0.reject();}}this.$7C_1=false;return$v_0.promise();}</Function>
<Function>anonymous(action,isAutoSave){this.saveInternal(action,isAutoSave);}</Function>
<Function>anonymous(action){this.$1T_1.save(action);}</Function>
<Function>anonymous(saveMode){if(Mscrm.InternalUtilities._String.isNullOrWhiteSpace(saveMode))Xrm.Page.data.entity.save();elseXrm.Page.data.entity.save(saveMode)}</Function>
<Function>anonymous(form){if(Mscrm.RibbonActions.isRefreshForm())Mscrm.CommandBarActions.saveForm("");elseMscrm.RibbonActions.saveLegacyForm(form,"Save")}</Function>
<Function>anonymous($p0,$p1,$p2,$p3){try{var$v_0=Mscrm.CommandHandler.$JQ($p1);Mscrm.CrmHeader.setScriptFile(Mscrm.CrmUri.create($p1.trim()),true,null,$v_0);var$v_1=!$v_0?window:Mscrm.Utilities.getTurboFormCustomScriptWindow();$v_0&&Xrm.Internal.trace.logT(Mscrm.CommandHandler,$p1+"isbeingloadedintoturboformscriptmanager");for(var$v_2=$p0.split("."),$v_3=0;$v_3<$v_2.length;$v_3++)if($v_1)$v_1=$v_1[$v_2[$v_3]];if(!IsNull($v_1)&&typeof$v_1==="function"){var$v_4=this.$Fa_1($p2,$p3);return$v_1.apply(null,$v_4)}returnnull}catch($v_5){returnnull}}</Function>
<Function>anonymous($p0,$p1,$p2,$p3){var$v_0=this.getCommandDefinition($p0,$p1);if(IsNull($v_0)||IsNull($v_0.Actions))returnfalse;for(var$v_1=0;$v_1<$v_0.Actions.length;$v_1++){var$v_2=$v_0.Actions[$v_1];switch($v_2.ActionType){case2:this.$GX_1($v_2.Attributes);break;case3:var$v_3=$v_2.Attributes;this.$Ce_1($v_3.FunctionName,$v_3.Library,$v_2.Parameters,$p2);break;case1:this.$GY_1($v_2.Attributes,$v_2.Parameters);break}}returntrue}</Function>
<Function>anonymous($p0,$p1,$p2){var$v_0=this.parseCommandFromRibbon($p0),$v_1=this.$Ag_1($v_0.command,$v_0.entityLogicalName,$p1,$p2),$v_2=$p1;if(!IsNull($v_2)&&!isNullOrEmptyString($v_2.PopulationXML)&&!$v_2.SuppressCommandIncludes){var$v_3=null;if($v_0.entityContext==="Form"){var$v_4=$find("crmFormSelector");if($v_4)$v_3=$v_4.get_currentFormId()}$v_2.PopulationXML=this.$Iq_1($v_2.PopulationXML,$v_0.entityLogicalName,$v_3)}return$v_1}</Function>
<Function>anonymous(command,properties){if(this.isControlEnabled(command)){if(!properties)properties={};this.get_$50_2().handleCommand(command,properties,0)}}</Function>
<Function>anonymous($p0,$p1){if(!IsNull(this.ribbonData)){if(IsNull($p1))$p1={};$p1["SourceControlId"]=IsNull(this.id)?$p0.id:this.id;var$v_0=this.getAttribute("CommandValueId");if(!IsNull($v_0))$p1["CommandValueId"]=$v_0;this.get_commandBar().$CU_4(.5);try{this.ribbonData.executeCommand(this.command,$p1);this.$5K_0&&Mscrm.RibbonManager.get_$3T().$z_1.executeCommand(this.command,$p1)}finally{this.get_commandBar().$CW_4(true)}}}</Function>
<Function>anonymous($p0,$p1){this.executeCommand($p0,null)}</Function>
<Function>anonymous(domEvent){var$v_0=Mscrm.Utilities.getDomEventElement(domEvent,"LI"),$v_1=this.$1T_4[$v_0.id];if($v_1)$v_1.click($v_0,domEvent);elseif(this.$7Q_4($v_0.id)){window.self.CommandBarMoreMenuLoadStartTime=(newDate).getTime();this.$I0_4(domEvent);window.self.CommandBarMoreMenuLoadEndTime=(newDate).getTime()}}</Function>
<Function>anonymous(){returnb.apply(a,arguments)}</Function>
<Function>anonymous(b){returne.call(a,newSys.UI.DomEvent(b))}</Function>
</CallStack>
</ScriptErrorDetails>
<ClientInformation>
<BrowserUserAgent>Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; rv:11.0) like Gecko</BrowserUserAgent>
<BrowserLanguage>en-US</BrowserLanguage>
<SystemLanguage>ru-RU</SystemLanguage>
<UserLanguage>en-US</UserLanguage>
<ScreenResolution>1920x1080</ScreenResolution>
<ClientName>Web</ClientName>
<ClienState>Online</ClienState>
<ClientTime>2016-09-23T17:30:33</ClientTime>
</ClientInformation>
<ServerInformation>
<OrgLanguage>1033</OrgLanguage>
<OrgCulture>1033</OrgCulture>
<UserLanguage>1033</UserLanguage>
<UserCulture>1033</UserCulture>
<OrgID>{E5438BCF-087C-E611-80CA-000C29135D52}</OrgID>
<UserID>{6A82F1DF-087C-E611-80CA-000C29135D52}</UserID>
<CRMVersion>8.0.1.79</CRMVersion>
</ServerInformation>
</CrmScriptErrorReport>
What am I doing wrong? And how to fix it if possible?
Upvotes: 0
Views: 493
Reputation: 7918
Your code is tampering with the form's DOM, which is unsupported and should be avoided, as it can cause the form to behave in unpredictable ways and also can break when CRM is updated with Service Packs or new versions.
When you need a custom piece of HTML on your form, use an HTML web resource instead.
Upvotes: 1