CreateEntityLayoutView.js 46.7 KB
Newer Older
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
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define(['require',
    'backbone',
    'hbs!tmpl/entity/CreateEntityLayoutView_tmpl',
    'utils/Utils',
    'collection/VTagList',
    'collection/VEntityList',
    'models/VEntity',
    'modules/Modal',
    'utils/Messages',
    'moment',
    'utils/UrlLinks',
    'collection/VSearchList',
31
    'utils/Enums',
32 33 34
    'utils/Globals',
    'daterangepicker'
], function(require, Backbone, CreateEntityLayoutViewTmpl, Utils, VTagList, VEntityList, VEntity, Modal, Messages, moment, UrlLinks, VSearchList, Enums, Globals) {
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

    var CreateEntityLayoutView = Backbone.Marionette.LayoutView.extend(
        /** @lends CreateEntityLayoutView */
        {
            _viewName: 'CreateEntityLayoutView',

            template: CreateEntityLayoutViewTmpl,

            templateHelpers: function() {
                return {
                    guid: this.guid
                };
            },

            /** Layout sub regions */
            regions: {},

            /** ui selector cache */
            ui: {
                entityName: "[data-id='entityName']",
                entityList: "[data-id='entityList']",
                entityInputData: "[data-id='entityInputData']",
                toggleRequired: 'input[name="toggleRequired"]',
                assetName: "[data-id='assetName']",
59 60 61
                entityInput: "[data-id='entityInput']",
                entitySelectionBox: "[data-id='entitySelectionBox']",

62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
            },
            /** ui events hash */
            events: function() {
                var events = {};
                events["change " + this.ui.entityList] = "onEntityChange";
                events["change " + this.ui.toggleRequired] = function(e) {
                    this.requiredAllToggle(e.currentTarget.checked)
                };
                return events;
            },
            /**
             * intialize a new CreateEntityLayoutView Layout
             * @constructs
             */
            initialize: function(options) {
77
                _.extend(this, _.pick(options, 'guid', 'callback', 'showLoader', 'entityDefCollection', 'typeHeaders'));
78 79 80
                var that = this,
                    entityTitle, okLabel;
                this.selectStoreCollection = new Backbone.Collection();
81
                this.collection = new VEntityList();
82 83 84 85
                this.entityModel = new VEntity();
                if (this.guid) {
                    this.collection.modelAttrName = "createEntity"
                }
86
                this.asyncReferEntityCounter = 0;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
                this.required = true;
                if (this.guid) {
                    entityTitle = 'Edit entity';
                    okLabel = 'Update';
                } else {
                    entityTitle = 'Create entity';
                    okLabel = 'Create';
                }
                this.modal = new Modal({
                    title: entityTitle,
                    content: this,
                    cancelText: "Cancel",
                    okText: okLabel,
                    allowCancel: true,
                    okCloses: false,
102
                    width: '50%'
103
                }).open();
104
                this.modal.$el.find('button.ok').attr("disabled", true);
105
                this.modal.on('ok', function(e) {
106
                    that.modal.$el.find('button.ok').showButtonLoader();
107 108 109 110 111 112 113 114 115 116 117 118
                    that.okButton();
                });
                this.modal.on('closeModal', function() {
                    that.modal.trigger('cancel');
                });
            },
            bindEvents: function() {
                var that = this;
                this.listenTo(this.collection, "reset", function() {
                    this.entityCollectionList();
                }, this);
                this.listenTo(this.collection, 'error', function() {
119
                    this.hideLoader();
120
                }, this);
121 122 123 124 125 126 127 128
            },
            onRender: function() {
                this.bindEvents();
                if (!this.guid) {
                    this.bindRequiredField();
                }
                this.showLoader();
                this.fetchCollections();
129
                this.$('.toggleRequiredSwitch').hide();
130 131 132
            },
            bindRequiredField: function() {
                var that = this;
133
                this.ui.entityInputData.on("keyup change", "textarea", function(e) {
134
                    var value = this.value;
135 136 137 138 139 140 141 142 143 144 145 146 147
                    if (!value.length && $(this).hasClass('false')) {
                        $(this).removeClass('errorClass');
                        that.modal.$el.find('button.ok').prop("disabled", false);
                    } else {
                        try {
                            if (value && value.length) {
                                JSON.parse(value);
                                $(this).removeClass('errorClass');
                                that.modal.$el.find('button.ok').prop("disabled", false);
                            }
                        } catch (err) {
                            $(this).addClass('errorClass');
                            that.modal.$el.find('button.ok').prop("disabled", true);
148 149 150
                        }
                    }
                });
151

152
                this.ui.entityInputData.on('keyup change', 'input.true,select.true', function(e) {
153 154
                    if (this.value !== "") {
                        if ($(this).data('select2')) {
155
                            $(this).data('select2').$container.find('.select2-selection').removeClass("errorClass");
156 157
                        } else {
                            $(this).removeClass('errorClass');
158 159 160
                        }
                        if (that.ui.entityInputData.find('.errorClass').length === 0) {
                            that.modal.$el.find('button.ok').prop("disabled", false);
161 162
                        }
                    } else {
163
                        that.modal.$el.find('button.ok').prop("disabled", true);
164
                        if ($(this).data('select2')) {
165
                            $(this).data('select2').$container.find('.select2-selection').addClass("errorClass");
166 167 168 169 170
                        } else {
                            $(this).addClass('errorClass');
                        }
                    }
                });
171
            },
172 173
            bindNonRequiredField: function() {
                var that = this;
174
                this.ui.entityInputData.off('keyup change', 'input.false,select.false').on('keyup change', 'input.false,select.false', function(e) {
175 176 177 178 179
                    if (that.modal.$el.find('button.ok').prop('disabled') && that.ui.entityInputData.find('.errorClass').length === 0) {
                        that.modal.$el.find('button.ok').prop("disabled", false);
                    }
                });
            },
180 181 182 183 184
            decrementCounter: function(counter) {
                if (this[counter] > 0) {
                    --this[counter];
                }
            },
185 186
            fetchCollections: function() {
                if (this.guid) {
187
                    this.collection.url = UrlLinks.entitiesApiUrl({ guid: this.guid });
188 189
                    this.collection.fetch({ reset: true });
                } else {
190
                    this.entityCollectionList();
191 192 193 194 195 196 197 198 199
                }
            },
            entityCollectionList: function() {
                this.ui.entityList.empty();
                var that = this,
                    name = "",
                    value;
                if (this.guid) {
                    this.collection.each(function(val) {
200
                        name += Utils.getName(val.get("entity"));
201 202 203
                        that.entityData = val;
                    });
                    this.ui.assetName.html(name);
204 205 206 207 208 209 210 211 212 213 214
                    var referredEntities = this.entityData.get('referredEntities');
                    var attributes = this.entityData.get('entity').attributes;
                    _.map(_.keys(attributes), function(key) {
                        if (_.isObject(attributes[key])) {
                            var attrObj = attributes[key];
                            if (_.isObject(attrObj) && !_.isArray(attrObj)) {
                                attrObj = [attrObj];
                            }
                            _.each(attrObj, function(obj) {
                                if (obj.guid && !referredEntities[obj.guid]) {
                                    ++that.asyncReferEntityCounter;
215
                                    that.collection.url = UrlLinks.entitiesApiUrl({ guid: obj.guid });
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                                    that.collection.fetch({
                                        success: function(data, response) {
                                            referredEntities[obj.guid] = response.entity;
                                        },
                                        complete: function() {
                                            that.decrementCounter('asyncReferEntityCounter');
                                            if (that.asyncReferEntityCounter === 0) {
                                                that.onEntityChange(null, that.entityData);
                                            }
                                        },
                                        silent: true
                                    });
                                }
                            });
                        }
                    });
                    if (this.asyncReferEntityCounter === 0) {
                        this.onEntityChange(null, this.entityData);
                    }
235
                } else {
236
                    var str = '<option disabled="disabled" selected>--Select entity-type--</option>';
237
                    this.entityDefCollection.fullCollection.each(function(val) {
238
                        var name = Utils.getName(val.toJSON());
239
                        if (Globals.entityTypeConfList && name.indexOf("__") !== 0) {
240
                            if (_.isEmptyArray(Globals.entityTypeConfList)) {
241
                                str += '<option>' + name + '</option>';
242 243
                            } else {
                                if (_.contains(Globals.entityTypeConfList, val.get("name"))) {
244
                                    str += '<option>' + name + '</option>';
245 246 247
                                }
                            }
                        }
248 249
                    });
                    this.ui.entityList.html(str);
250
                    this.ui.entityList.select2({});
251
                    this.hideLoader();
252 253 254 255 256 257 258
                }
            },
            capitalize: function(string) {
                return string.charAt(0).toUpperCase() + string.slice(1);
            },
            requiredAllToggle: function(checked) {
                if (checked) {
259
                    this.ui.entityInputData.addClass('all').removeClass('required');
260 261
                    this.ui.entityInputData.find('div.true').show();
                    this.ui.entityInputData.find('fieldset div.true').show();
262
                    this.ui.entityInputData.find('fieldset').show();
263 264
                    this.required = false;
                } else {
265
                    this.ui.entityInputData.addClass('required').removeClass('all');
266 267 268 269 270
                    this.ui.entityInputData.find('fieldset').each(function() {
                        if (!$(this).find('div').hasClass('false')) {
                            $(this).hide();
                        }
                    });
271 272 273 274 275 276 277 278
                    this.ui.entityInputData.find('div.true').hide();
                    this.ui.entityInputData.find('fieldset div.true').hide();
                    this.required = true;
                }

            },
            onEntityChange: function(e, value) {
                var that = this,
279
                    typeName = value && value.get('entity') ? value.get('entity').typeName : null;
280 281 282
                if (!this.guid) {
                    this.showLoader();
                }
283 284 285
                this.ui.entityInputData.empty();
                if (typeName) {
                    this.collection.url = UrlLinks.entitiesDefApiUrl(typeName);
286
                } else if (e) {
287 288 289 290 291
                    this.collection.url = UrlLinks.entitiesDefApiUrl(e.target.value);
                    this.collection.modelAttrName = 'attributeDefs';
                }
                this.collection.fetch({
                    success: function(model, data) {
292
                        that.supuertypeFlag = 0;
293 294 295
                        that.subAttributeData(data)
                    },
                    complete: function() {
296
                        //that.initilizeElements();
297 298 299 300
                    },
                    silent: true
                });
            },
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 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
            renderAttribute: function(object) {
                var that = this,
                    visitedAttr = {},
                    attributeObj = object.attributeDefs,
                    isAllAttributeOptinal = true,
                    isAllRelationshipAttributeOptinal = true,
                    attributeDefList = attributeObj.attributeDefs,
                    relationshipAttributeDefsList = attributeObj.relationshipAttributeDefs,
                    attributeHtml = "",
                    relationShipAttributeHtml = "",
                    fieldElemetHtml = '',
                    commonInput = function(object) {
                        var value = object.value,
                            containerHtml = '';
                        containerHtml += that.getContainer(object);
                        return containerHtml;
                    };
                if (attributeDefList.length || relationshipAttributeDefsList.length) {
                    _.each(attributeDefList, function(value) {
                        if (value.isOptional === false) {
                            isAllAttributeOptinal = false;
                        }
                        attributeHtml += commonInput({
                            "value": value,
                            "duplicateValue": false,
                            "isAttribute": true
                        });
                    });
                    _.each(relationshipAttributeDefsList, function(value) {
                        if (value.isOptional === false) {
                            isAllRelationshipAttributeOptinal = false;
                        }
                        if (visitedAttr[value.name] === null) {
                            // on second visited set it to true;and now onwords ignore if same value come.
                            var duplicateRelationship = _.where(relationshipAttributeDefsList, { name: value.name });
                            var str = '<option value="">--Select a Relationship Type--</option>';
                            _.each(duplicateRelationship, function(val, index, list) {
                                str += '<option>' + _.escape(val.relationshipTypeName) + '</option>';
                            });
                            var isOptional = value.isOptional;
                            visitedAttr[value.name] = '<div class="form-group"><select class="form-control row-margin-bottom entityInputBox ' + (value.isOptional === true ? "false" : "true") + '" data-for-key= "' + value.name + '"> ' + str + '</select></div>';
                        } else {
                            relationShipAttributeHtml += commonInput({
                                "value": value,
                                "duplicateValue": true,
                                "isRelation": true
                            });
                            // once visited set it to null;
                            visitedAttr[value.name] = null;
                        }
                    });
                    if (attributeHtml.length) {
                        fieldElemetHtml += that.getFieldElementContainer({
                            "htmlField": attributeHtml,
                            "attributeType": true,
                            "alloptional": isAllAttributeOptinal
                        });
                    }
                    if (relationShipAttributeHtml.length) {
                        fieldElemetHtml += that.getFieldElementContainer({
                            "htmlField": relationShipAttributeHtml,
                            "relationshipType": true,
                            "alloptional": isAllRelationshipAttributeOptinal
                        });
                    }
                    if (fieldElemetHtml.length) {
                        that.ui.entityInputData.append(fieldElemetHtml);
                        _.each(_.keys(visitedAttr), function(key) {
                            if (visitedAttr[key] === null) {
                                return;
                            }
                            var elFound = that.ui.entityInputData.find('[data-key="' + key + '"]');
373
                            elFound.prop('disabled', true);
374 375 376 377 378 379 380 381
                            elFound.parent().prepend(visitedAttr[key]);
                        });
                    } else {
                        fieldElemetHtml = "<h4 class='text-center'>Defination not found</h4>";
                        that.ui.entityInputData.append(fieldElemetHtml);
                    }

                }
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
                that.ui.entityInputData.find("select[data-for-key]").select2({}).on('change', function() {
                    var forKey = $(this).data('forKey'),
                        forKeyEl = null;
                    if (forKey && forKey.length) {
                        forKeyEl = that.ui.entityInputData.find('[data-key="' + forKey + '"]');
                        if (forKeyEl) {
                            if (this.value == "") {
                                forKeyEl.val(null).trigger('change');
                                forKeyEl.prop("disabled", true);
                            } else {
                                forKeyEl.prop("disabled", false);
                            }
                        }
                    }
                });
397 398
                return false;
            },
399 400 401
            subAttributeData: function(data) {
                var that = this,
                    attributeInput = "",
402
                    alloptional = false,
403 404 405 406 407 408 409 410 411 412
                    attributeDefs = Utils.getNestedSuperTypeObj({
                        seperateRelatioshipAttr: true,
                        attrMerge: true,
                        data: data,
                        collection: this.entityDefCollection
                    });
                if (attributeDefs && attributeDefs.relationshipAttributeDefs.length) {
                    attributeDefs.attributeDefs = _.filter(attributeDefs.attributeDefs, function(obj) {
                        if (_.find(attributeDefs.relationshipAttributeDefs, { name: obj.name }) === undefined) {
                            return true;
413
                        }
414 415
                    })
                }
416 417 418 419 420
                if (attributeDefs.attributeDefs.length || attributeDefs.relationshipAttributeDefs.length) {
                    this.$('.toggleRequiredSwitch').show();
                } else {
                    this.$('.toggleRequiredSwitch').hide();
                }
421 422 423
                //make a function call.
                this.renderAttribute({
                    attributeDefs: attributeDefs
424
                });
425

426 427 428 429 430
                if (this.required) {
                    this.ui.entityInputData.find('fieldset div.true').hide()
                    this.ui.entityInputData.find('div.true').hide();
                }
                if (!('placeholder' in HTMLInputElement.prototype)) {
431
                    this.ui.entityInputData.find("input,select,textarea").placeholder();
432
                }
433
                that.initilizeElements();
434 435 436
            },
            initilizeElements: function() {
                var that = this;
437
                this.$('input[data-type="date"]').each(function() {
438 439 440 441 442 443
                    if (!$(this).data('daterangepicker')) {
                        var dateObj = { "singleDatePicker": true, "showDropdowns": true };
                        if (that.guid) {
                            dateObj["startDate"] = this.value
                        }
                        $(this).daterangepicker(dateObj);
444
                    }
445 446 447 448 449 450 451 452
                });
                this.initializeValidation();
                if (this.ui.entityInputData.find('fieldset').length > 0 && this.ui.entityInputData.find('select.true,input.true').length === 0) {
                    this.requiredAllToggle(this.ui.entityInputData.find('select.true,input.true').length === 0);
                    if (!this.guid) {
                        // For create entity bind keyup for non-required field when all elements are optional
                        this.bindNonRequiredField();
                    }
453
                }
454 455 456 457 458 459 460 461
                this.$('select[data-type="boolean"]').each(function(value, key) {
                    var dataKey = $(key).data('key');
                    if (that.entityData) {
                        var setValue = that.entityData.get("entity").attributes[dataKey];
                        this.value = setValue;
                    }
                });
                this.addJsonSearchData();
462 463 464
            },
            initializeValidation: function() {
                // IE9 allow input type number
465
                var regex = /^[0-9]*((?=[^.]|$))?$/, // allow only numbers [0-9]
466 467 468 469 470 471 472 473
                    removeText = function(e, value) {
                        if (!regex.test(value)) {
                            var txtfld = e.currentTarget;
                            var newtxt = txtfld.value.slice(0, txtfld.value.length - 1);
                            txtfld.value = newtxt;
                        }
                    }
                this.$('input[data-type="int"],input[data-type="long"]').on('keydown', function(e) {
474
                    // allow only numbers [0-9]
475 476 477 478 479 480 481 482 483 484 485
                    if (!regex.test(e.currentTarget.value)) {
                        return false;
                    }
                });
                this.$('input[data-type="int"],input[data-type="long"]').on('paste', function(e) {
                    return false;
                });

                this.$('input[data-type="long"],input[data-type="int"]').on('keyup click', function(e) {
                    removeText(e, e.currentTarget.value);
                });
486

487
                this.$('input[data-type="date"]').on('hide.daterangepicker keydown', function(event) {
488
                    if (event.type) {
489
                        if (event.type == 'hide') {
490 491 492 493 494
                            this.blur();
                        } else if (event.type == 'keydown') {
                            return false;
                        }
                    }
495
                });
496
            },
497 498
            getContainer: function(object) {
                var value = object.value,
499
                    entityLabel = this.capitalize(_.escape(value.name));
500 501

                return '<div class=" row ' + value.isOptional + '"><span class="col-sm-3">' +
502
                    '<label><span class="' + (value.isOptional ? 'true' : 'false required') + '">' + entityLabel + '</span><span class="center-block ellipsis-with-margin text-gray" title="Data Type : ' + value.typeName + '">' + '(' + Utils.escapeHtml(value.typeName) + ')' + '</span></label></span>' +
503
                    '<span class="col-sm-9">' + (this.getElement(object)) +
504
                    '</input></span></div>';
505
            },
506 507 508 509 510 511 512
            getFieldElementContainer: function(object) {
                var htmlField = object.htmlField,
                    attributeType = object.attributeType ? object.attributeType : false,
                    relationshipType = object.relationshipType ? object.relationshipType : false,
                    alloptional = object.alloptional,
                    typeOfDefination = (relationshipType ? "Relationships" : "Attributes");
                return '<div class="attribute-dash-box ' + (alloptional ? "alloptional" : "") + ' "><span class="attribute-type-label">' + (typeOfDefination) + '</span>' + htmlField + '</div>';
513
            },
514 515 516 517 518
            getSelect: function(object) {
                var value = object.value,
                    entityValue = object.entityValue,
                    isAttribute = object.isAttribute,
                    isRelation = object.isRelation;
519
                if (value.typeName === "boolean") {
520 521 522 523 524 525
                    return '<select class="form-control row-margin-bottom ' + (value.isOptional === true ? "false" : "true") +
                        '" data-type="' + value.typeName +
                        '" data-attribute="' + isAttribute +
                        '" data-relation="' + isRelation +
                        '" data-key="' + value.name +
                        '" data-id="entityInput">' +
526
                        '<option value="">--Select true or false--</option><option value="true">true</option>' +
527 528 529 530 531 532 533 534
                        '<option value="false">false</option></select>';
                } else {
                    var splitTypeName = value.typeName.split("<");
                    if (splitTypeName.length > 1) {
                        splitTypeName = splitTypeName[1].split(">")[0];
                    } else {
                        splitTypeName = value.typeName;
                    }
535 536 537 538 539 540
                    return '<select class="form-control row-margin-bottom entityInputBox ' + (value.isOptional === true ? "false" : "true") +
                        '" data-type="' + value.typeName +
                        '" data-attribute="' + isAttribute +
                        '" data-relation="' + isRelation +
                        '" data-key="' + value.name +
                        '" data-id="entitySelectData" data-queryData="' + splitTypeName + '">' + (this.guid ? entityValue : "") + '</select>';
541 542 543
                }

            },
544 545 546 547 548 549
            getTextArea: function(object) {
                var value = object.value,
                    setValue = object.entityValue,
                    isAttribute = object.isAttribute,
                    isRelation = object.isRelation,
                    structType = object.structType;
550 551 552 553 554 555 556 557 558
                try {
                    if (structType && entityValue && entityValue.length) {
                        var parseValue = JSON.parse(entityValue);
                        if (_.isObject(parseValue) && !_.isArray(parseValue) && parseValue.attributes) {
                            setValue = JSON.stringify(parseValue.attributes);
                        }
                    }
                } catch (err) {}

559 560 561
                return '<textarea class="form-control entityInputBox ' + (value.isOptional === true ? "false" : "true") + '"' +
                    ' data-type="' + value.typeName + '"' +
                    ' data-key="' + value.name + '"' +
562 563
                    ' data-attribute="' + isAttribute + '"' +
                    ' data-relation="' + isRelation + '"' +
564
                    ' placeholder="' + value.name + '"' +
565 566
                    ' data-id="entityInput">' + setValue + '</textarea>';

567
            },
568 569 570 571 572
            getInput: function(object) {
                var value = object.value,
                    entityValue = object.entityValue,
                    isAttribute = object.isAttribute,
                    isRelation = object.isRelation;
573 574 575 576
                return '<input class="form-control entityInputBox ' + (value.isOptional === true ? "false" : "true") + '"' +
                    ' data-type="' + value.typeName + '"' +
                    ' value="' + entityValue + '"' +
                    ' data-key="' + value.name + '"' +
577 578
                    ' data-attribute="' + isAttribute + '"' +
                    ' data-relation="' + isRelation + '"' +
579 580 581
                    ' placeholder="' + value.name + '"' +
                    ' data-id="entityInput">';
            },
582 583 584 585 586
            getElement: function(object) {
                var value = object.value,
                    isAttribute = object.isAttribute,
                    isRelation = object.isRelation,
                    typeName = value.typeName,
587
                    entityValue = "";
588
                if (this.guid) {
589
                    var dataValue = this.entityData.get("entity").attributes[value.name];
590 591 592 593 594 595
                    if (_.isObject(dataValue)) {
                        entityValue = JSON.stringify(dataValue);
                    } else {
                        if (dataValue) {
                            entityValue = dataValue;
                        }
596 597 598 599 600 601
                        if (value.typeName === "date") {
                            if (dataValue) {
                                entityValue = moment(dataValue).format("MM/DD/YYYY");
                            } else {
                                entityValue = moment().format("MM/DD/YYYY");
                            }
602 603 604
                        }
                    }
                }
605
                if ((typeName && this.entityDefCollection.fullCollection.find({ name: typeName })) || typeName === "boolean" || typeName.indexOf("array") > -1) {
606 607 608 609 610 611 612
                    return this.getSelect({
                        "value": value,
                        "entityValue": entityValue,
                        "isAttribute": isAttribute,
                        "isRelation": isRelation

                    });
613
                } else if (typeName.indexOf("map") > -1) {
614 615 616 617 618 619 620
                    return this.getTextArea({
                        "value": value,
                        "entityValue": entityValue,
                        "isAttribute": isAttribute,
                        "isRelation": isRelation,
                        "structType": false
                    });
621
                } else {
622 623
                    var typeNameCategory = this.typeHeaders.fullCollection.findWhere({ name: typeName });
                    if (typeNameCategory && typeNameCategory.get('category') === 'STRUCT') {
624 625 626 627 628 629 630
                        return this.getTextArea({
                            "value": value,
                            "entityValue": entityValue,
                            "isAttribute": isAttribute,
                            "isRelation": isRelation,
                            "structType": true
                        });
631
                    } else {
632 633 634 635 636 637
                        return this.getInput({
                            "value": value,
                            "entityValue": entityValue,
                            "isAttribute": isAttribute,
                            "isRelation": isRelation,
                        });
638
                    }
639 640 641 642
                }
            },
            okButton: function() {
                var that = this;
643 644 645
                this.showLoader({
                    editVisiblityOfEntitySelectionBox: true
                });
646
                this.parentEntity = this.ui.entityList.val();
647 648 649
                var entityAttribute = {},
                    referredEntities = {},
                    relationshipAttribute = {};
650
                var extractValue = function(value, typeName) {
651 652 653
                    if (!value) {
                        return value;
                    }
654
                    if (_.isArray(value)) {
655 656 657 658
                        var parseData = [];
                        _.map(value, function(val) {
                            parseData.push({ 'guid': val, 'typeName': typeName });
                        });
659
                    } else {
660
                        var parseData = { 'guid': value, 'typeName': typeName };
661
                    }
662 663 664 665
                    return parseData;
                }
                try {
                    this.ui.entityInputData.find("input,select,textarea").each(function() {
666 667
                        var value = $(this).val(),
                            el = this;
668 669 670 671 672 673 674 675 676 677 678
                        if ($(this).val() && $(this).val().trim) {
                            value = $(this).val().trim();
                        }
                        if (this.nodeName === "TEXTAREA") {
                            try {
                                if (value && value.length) {
                                    JSON.parse(value);
                                    $(this).removeClass('errorClass');
                                }
                            } catch (err) {
                                throw new Error(err.message);
679 680 681
                                $(this).addClass('errorClass');
                            }
                        }
682 683 684 685
                        // validation
                        if ($(this).hasClass("true")) {
                            if (value == "" || value == undefined) {
                                if ($(this).data('select2')) {
686
                                    $(this).data('select2').$container.find('.select2-selection').addClass("errorClass")
687
                                } else {
688 689 690
                                    $(this).addClass('errorClass');
                                }
                                that.hideLoader();
691
                                that.modal.$el.find('button.ok').hideButtonLoader();
692 693 694 695
                                throw new Error("Please fill the required fields");
                                return;
                            }
                        }
696 697 698
                        var dataTypeEnitity = $(this).data('type'),
                            datakeyEntity = $(this).data('key'),
                            typeName = $(this).data('querydata'),
699 700 701 702
                            attribute = $(this).data('attribute') == 'undefined' ? false : true,
                            relation = $(this).data('relation') == 'undefined' ? false : true,
                            typeNameCategory = that.typeHeaders.fullCollection.findWhere({ name: dataTypeEnitity }),
                            val = null;
703 704 705
                        // Extract Data
                        if (dataTypeEnitity && datakeyEntity) {
                            if (that.entityDefCollection.fullCollection.find({ name: dataTypeEnitity })) {
706
                                val = extractValue(value, typeName);
707
                            } else if (dataTypeEnitity === 'date' || dataTypeEnitity === 'time') {
708
                                val = Date.parse(value);
709
                            } else if (dataTypeEnitity.indexOf("map") > -1 || (typeNameCategory && typeNameCategory.get('category') === 'STRUCT')) {
710 711 712
                                try {
                                    if (value && value.length) {
                                        parseData = JSON.parse(value);
713
                                        val = parseData;
714
                                    }
715 716 717 718 719 720
                                } catch (err) {
                                    $(this).addClass('errorClass');
                                    throw new Error(datakeyEntity + " : " + err.message);
                                    return;
                                }
                            } else if (dataTypeEnitity.indexOf("array") > -1 && dataTypeEnitity.indexOf("string") === -1) {
721
                                val = extractValue(value, typeName);
722 723 724
                            } else {
                                if (_.isString(value)) {
                                    if (value.length) {
725
                                        val = value;
726
                                    } else {
727
                                        val = null;
728
                                    }
729
                                } else {
730
                                    val = value;
731
                                }
732
                            }
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
                            if (attribute) {
                                entityAttribute[datakeyEntity] = val;
                            } else if (relation) {
                                relationshipAttribute[datakeyEntity] = val;
                            }
                        } else {
                            var dataRelEntity = $(this).data('forKey');
                            if (dataRelEntity && relationshipAttribute[dataRelEntity]) {
                                if (_.isArray(relationshipAttribute[dataRelEntity])) {
                                    _.each(relationshipAttribute[dataRelEntity], function(obj) {
                                        if (obj) {
                                            obj["relationshipType"] = $(el).val();
                                        }
                                    });
                                } else {
                                    relationshipAttribute[dataRelEntity]["relationshipType"] = $(this).val();
                                }

                            }
752
                        }
753 754
                    });
                    var entityJson = {
755 756
                        "entity": {
                            "typeName": (this.guid ? this.entityData.get("entity").typeName : this.parentEntity),
757 758
                            "attributes": entityAttribute,
                            "relationshipAttributes": relationshipAttribute,
759 760 761
                            "guid": (this.guid ? this.guid : -1)
                        },
                        "referredEntities": referredEntities
762
                    };
763
                    this.entityModel.createOreditEntity({
764
                        data: JSON.stringify(entityJson),
765
                        type: "POST",
766
                        success: function(model, response) {
767
                            that.modal.$el.find('button.ok').hideButtonLoader();
768
                            that.modal.close();
769
                            var msgType = that.guid ? 'editSuccessMessage' : 'addSuccessMessage';
770
                            Utils.notifySuccess({
771
                                content: "Entity " + Messages.getAbbreviationMsg(false, msgType)
772
                            });
773 774 775
                            if (that.guid && that.callback) {
                                that.callback();
                            } else {
776
                                if (model.mutatedEntities && model.mutatedEntities.CREATE && _.isArray(model.mutatedEntities.CREATE) && model.mutatedEntities.CREATE[0] && model.mutatedEntities.CREATE[0].guid) {
777 778 779 780 781
                                    Utils.setUrl({
                                        url: '#!/detailPage/' + (model.mutatedEntities.CREATE[0].guid),
                                        mergeBrowserUrl: false,
                                        trigger: true
                                    });
782 783
                                }
                            }
784 785
                        },
                        complete: function() {
786 787 788
                            that.hideLoader({
                                editVisiblityOfEntitySelectionBox: true
                            });
789
                            that.modal.$el.find('button.ok').hideButtonLoader();
790 791
                        }
                    });
792 793 794 795 796

                } catch (e) {
                    Utils.notifyError({
                        content: e.message
                    });
797 798 799
                    that.hideLoader({
                        editVisiblityOfEntitySelectionBox: true
                    });
800 801
                }
            },
802 803 804
            showLoader: function(options) {
                var editVisiblityOfEntitySelectionBox = options && options.editVisiblityOfEntitySelectionBox;
                this.$('.entityLoader').addClass('show');
805
                this.$('.entityInputData').hide();
806 807 808
                if (this.guid || editVisiblityOfEntitySelectionBox) {
                    this.ui.entitySelectionBox.hide();
                }
809
            },
810 811 812
            hideLoader: function(options) {
                var editVisiblityOfEntitySelectionBox = options && options.editVisiblityOfEntitySelectionBox
                this.$('.entityLoader').removeClass('show');
813
                this.$('.entityInputData').show();
814 815 816
                if (this.guid || editVisiblityOfEntitySelectionBox) {
                    this.ui.entitySelectionBox.show();
                }
817 818 819
                // To enable scroll after selecting value from select2.
                this.ui.entityList.select2('open');
                this.ui.entityList.select2('close');
820
            },
821
            addJsonSearchData: function() {
822 823 824 825 826 827 828 829 830
                var that = this;
                this.$('select[data-id="entitySelectData"]').each(function(value, key) {
                    var $this = $(this),
                        keyData = $(this).data("key"),
                        typeData = $(this).data("type"),
                        queryData = $(this).data("querydata"),
                        skip = $(this).data('skip'),
                        placeholderName = "Select a " + typeData + " from the dropdown list";
                    $this.attr("multiple", ($this.data('type').indexOf("array") === -1 ? false : true));
831

832 833 834 835
                    // Select Value.
                    if (that.guid) {
                        var dataValue = that.entityData.get("entity").attributes[keyData],
                            entities = that.entityData.get("entity").attributes,
836
                            relationshipType = that.entityData.get("entity").relationshipAttributes[keyData],
837 838 839 840 841 842 843 844 845 846 847 848 849 850
                            referredEntities = that.entityData.get("referredEntities"),
                            selectedValue = [],
                            select2Options = [];
                        if (dataValue) {
                            if (_.isObject(dataValue) && !_.isArray(dataValue)) {
                                dataValue = [dataValue];
                            }
                            _.each(dataValue, function(obj) {
                                if (_.isObject(obj) && obj.guid && referredEntities[obj.guid]) {
                                    var refEntiyFound = referredEntities[obj.guid];
                                    refEntiyFound['id'] = refEntiyFound.guid;
                                    if (!Enums.entityStateReadOnly[refEntiyFound.status]) {
                                        select2Options.push(refEntiyFound);
                                        selectedValue.push(refEntiyFound.guid);
851 852 853
                                    }
                                }
                            });
854 855 856 857 858 859
                            if (!_.isUndefined(relationshipType)) {
                                if (relationshipType && relationshipType.relationshipAttributes && relationshipType.relationshipAttributes.typeName) {
                                    that.$("select[data-for-key=" + keyData + "]").val(relationshipType.relationshipAttributes.typeName).trigger("change");
                                }

                            }
860 861
                        }

862 863 864 865 866 867 868
                        // Array of string.
                        if (selectedValue.length === 0 && dataValue && dataValue.length && ($this.data('querydata') === "string")) {
                            var str = "";
                            _.each(dataValue, function(obj) {
                                if (_.isString(obj)) {
                                    selectedValue.push(obj);
                                    str += '<option>' + _.escape(obj) + '</option>';
869
                                }
870 871 872
                            });
                            $this.html(str);
                        }
873

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
                    } else {
                        $this.val([]);
                    }
                    var select2Option = {
                        placeholder: placeholderName,
                        allowClear: true,
                        tags: ($this.data('querydata') == "string" ? true : false)
                    }
                    var getTypeAheadData = function(data, params) {
                        var dataList = data.entities,
                            foundOptions = [];
                        _.each(dataList, function(obj) {
                            if (obj) {
                                if (obj.guid) {
                                    obj['id'] = obj.guid;
                                }
                                foundOptions.push(obj);
891 892
                            }
                        });
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
                        return foundOptions;
                    }
                    if ($this.data('querydata') !== "string") {
                        _.extend(select2Option, {
                            ajax: {
                                url: UrlLinks.searchApiUrl('attribute'),
                                dataType: 'json',
                                delay: 250,
                                data: function(params) {
                                    return {
                                        attrValuePrefix: params.term, // search term
                                        typeName: queryData,
                                        limit: 10,
                                        offset: 0
                                    };
                                },
                                processResults: function(data, params) {
                                    return {
                                        results: getTypeAheadData(data, params)
                                    };
                                },
                                cache: true
                            },
                            templateResult: function(option) {
                                var name = Utils.getName(option, 'qualifiedName');
                                return name === "-" ? option.text : name;
                            },
                            templateSelection: function(option) {
                                var name = Utils.getName(option, 'qualifiedName');
                                return name === "-" ? option.text : name;
                            },
                            escapeMarkup: function(markup) {
                                return markup;
                            },
                            data: select2Options,
928
                            minimumInputLength: 1
929 930 931 932 933 934
                        });
                    }
                    $this.select2(select2Option);
                    if (selectedValue) {
                        $this.val(selectedValue).trigger("change");
                    }
935

936
                });
937 938 939 940
                if (this.guid) {
                    this.bindRequiredField();
                    this.bindNonRequiredField();
                }
941
                this.hideLoader();
942 943 944
            }
        });
    return CreateEntityLayoutView;
945
});