Help writing custom fields from Idea Portal

Mike D1
Giga Guru

Hi

 

I have created a custom string field ("u_test") on my table and am trying to test modifying the "IM Create/Edit Idea" widget to write the value once create button has been clicked. 

I have managed to create a new field by modifying the widget, however I am a stuck on how to write the value to the table. When I check the record it is not showing any value in the field or XML.

MikeD1_1-1668557274806.png

 

 

I have included the source code so hopefully someone can assist.

 

HTML

<div class="im_cq_wrapper row page-bg">
        <div ng-if="data.hasPermissions">
            <div class="col-md-12" ng-if="data.widgetMode == 'create'">
                <h2 class="h3">${Create an Idea}</h2>
            </div>
            <div ng-class="data.widgetMode == 'create' ? 'col-md-9 col-sm-9 col-xs-12' : 'col-md-12 col-sm-12 col-xs-12'">
                <uib-alert id="im-alert" ng-if="(formSubmitted && (!data.formModel._fields.title.stagedValue.trim() || data.formModel._fields.category.selectedCategoryId.length == 0 || !data.formModel._fields.description.stagedValue))" type="{{alertMessages.type}}">
                    <div class="msg-container">
                        <i class="fa fa-exclamation-circle" aria-hidden="true"></i>
                        <span class="message">{{alertMessages.msg}}</span>
                    </div>
                </uib-alert>
                <div class="panel panel-default">
                    <div class="panel-body">
                        <form name="forms.createForm" class="idea-form">
                            <div class="form-group title-field-container">
                                <label for="sp_form_field_title" class="field-label" title="{{::data.formModel._fields.title.label}}" aria-label="{{::data.formModel._fields.title.label}} "
                                    tooltip-right="true">
                                    <span class="field-decorations">
                                        <span ng-show="::data.formModel._fields.title.mandatory" class="fa fa-asterisk mandatory" ng-class="{'mandatory-filled': data.formModel._fields.title.mandatory_filled()}"
                                            title="${Required}" style="padding-right: .25em" aria-label="{{data.formModel._fields.title.mandatory_filled()? '${Required Filled}' : '${Required}'}}"></span>
                                    </span>
                                    {{::data.formModel._fields.title.label}}
                                </label>
                              	<span ng-if="data.showIdeaSuggestion">
                                 	<sp-widget widget="::data.ideaTypeaheadSearch"></sp-widget>
                                  </span>
                              	<span ng-if="!data.showIdeaSuggestion">
                              		<input name="Title" aria-label="{{::data.formModel._fields.title.label}}" id="sp_form_field_title" im-focus-element class="form-control" maxlength="{{data.maxLengthForTitleField}}" ng-class="(formSubmitted && !data.formModel._fields.title.stagedValue) ? 'field-invalid' : ''" data-type="{{::data.formModel._fields.title.type}}" ng-model="data.formModel._fields.title.stagedValue" ng-model-options="{allowInvalid: true}" ng-change="stagedValueChange()" autocomplete="off" ng-readonly="data.formModel._fields.title.isReadonly()" ng-attr-placeholder="{{data.formModel._fields.title.placeholder}}" type="text">
                              	</span>
                         </div>
                          <div id="results" class="col-xs-12 idea-search-results idea-page-view" data-ng-if="::data.showIdeaSuggestion">
                          </div>
                            <div class="form-group category-field-container">
                                <label for="categoryFltr" class="field-label" title="{{::data.formModel._fields.category.label}}" aria-label="{{::data.formModel._fields.category.label}} "
                                    tooltip-right="true">
                                    <span class="field-decorations">
                                        <span ng-show="::data.formModel._fields.category.mandatory" class="fa fa-asterisk mandatory" ng-class="{'mandatory-filled': data.formModel._fields.category.mandatory_filled()}"
                                            title="${Required}" style="padding-right: .25em" aria-label="{{data.formModel._fields.category.mandatory_filled()? '${Required Filled}' : '${Required}'}}"></span>
                                    </span>
                                    {{::data.formModel._fields.category.label}}
                                </label>
                                <span class="type-{{::data.formModel._fields.category.type}} field-actual" ng-class="{'state-mandatory': data.formModel._fields.category.mandatory, 'state-readonly': data.formModel._fields.category.read_only, 'state-hidden': data.formModel._fields.category.hidden, 'has-error': data.formModel._fields.category.isInvalid}">
                                    <idea-category-select ng-class="(formSubmitted && data.formModel._fields.category.selectedCategoryId.length == 0) ? 'field-invalid' : ''" category-levels-text="data.messages.categoryLevelsText" categories="data.formModel._fields.category.optionsList"
                                        show-all-category-opt="false" selected-category-id="data.formModel._fields.category.selectedCategoryId"
                                        no-label="true" allow-multiple="true" category-opts="data.formModel._fields.category.config" category-label="data.messages.categoryLabel"
                                        multiple="true">
                                    </idea-category-select>
                                </span>
                                <p class="category_caption" ng-if="data._categorySelectionLimit > 1">{{::data.messages.categorySelectionLimitMsg}}</p>
                            </div>
                            <label for="description" class="field-label description" title="{{::data.formModel._fields.description.label}}" aria-label="{{::data.formModel._fields.description.label}} "
                                tooltip-right="true">
                                <span class="field-decorations">
                                    <span ng-show="::data.formModel._fields.description.mandatory" class="fa fa-asterisk mandatory" ng-class="{'mandatory-filled': data.formModel._fields.description.mandatory_filled()}"
                                        title="${Required}" style="padding-right: .25em" aria-label="{{data.formModel._fields.description.mandatory_filled()? '${Required Filled}' : '${Required}'}}"></span>
                                </span>
                                {{::data.formModel._fields.description.label}}
                            </label>
                            <cf-tiny-mce
                                         ng-class="(formSubmitted && !data.formModel._fields.description.stagedValue) ? 'field-invalid' : ''"
                                         ng-model="data.formModel._fields.description.stagedValue"
                                         label= "data.formModel._fields.description.label"
                                         arial-label = "${Add a description}"
                                         ng-model-options="{height: '300', allow: false}"
                                         table="{{data.formModel.table}}"
                                         attachment-sys-id="-1"
                                         max-file-size="{{data._maxAttachmentSize}}">
                           </cf-tiny-mce>
                          
                          <!--Custom change 15/11-->
                          
                           <div class="form-group u_test-field-container">
                            <label for="sp_form_field_u_test" class="field-label" title="{{::data.formModel._fields.u_test.label}}" aria-label="{{::data.formModel._fields.u_test.label}} "
                                tooltip-right="true">
                                <span class="field-decorations">
                                    <span ng-show="::data.formModel._fields.u_test.mandatory" class="fa fa-asterisk mandatory" ng-class="{'mandatory-filled': data.formModel._fields.u_test.mandatory_filled()}"
                                        title="${Required}" style="padding-right: .25em" aria-label="{{data.formModel._fields.u_test.mandatory_filled()? '${Required Filled}' : '${Required}'}}"></span>
                                </span>
                                {{::data.formModel._fields.u_test.label}}
                            </label>
                                  <input name="Test" aria-label="{{::data.formModel._fields.u_test.label}}" id="sp_form_field_u_test" im-focus-element class="form-control" maxlength="{{data.maxLengthForTitleField}}" ng-class="(formSubmitted && !data.formModel._fields.u_test.stagedValue) ? 'field-invalid' : ''" data-type="{{::data.formModel._fields.u_test.type}}" ng-model="data.formModel._fields.u_test.stagedValue" ng-model-options="{allowInvalid: true}" ng-change="stagedValueChange()" autocomplete="off" ng-readonly="data.formModel._fields.u_test.isReadonly()" ng-attr-placeholder="{{data.formModel._fields.u_test.placeholder}}" type="text">
                              </span>
                     </div>
                      
												 <!--Custom change end 15/11-->
                      
                        </form>
                    </div>
                    <div class="panel-footer">
                        <div class="no-margin">
                            <div class="idea-attachment-list">
                                <div class="sp-attachments">
                                    <now-attachments-list template="im_attachment_preview"></now-attachments-list>
                                </div>
                            </div>
                            <label class="attachment-label" ng-class="data.widgetMode == 'create' ? 'right': 'left'">
                                <sp-attachment-button></sp-attachment-button>
                                <span>${Add attachments}</span>
                                <span class="clearfix"></span>
                            </label>
                            <div class="edit-idea-btn-actions" ng-if="data.widgetMode == 'edit'">
                                <button id="cancel_idea" class="btn btn-default " ng-click="cancelEditingIdea($event)">${Cancel}</button>
                                <button id="save_idea" class="btn btn-primary " ng-click="saveEditingIdea($event)">${Save}</button>
                            </div>
                            <span class="clearfix"></span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3 col-sm-3 col-xs-12 im_submit_cont" ng-if="data.widgetMode == 'create'">
                <button type="submit" id="submit_idea" class="btn btn-primary " ng-click="submitIdea($event)">${Create}</button>
            </div>
        </div>
        <div ng-if="!data.hasPermissions">
            <div class="alert alert-danger m-t" role="alert">
                ${Missing module/category configuration / Invalid module id!}
            </div>
        </div>
    </div>
