Idea Portal Widget Populate Default Field Values

litchick10
Tera Guru

In the Idea Portal widget IM Create/Edit I added a field called u_epic.  However, I cannot get a default value to populate on the form.

I tried to set the value and displayValue in the code shown below that can be found under $scope.data.formModel object. No text shows up in the form field (using 'Test' below just as example)

u_epic: {
 label: $scope.data.messages.formLabels.u_epic,
 name: $scope.data.messages.formLabels.u_epic,
 stagedValue: ($scope.data.ideaInfo && $scope.data.ideaInfo.u_epic) || '',
 value: 'Test',
 displayValue: 'Test',
 type: 'html',
 mandatory: true,
 mandatory_filled: function () {
 return !!($scope.data.formModel._fields.u_epic.stagedValue);
 },
 isMandatory: function () {
 return true;
 }
}

 

 find_real_file.png

 

 

1 ACCEPTED SOLUTION

So looks like your HTML tinyMce editor is bound to the stagedValue.

Can you replace the staged value line in your client controller's u_epic's definition with:

stagedValue: ($scope.data.ideaInfo && $scope.data.ideaInfo.u_epic) || 'Test',

Thanks & Regards,

Rishabh Jha

Aavenir (http://www.aavenir.com/)

 

 

 

View solution in original post

13 REPLIES 13

Ct111
Giga Sage

Hi,

The below response for Lars is worth checking in your scenario

https://community.servicenow.com/community?id=community_question&sys_id=e1004321db98dbc01dcaf3231f96...

 

https://serviceportal.io/embedding-widgets-in-service-catalog/

 

Mark my ANSWER as CORRECT and HELPFUL if it helps

Rishabh Jha
Mega Guru

Hi @litchick10 ,

You should be able to use g_form.Setvalue on your widget's client script, to set the initial value of your field. Try code snippet below on the initForm() function on the client script (if there's one), or anywhere where your form load function is defined.

g_form.setValue('u_epic', 'Test'); 



Thanks & Regards,
Rishabh Jha
Aavenir(https://www.aavenir.com/)

Here is the entire client controller script for the widget. I do not see where the form load is defined or an initForm function

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 () {
			$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;
                }
            },
            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
                }
            },
			   u_epic: {
                label: $scope.data.messages.formLabels.u_epic,
                name: $scope.data.messages.formLabels.u_epic,
				stagedValue: ($scope.data.ideaInfo && $scope.data.ideaInfo.u_epic) || '',
                value: '',
				displayValue: '',
				type: 'html',
				mandatory: true,
				mandatory_filled: function () {
				 return !!($scope.data.formModel._fields.u_epic.stagedValue);
				 },
				 isMandatory: function () {
				 return true;
				 }
            }
        },
        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) {
		console.log($scope.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 === '') {
          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;
        requestParams.sysparm_description = formFields.description.stagedValue;
		requestParams.sysparm_u_epic = formFields.u_epic.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.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}
			  ).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);
}

Hi,

Can you try putting the snippet below at line 111, i.e. after the point where g_form is getting created, and see if that works?

g_form.setValue('u_epic', 'Test'); 


Thanks & Regards,
Rishabh Jha
Aavenir(https://www.aavenir.com/)