-
Notifications
You must be signed in to change notification settings - Fork 37
/
index.ts
343 lines (286 loc) · 11.6 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
import {IInputs, IOutputs} from "./generated/ManifestTypes";
import { Select2 } from "select2";
import * as $ from 'jquery';
import "./scripts/select2.min.js";
declare var Xrm: any;
class DataAction{
guid : string;
associate: boolean;
}
class NToNData{
len : string;
ida : string;
na : string;
re : string;
rn : string;
actions : DataAction[];
}
export class NToNMultiSelect implements ComponentFramework.StandardControl<IInputs, IOutputs> {
private contextObj: ComponentFramework.Context<IInputs>;
// Div element created as part of this control's main container
private mainContainer: HTMLSelectElement;
private selectedItems: string[] = [];
private _relData : NToNData;
private _linkedEntityName: string;
private _relationshipEntity: string;
private _relationshipName: string;
private _idAttribute: string;
private _nameAttribute: string;
private _linkedEntityCollectionName: string;
private _mainEntityCollectionName: string;
private _entityMetadataSuccessCallback: any;
private _linkedEntityMetadataSuccessCallback: any;
private _relationshipSuccessCallback: any;
private _successCallback : any;
private _ctrlId : string;
private _notifyOutputChanged: () => void;
/**
* Empty constructor.
*/
constructor()
{
}
public S4() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
public newGuid(){
var result : string = (this.S4() + this.S4() + "-" + this.S4() + "-4" + this.S4().substr(0,3) + "-" + this.S4() + "-" + this.S4() + this.S4() + this.S4()).toLowerCase();
return result;
}
// then to call it, plus stitch in '4' in the third group
/**
* Used to initialize the control instance. Controls can kick off remote server calls and other initialization actions here.
* Data-set values are not initialized here, use updateView.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to property names defined in the manifest, as well as utility functions.
* @param notifyOutputChanged A callback method to alert the framework that the control has new outputs ready to be retrieved asynchronously.
* @param state A piece of data that persists in one session for a single user. Can be set at any point in a controls life cycle by calling 'setControlState' in the Mode interface.
* @param container If a control is marked control-type='standard', it will receive an empty div element within which it can render its content.
*/
public init(context: ComponentFramework.Context<IInputs>, notifyOutputChanged: () => void, state: ComponentFramework.Dictionary, container:HTMLDivElement)
{
this.contextObj = context;
this._ctrlId = this.newGuid();
this._relData = new NToNData();
this._relData.actions = [];
debugger;
if(context.parameters.linkedEntityName.raw != null){
this._linkedEntityName = context.parameters.linkedEntityName.raw;
this._relData.len = this._linkedEntityName;
}
if(context.parameters.idAttribute.raw != null){
this._idAttribute = context.parameters.idAttribute.raw;
this._relData.ida = this._idAttribute;
}
if(context.parameters.nameAttribute.raw != null){
this._nameAttribute = context.parameters.nameAttribute.raw;
this._relData.na = this._nameAttribute;
}
if(context.parameters.relationshipEntity.raw != null){
this._relationshipEntity = context.parameters.relationshipEntity.raw;
this._relData.re = this._relationshipEntity;
}
if(context.parameters.relationshipName.raw != null){
this._relationshipName = context.parameters.relationshipName.raw;
this._relData.rn = this._relationshipName;
}
// Need to track container resize so that control could get the available width. The available height won't be provided even this is true
context.mode.trackContainerResize(true);
// Create main table container div.
this.mainContainer = document.createElement("select");
this.mainContainer.id = this._ctrlId;
this.mainContainer.classList.add("js-example-basic-multiple");
this.mainContainer.multiple = true;
this.mainContainer.name = "states[]";
container.appendChild(this.mainContainer);
this._entityMetadataSuccessCallback = this.entityMetadataSuccessCallback.bind(this);
this._linkedEntityMetadataSuccessCallback = this.linkedEntityMetadataSuccessCallback.bind(this);
this._relationshipSuccessCallback = this.relationshipSuccessCallback.bind(this);
this._successCallback = this.successCallback.bind(this);
this._notifyOutputChanged = notifyOutputChanged;
(<any>Xrm).Utility.getEntityMetadata((<any>this.contextObj).page.entityTypeName,[]).then(this._entityMetadataSuccessCallback, this.errorCallback);
(<any>Xrm).Utility.getEntityMetadata(this._linkedEntityName,[]).then(this._linkedEntityMetadataSuccessCallback, this.errorCallback);
//(<any>Xrm).WebApi.retrieveMultipleRecords(this._relationshipEntity, "?$filter="+ (<any>this.contextObj).page.entityTypeName+"id eq " + (<any>this.contextObj).page.entityId, 5000).then(this._relationshipSuccessCallback, this.errorCallback);
if((<any>this.contextObj).page.entityId != null
&& (<any>this.contextObj).page.entityId != "00000000-0000-0000-0000-000000000000")
{
this.contextObj.webAPI.retrieveMultipleRecords(this._relationshipEntity, "?$filter="+ (<any>this.contextObj).page.entityTypeName+"id eq " + (<any>this.contextObj).page.entityId, 5000).then(this._relationshipSuccessCallback, this.errorCallback);
}
else{
this.relationshipSuccessCallback(null);
}
var thisVar : any;
thisVar = this;
$(document).ready(function() {
$('#'+ thisVar._ctrlId).select2().on('select2:select', function (e) {
var data = e.params.data;
thisVar.selectAction("select", data.id);
}).on('select2:unselect', function (e) {
var data = e.params.data;
thisVar.selectAction("unselect", data.id);
});
});
}
public entityMetadataSuccessCallback(value: any) : void | PromiseLike<void>
{
this._mainEntityCollectionName = value.EntitySetName;
}
public linkedEntityMetadataSuccessCallback(value: any) : void | PromiseLike<void>
{
this._linkedEntityCollectionName = value.EntitySetName;
}
public addOptions(value: any)
{
for(var i in value.entities)
{
var current : any = value.entities[i];
var checked = this.selectedItems.indexOf(<string>current[this._idAttribute]) > -1;
var newOption = new Option(current[this._nameAttribute], current[this._idAttribute], checked, checked);
$('#'+ this._ctrlId).append(newOption);
/*
var option = document.createElement("option");
option.value = current[this._idAttribute];
option.text = current[this._nameAttribute];
this.mainContainer.options.add(option);
*/
}
/*
var thisVar : any = this;
setTimeout(function(){
for(var si in thisVar.selectedItems){
var sel : any = thisVar.selectedItems[si];
$('#'+ thisVar._ctrlId).val(sel);
}
}, 200);
*/
}
public successCallback(value: any) : void | PromiseLike<void>
{
this.addOptions(value);
//this.initTree();
}
public relationshipSuccessCallback(value: any) : void | PromiseLike<void>
{
if(value != null)
{
for(var i in value.entities)
{
this.selectedItems.push(value.entities[i][this._idAttribute]);
}
}
this.contextObj.webAPI.retrieveMultipleRecords(this._linkedEntityName, "?$orderby=" + this._nameAttribute + " asc", 5000).then(this._successCallback, this.errorCallback);
}
public errorCallback(value: any)
{
alert(value);
}
/**
* Called when any value in the property bag has changed. This includes field values, data-sets, global values such as container height and width, offline status, control metadata values such as label, visible, etc.
* @param context The entire property bag available to control via Context Object; It contains values as set up by the customizer mapped to names defined in the manifest, as well as utility functions
*/
public updateView(context: ComponentFramework.Context<IInputs>): void
{
// Add code to update control view
}
/**
* It is called by the framework prior to a control receiving new data.
* @returns an object based on nomenclature defined in manifest, expecting object[s] for property marked as “bound” or “output”
*/
public getOutputs(): IOutputs
{
return {
value: "NTONDATA:"+JSON.stringify(this._relData)
};
}
/**
* Called when the control is to be removed from the DOM tree. Controls should use this call for cleanup.
* i.e. cancelling any pending remote calls, removing listeners, etc.
*/
public destroy(): void
{
// Add code to cleanup control if necessary
}
public selectAction(action : string, id : string)
{
/*
function (e: any, data: any) {
ProcessClick(
alert("Checked: " + data.node.id);
alert("Parent: " + data.node.parent);
//alert(JSON.stringify(data));
}
*/
if((<any>this.contextObj).page.entityId == null
|| (<any>this.contextObj).page.entityId == "00000000-0000-0000-0000-000000000000")
{
if(action == "select")
{
debugger;
var act = new DataAction();
act.associate = true;
act.guid = id;
this._relData.actions.push(act);
}
else{
for(var i=0; i < this._relData.actions.length; i++)
{
var act = this._relData.actions[i];
if(act.guid == id){
this._relData.actions.splice(i,1);
break;
}
}
}
this._notifyOutputChanged();
}
else{
var url: string = (<any>Xrm).Utility.getGlobalContext().getClientUrl();
var recordUrl: string = url + "/api/data/v9.1/"+ this._mainEntityCollectionName + "(" + (<any>this.contextObj).page.entityId + ")";
if(action == "select")
{
//See himbap samples here: http://himbap.com/blog/?p=2063
var associate = {
"@odata.id": recordUrl
};
var req = new XMLHttpRequest();
req.open("POST", url + "/api/data/v9.1/"+ this._linkedEntityCollectionName +"(" + id + ")/" + this._relationshipName + "/$ref", true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function() {
if (this.readyState == 4 /* complete */ ) {
req.onreadystatechange = null;
if (this.status == 204) {
//alert('Record Associated');
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send(JSON.stringify(associate));
}
else if(action == "unselect")
{
var req = new XMLHttpRequest();
req.open("DELETE",url + "/api/data/v9.1/"+ this._linkedEntityCollectionName +"(" + id + ")/" + this._relationshipName + "/$ref"+"?$id="+recordUrl, true);
req.setRequestHeader("Accept", "application/json");
req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
req.setRequestHeader("OData-MaxVersion", "4.0");
req.setRequestHeader("OData-Version", "4.0");
req.onreadystatechange = function() {
if (this.readyState == 4 /* complete */ ) {
req.onreadystatechange = null;
if (this.status == 204) {
//alert('Record Disassociated');
} else {
var error = JSON.parse(this.response).error;
alert(error.message);
}
}
};
req.send();
}
}
}
}