<cf-confirm-modal data="modalConfig.opts" ng-if="modalConfig.showModal"></cf-confirm-modal>
<div class="loading-wrpr flex flex-center" ng-if="showLoading">
  <div class="flex flex-center flex-column">
    <div class="fa fa-spinner rotating"></div>
    <div ng-if="data.widgetMode == 'create'">${Creating idea...}</div>
    <div ng-if="data.widgetMode == 'edit'">${Saving idea...}</div>
  </div>
</div>

 

 Client scipt

function ($scope, glideFormFactory, $rootScope, spModal, IdeaPortalService, $timeout, IdeaHelpers, $window, IdeaPortalConstants, spUtil, $anchorScroll, $location) {
    $scope.alertMessages = {
        show: false
    };
    $scope.formSubmitted = false;
    $scope.forms = {};
	$scope.byPassRoute = false;
	$scope.modalConfig = {
		showModal: false
	};

	$scope.trackEvent = function(key, value, additionalValue) {
		IdeaHelpers.setWebaConfig($scope.data.snWebaConfig);
		IdeaHelpers.trackEvent(key, value, additionalValue);
	};

    if ($scope.data.widgetMode == 'create') {
        $timeout(function () {
			if($scope.data.isFromUniversalRecord){
				setTimeout(function(){
					jQuery('iframe')[0].contentDocument.getElementById("tinymce").innerText = $scope.data.ideaInfo.description;
		}, 3000);
			}
			$scope.trackEvent(IdeaPortalConstants.ANALYTICS_EVENTS.CREATE_PAGE.IM_IDEA_CREATE.KEY, IdeaPortalConstants.ANALYTICS_EVENTS.CREATE_PAGE.IM_IDEA_CREATE.VALUE, 1);
            $scope.portal.homepage_dv = 'ideas_list&sysparm_module_id=' + $scope.data.moduleInfo.id;
            $rootScope.$broadcast('sp.update.breadcrumbs', [{
                label: $scope.data.messages.createIdeaLbl,
                url: '#'
            }]);
        });
    }
    $scope.data._categorySelectionLimit = $scope.data.moduleInfo.maxCategorySelectionLimit;
    $scope.data.formModel = {
        _fields: {
            title: {
                label: $scope.data.messages.formLabels.title,
                name: $scope.data.messages.formLabels.title,
                stagedValue: ($scope.data.ideaInfo && $scope.data.ideaInfo.title) || '',
                value: '',
                displayValue: '',
                mandatory: true,
                mandatory_filled: function () {
                    return !!($scope.data.formModel._fields.title.stagedValue.trim());
                },
                isMandatory: function () {
                    return true;
                }
            },
					
					//Custom change 15/11
					 u_test: {
                label: $scope.data.messages.formLabels.u_test,
                name: $scope.data.messages.formLabels.u_test,
                stagedValue: ($scope.data.ideaInfo && $scope.data.ideaInfo.u_test) || '',
                value: '',
                displayValue: '',
                mandatory: true,
                mandatory_filled: function () {
                    return !!($scope.data.formModel._fields.u_test.value());
                },
                isMandatory: function () {
                    return true;
                }
            },
					
					//Custom change end 15/11
					
            description: {
                label: $scope.data.messages.formLabels.description,
                name: $scope.data.messages.formLabels.description,
                stagedValue: ($scope.data.ideaInfo && $scope.data.ideaInfo.description) || '',
                value: '',
                displayValue: '',
                type: 'html',
                mandatory: true,
                mandatory_filled: function () {
                    return !!($scope.data.formModel._fields.description.stagedValue);
                },
                isMandatory: function () {
                    return true;
                }
            },
            category: {
                label: $scope.data.messages.formLabels.category,
                name: $scope.data.messages.formLabels.category,
                mandatory: true,
                isReadOnly: function () {
                    return false;
                },
                isMandatory: function () {
                    return true;
                },
                mandatory_filled: function () {
                    return !!($scope.data.formModel._fields.category.selectedCategoryId.length > 0);
                },
                optionsList: $scope.data.categoryOptionsList,
                selectedCategoryId: ($scope.data.ideaInfo && $scope.data.ideaInfo.categoryValues) || "",
                config: {
                    maximumSelectionSize: $scope.data._categorySelectionLimit,
					formatSelectionTooBig: function() {
						return $scope.data.messages.maxCategoriesSelectedMsg;
					}
                }
            }
        },
        table: $scope.data.moduleInfo.ideaTable,
        sys_id: $scope.data._attachmentTableSysId || -1,
        _attachmentGUID: $scope.data._attachmentTableSysId || -1
    };
    $scope.attachmentsConfig = {
        isAttachmentToolsEnabled: true,
        showAttachmentUpdatedTime: true
    };
    var flatFields = [];
    angular.forEach($scope.data.formModel._fields, function (field) {
        flatFields.push(field);
    });
    var g_form = glideFormFactory.create($scope, $scope.data.formModel.table, $scope.data.formModel.sys_id, flatFields, null, {
        uiMessageHandler: IdeaHelpers.showUiNotificationMsg
    });

    $scope.getGlideForm = function () {
        return g_form;
    };

    var attachmentParams = {
        attachmentTable: $scope.data.moduleInfo.ideaTable,
        attachmentTableSysId: $scope.data._attachmentTableSysId,
        attachmentSize: $scope.data._maxAttachmentSize
    };
    var _onFileUploadCb = function (action, attachments) {
		if($scope.data.widgetMode == 'edit') {
			/* On edit Mode filter from editor attachments */
			var existingAttachmentsData = $scope.data.ideaInfo.attachmentsData;
			if(existingAttachmentsData && existingAttachmentsData.editorAttachments)
				attachments = IdeaHelpers.differenceInArrayOfObjs(attachments, existingAttachmentsData.editorAttachments);
		}
        $scope.attachments = attachments;
        if (action === 'added') {
			$scope.trackEvent(IdeaPortalConstants.ANALYTICS_EVENTS.CREATE_PAGE.IM_IDEA_ATTACHMENT_ADDED.KEY, IdeaPortalConstants.ANALYTICS_EVENTS.CREATE_PAGE.IM_IDEA_ATTACHMENT_ADDED.VALUE);
			$scope.setFocusToAttachment();
		}
        if (action === 'deleted') {
			$scope.trackEvent(IdeaPortalConstants.ANALYTICS_EVENTS.CREATE_PAGE.IM_IDEA_ATTACHMENT_DELETED.KEY, IdeaPortalConstants.ANALYTICS_EVENTS.CREATE_PAGE.IM_IDEA_ATTACHMENT_DELETED.VALUE);
			$scope.setFocusToAttachmentButton();	
		}
        else if (!action)
            $scope.initialAttachments = attachments;
    };
    var _onFileSizeLargeCb = function (e) {
        IdeaHelpers.showUiNotificationMsg('addErrorMessage', $scope.data.messages.largeAttachmentMsg);
    };
	var _titleValidationCb = function(e, data) {
		if($scope.formSubmitted && data === '')
			$('#sp_form_field_title').addClass('field-invalid');
		else
			$('#sp_form_field_title').removeClass('field-invalid');
		$scope.data.formModel._fields.title.stagedValue = data;
	}

    $scope.attachmentHandler = IdeaHelpers.initializeAttachmentHandler(attachmentParams, _onFileUploadCb);
    $scope.confirmDeleteAttachment = function (attachment) {
        spModal.confirm($scope.data.messages.delAttachmentMsg).then(function () {
            /*
			* on edit, just mark for delete and on save of editing changes we delete it.
			*/
			if($scope.data.widgetMode == 'edit') {
				$scope.onAttachmentDelete(attachment.sys_id, true);
				attachment.marked_for_delete = true;
			} else
				$scope.attachmentHandler.deleteAttachment(attachment);
        });
    };

    $scope.$evalAsync(function () {
        $scope.attachmentHandler.getAttachmentList();
    });

    var _isValidForm = function (formFields) {

        if(formFields.title.stagedValue.trim() === '' || (formFields.category.selectedCategoryId.length === 0) || formFields.description.stagedValue === '' /*Custom change 15/11*/ || formFields.u_test.stagedValue === '' /*Custom change end 15/11*/ ) {
          if(formFields.title.stagedValue.trim() === '') {
            $('#sp_form_field_title').addClass('field-invalid');
          }
          $scope.showAlert($scope.data.messages.formErrorMsg, 'danger');
          return false;
        }
		    return true;
    };

    var _getRequestParams = function (formFields, widgetMode) {
        var requestParams = {};
        requestParams.sysparm_sys_id = $scope.data._attachmentTableSysId;
        requestParams.sysparm_title = formFields.title.stagedValue;
			//Custom change 15/11 
			requestParams.sysparm_u_test = formFields.u_test.stagedValue;
			//Custom change end 15/11
        requestParams.sysparm_description = formFields.description.stagedValue;
        requestParams.sysparm_category_info = {
            categoryList: formFields.category.selectedCategoryId.join(','),
            categoryTable: $scope.data.categoryInfo.table,
            categoryField: $scope.data.categoryInfo.field
        };
		
        if (widgetMode == 'edit') {
            requestParams.sysparm_category_info.categoryAddedList = IdeaHelpers.differenceInArrays(formFields.category.selectedCategoryId, $scope.data.ideaInfo.categoryValues);
            requestParams.sysparm_category_info.categoryRemovedList = IdeaHelpers.differenceInArrays($scope.data.ideaInfo.categoryValues, formFields.category.selectedCategoryId);
        }
		requestParams.universal_request = $scope.data.universal_request_id ? $scope.data.universal_request_id : '';
        requestParams.sysparm_category_info = JSON.stringify(requestParams.sysparm_category_info);
        requestParams.sysparm_module_id = $scope.data.moduleInfo.sysId;
        requestParams.sysparm_idea_table = $scope.data.moduleInfo.ideaTable;
		requestParams.sysparm_editor_images = JSON.stringify(formFields.description.editorImagesArray);
        return requestParams;
    };

    $scope.submitIdea = function ($event) {
        $timeout(function () {
            $scope.formSubmitted = true;
            var formFields = $scope.data.formModel._fields;
            if(_isValidForm(formFields)) {
				$scope.isFormValid = true;
				var requestParams = _getRequestParams(formFields);
				$scope.showLoading = true;
				IdeaPortalService.createIdea(requestParams).then(function (response) {
									$scope.showLoading = false;
									var ideaDetails = response.data.result.ideaDetails;
									$window.location.href = '?id=view_idea&sysparm_idea_id='+ideaDetails.sys_id+'&sysparm_idea_table='+$scope.data.moduleInfo.ideaTable+'&sysparm_module_id='+$scope.data.moduleInfo.id;								
				}, function (error) {
					$scope.showLoading = false;
					console.error(error);
				});
			}
			
        });
    };

    $scope.saveEditingIdea = function ($event) {
        $timeout(function () {
            $scope.formSubmitted = true;
            var formFields = $scope.data.formModel._fields;
            if (_isValidForm(formFields)) {
                $scope.isFormValid = true;
                var requestParams = _getRequestParams(formFields, 'edit');
                $scope.showLoading = true;
				/*
				* Find number of attachments that are marked for delete in all attachments
				*/
				var _deletedAttachmentsInAllAttachments = IdeaHelpers.filterArrayOfObjsByKey($scope.attachments, 'marked_for_delete', true);
				/*
				* if marked for delete attachments are 0, ignore and save idea
				*/
				if(_deletedAttachmentsInAllAttachments.length > 0) {
					/*
					* if marked for delete attachments are more than 1, find diff between initial and deleted attachments which gives difference in attachments.
					*/
					var _diffInAttachments = IdeaHelpers.differenceInArrayOfObjs($scope.initialAttachments, _deletedAttachmentsInAllAttachments);
					/*
					* then, get the difference between marked for delete attachments and attachments in above step
					*/
					var _attachmentsDeleted = IdeaHelpers.differenceInArrayOfObjs(_deletedAttachmentsInAllAttachments, _diffInAttachments);
					/*
					* then, loop and delete one by one, if it is marked_for_delete
					*/
					_attachmentsDeleted.forEach(function(attachment) {
						if(attachment.marked_for_delete) {
							$scope.attachmentHandler.deleteAttachment(attachment);
						}
					});
				}
				IdeaPortalService.updateIdea(requestParams).then(function (response) {
					$scope.showLoading = false;
					$rootScope.$broadcast('im.view_page.edit_mode.stop');
				}, function (error) {
					$scope.showLoading = false;
					console.error(error);
				});
			}
       });
    };

    $scope.cancelEditingIdea = function ($event) {
        var _attachmentsAdded = IdeaHelpers.differenceInArrayOfObjs($scope.attachments, $scope.initialAttachments);
		/*
		* No need of taking action on deleted attachments. Because on cancel will refresh the view idea widget which will fetch all attachments that are existing.
		*/
        _attachmentsAdded.forEach(function (attachment) {
            $scope.attachmentHandler.deleteAttachment(attachment);
        });
        $rootScope.$broadcast('im.view_page.edit_mode.cancel');
    };

    spUtil.get("idea-typeahead-search", {contextual_search_sources: '44484ec187d03300c1ebd82548cb0b44', moduleInfo: $scope.data.moduleInfo, isSimiliarIdea: true, formModelTitle: $scope.data.formModel._fields.title, limit:10, maxLength: $scope.data.maxLengthForTitleField, typeAheadTitle :  $scope.data.typeAheadTitle}
			  ).then(function(response) {
      $scope.data.ideaTypeaheadSearch = response;
    });
	
	var _isFormDirty = function() {
		var formFields = $scope.data.formModel._fields;
		if($scope.data.widgetMode == 'create') {
			if ($scope.forms.createForm.$dirty) {
                if (!$scope.isFormValid)
                    return true
            }
		} else if($scope.data.widgetMode == 'edit') {
			if (formFields.title.stagedValue != ($scope.data.ideaInfo && $scope.data.ideaInfo.title) || (formFields.category.selectedCategoryId.length != ($scope.data.ideaInfo && $scope.data.ideaInfo.categoryValues.length)) ||
                (formFields.description.stagedValue != $scope.data.ideaInfo.description)) {
                if (!$scope.isFormValid)
                    return true
            }
		}
		return false;
	}

    $window.onbeforeunload = function () {
        if(_isFormDirty())
			return $scope.data.messages.formDirtyMsg;
    };

    var _onImagesAddedInEditor = function (event, imagesData) {
		$scope.data.formModel._fields.description.editorImagesArray = imagesData; 
    };

    $scope.showAlert = function (msg, type) {
				
        $scope.alertMessages.type = type;
        $scope.alertMessages.msg = msg;

        $timeout(function () {
            $anchorScroll('im-alert');
        });
    };
	
	var _onLocationChangeStart = function(event, next, current) {
		if(!$scope.byPassRoute && _isFormDirty()) {
			event.preventDefault();
			var confirmModalCtrl;
			$scope.modalConfig.opts = {
				size: 'sm',
				title: $scope.data.messages.saveChangesCnfrmModal.headerMsg,
				text: '<div class="text-content"><div class="my-modal-text"></div>'+$scope.data.messages.saveChangesCnfrmModal.bodyMsg+'</div>',
				okTxt: $scope.data.messages.saveChangesCnfrmModal.okMsg,
				cancelTxt: $scope.data.messages.saveChangesCnfrmModal.cancelMsg,
				okBtnClass: 'btn-danger',
				ok: function() {
					$scope.byPassRoute = true;
					$location.search(next.split('?')[1]);
					confirmModalCtrl.close();
				},
				afterOpen: function(ctrl) {
					confirmModalCtrl = ctrl;
				},
				afterClose: function() {
					$scope.modalConfig.showModal = false;
					confirmModalCtrl = null;
					$scope.modalConfig.opts = null;
				}
			};
			$timeout(function() {
				$scope.modalConfig.showModal = true;
			});
		}
	};

    /**
     * Event Listeners
     */
    $scope.$on('dialog.upload_too_large.show', _onFileSizeLargeCb);
	$scope.$on('similiar.idea.title.search', _titleValidationCb);
	$scope.$on('cf.editor_attachments.file_exceeded', _onFileSizeLargeCb);
    $scope.$on('cf.editor.image_array', _onImagesAddedInEditor);
	$scope.$on('$locationChangeStart', _onLocationChangeStart);
}

Server Script

(function($sp, input, data, gs, GlideRecord) {

	data._attachmentTableSysId = options.ideaId || gs.generateGUID();
	data._maxAttachmentSize = IMCommonService.properties.MAX_ATTACHMENT_SIZE;
	data.widgetMode = options.widgetMode || 'create';
	data.showIdeaSuggestion = data.widgetMode == 'create';
	var universalId = $sp.getParameter("sysparm_u_id");
	data.typeAheadTitle = gs.getMessage("Title");
	
	if(universalId) {
		data.isFromUniversalRecord = true;
		data.universal_request_id = universalId;
		
		var universalRequestRecord = new GlideRecord("universal_request");
		universalRequestRecord.get(universalId);
		
		var copyFields = gs.getProperty('com.snc.idea.universal_request.copy_fields','short_description,description');
		var copyFieldsList = copyFields.trim().split(",");
		var index;
		data.ideaInfo = {};
		
		if(copyFieldsList.indexOf('description') > -1)
			data.ideaInfo.description = universalRequestRecord.getDisplayValue('description');
		
		if(copyFieldsList.indexOf('short_description') > -1)
			data.ideaInfo.title = universalRequestRecord.getDisplayValue('short_description');
	}
	var getModuleInfo = function() {
		var moduleId = options.moduleId || $sp.getParameter('sysparm_module_id');

		if(JSUtil.nil(moduleId))
			moduleId = IMCommonService.getModuleIdFromUserPref();
		if(JSUtil.nil(moduleId)) {
			data.hasPermissions = false;
			return;
		}

		var moduleInfo = IMCommonService.getModuleInfoFromModuleId(moduleId);
		if(moduleInfo.isValid) { 
			data.hasPermissions = true;
			data.moduleInfo = moduleInfo;
			
			data.maxLengthForTitleField = IMCommonService.getMaxLengthForField(data.moduleInfo.ideaTable, 'short_description');
		} else {
			data.hasPermissions = false;
		}
	};

	var getCategoryInfo = function() {
		var imIdeaCategory = new IMIdeaCategory();
		var categoryInfo = imIdeaCategory.getCategoryInfo(data.moduleInfo.sysId);
		if(categoryInfo.table && categoryInfo.displayField) {
			data.categoryInfo = categoryInfo;
			data.categoryOptionsList = new IMCategoryTreeBuilder(data.moduleInfo.id).buildCategoryTree().getCategoryTree();
		} else {
			data.hasPermissions = false;
		}
	};
	
	getModuleInfo();
	if(data.moduleInfo.sysId)
		getCategoryInfo();

	if(data.widgetMode == 'edit') {
		var imEditIdeaService = new IMCreateEditIdeaDataService(data.moduleInfo.ideaTable);
		data.ideaInfo = imEditIdeaService.getIdeaInfo(options.ideaId, data.moduleInfo.id);
	}
	
	if(!input) {
    data.snWebaConfig = IMCommonService.getWebaConfig() || {};


		/**
		* Messages Configuration -  Start
		**/
		var _attachmentSizeString =  "" + (Number(data._maxAttachmentSize)/1000000) + "MB";
		data.messages = {};
		data.messages.createIdeaLbl = gs.getMessage('Create an Idea');
		data.messages.formLabels = {
			'title': gs.getMessage('Title'),
			'category': gs.getMessage('Category'),
			'description': gs.getMessage('Description'),
				//Custom change 15/11
			'u_test' : gs.getMessage('Test'),
			//Custom change end 15/11
		};

		data.messages.formErrorMsg = gs.getMessage('Error. Please fill all the required(*) fields.');
		data.messages.delAttachmentMsg = gs.getMessage('Delete Attachment?');
		data.messages.largeAttachmentMsg = gs.getMessage("Attached files must be smaller than {0} - please try again",_attachmentSizeString);
		data.messages.formDirtyMsg = gs.getMessage("Are you sure you want to leave?");
		data.messages.allCategories = gs.getMessage("All Categories");
		data.messages.categoryLabel = gs.getMessage("Category");
		data.messages.categoryLevelsText = [
			gs.getMessage("this is a level 1 category"),
			gs.getMessage("this is a level 2 category"),
			gs.getMessage("this is a level 3 category"),
			gs.getMessage("this category is beyond level 3")
		];
		data.messages.categorySelectionLimitMsg = gs.getMessage('Select 1 to {0} categories', [data.moduleInfo.maxCategorySelectionLimit]);
		data.messages.saveChangesCnfrmModal =  {
			headerMsg: gs.getMessage('Warning'),
			bodyMsg: gs.getMessage('Changes you made may not be saved. Are you sure?'),
			okMsg: gs.getMessage('Ok'),
			cancelMsg: gs.getMessage('Cancel')
		};
		data.messages.maxCategoriesSelectedMsg = gs.getMessage("You can only select {0} items", [data.moduleInfo.maxCategorySelectionLimit]);
		/**
		* Messages Configuration -  End
		**/
	}

})($sp, input, data, gs, GlideRecord);
2 ACCEPTED SOLUTIONS

Saurav11
Kilo Patron
Kilo Patron

Hello

 

Please check the below article for the same

 

https://www.servicenow.com/community/developer-forum/idea-portal-widget-im-create-edit-added-fields-...

 

Please mark answer as correct based on Impact 

View solution in original post

Hello,

 

If my answer helped you can you also mark it as correct.

 

Thanks.

View solution in original post

2 REPLIES 2

Saurav11
Kilo Patron
Kilo Patron

Hello

 

Please check the below article for the same

 

https://www.servicenow.com/community/developer-forum/idea-portal-widget-im-create-edit-added-fields-...

 

Please mark answer as correct based on Impact 

Hello,

 

If my answer helped you can you also mark it as correct.

 

Thanks.