Search and set values to Item record.

Jira Code: PS -14

This task is to set attributes, its values & category ID. Attribute names & number will be different for each Category ID. Also Client needs to search the Category ID.I have created 3 custom records and a suitelet script , client script, user event script  to achieve the task.

Client script

/**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * CLIENTNAME:PARKSLOPE
 * PS 13 - Alias Naming In Category ID
 *************************************************************************
 * Date : 21/02/2019
 *
 * Author: Jobin & Jismi IT Services LLP
 * Script Description : This is to button action
 *  			
 *  Date created : 21/02/2019
 *
 * REVISION HISTORY
 *
 * Revision 1.0 ${21/02/2019} aj : created
 * 			1.1 ${28/02/2019} aj : Added PS 14 
 *
 ******************************************************************************/
define(['N/record', 'N/search', 'N/url','N/currentRecord', 'N/ui/message'],
		/**
		 * @param {record} record
		 * @param {search} search
		 * @param {url} url
		 */
		function(record, search, url,currentRecord,message) {

	/**
	 * Function to be executed after page is initialized.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.mode - The mode in which the record is being accessed (create, copy, or edit)
	 *
	 * @since 2015.2
	 */
	function pageInit(scriptContext) {


		try{
			//custpage_select_attribute
			document.getElementById('custpage_select_attribute').style.display = 'none';
			//secondarycustpage_select_attribute
			document.getElementById('secondarycustpage_select_attribute').style.display = 'none';
			//avoid the standard NetSuite warning message when navigating away
			if (window.onbeforeunload) {
				window.onbeforeunload = function() {
					null;
				};
			}

		}catch(e)
		{
			console.log("Err@ FN pageInit=",e.message);
		}




	}

	/**
	 * Function to be executed when field is changed.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 * @param {string} scriptContext.fieldId - Field name
	 * @param {number} scriptContext.lineNum - Line number. Will be undefined if not a sublist or matrix field
	 * @param {number} scriptContext.columnNum - Line number. Will be undefined if not a matrix field
	 *
	 * @since 2015.2
	 */
	function fieldChanged(scriptContext) {
		try{
			var fieldIdObj = {
					'pageindexfield' : 'pageindexfield'
			};
			if (checkForParameter(fieldIdObj[scriptContext.fieldId])) {
				var skipWaitPromise = new Promise(function(resolve,
						reject) {
					resolve(scriptContext);
				});
				setTimeout(function() {
					runPromise(skipWaitPromise);
				}, 10);
				return true;
			}

			if ((scriptContext.sublistId == 'custpage_search_sublist')
					&& (scriptContext.fieldId == 'custcol_select')) {

				var CurrRecord = scriptContext.currentRecord;

				var linNum = CurrRecord.getLineCount({
					sublistId : 'custpage_search_sublist'
				});

				// get current line checkbox value
				var current_select = CurrRecord
				.getCurrentSublistValue({
					sublistId : 'custpage_search_sublist',
					fieldId : 'custcol_select'
				});
				// get line number of current line
				var currline = CurrRecord.getCurrentSublistIndex({
					sublistId : 'custpage_search_sublist'
				});
				// get line number of other line where checkbox is true

				for(var i=0;i<linNum;i++)
				{
					var trueLineNumber = CurrRecord
					.getSublistValue({
						sublistId : 'custpage_search_sublist',
						fieldId : 'custcol_select',
						line:i
					});


					if (trueLineNumber ==true ) {
						// set the true checkbox to false

						CurrRecord.selectLine({
							sublistId : 'custpage_search_sublist',
							line : i
						});
						CurrRecord.setCurrentSublistValue({
							sublistId : 'custpage_search_sublist',
							fieldId : 'custcol_select',
							value : false,
							ignoreFieldChange : true
						});
						CurrRecord.commitLine({
							sublistId : 'custpage_search_sublist'
						});

					}

					CurrRecord.selectLine({
						sublistId : 'custpage_search_sublist',
						line : currline
					});
					CurrRecord.setCurrentSublistValue({
						sublistId : 'custpage_search_sublist',
						fieldId : 'custcol_select',
						value : true,
						ignoreFieldChange : true
					});
					document.getElementById('custpage_select_attribute').style.display = 'block';
					document.getElementById('secondarycustpage_select_attribute').style.display = 'block';
				}


			}
			else 
				return true;

		}catch(e)
		{
			console.log("Err@ FN fieldChanged=",e);
		}

	}

	/**
	 * Function to be executed when field is slaved.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 * @param {string} scriptContext.fieldId - Field name
	 *
	 * @since 2015.2
	 */
	function postSourcing(scriptContext) {

	}

	/**
	 * Function to be executed after sublist is inserted, removed, or edited.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 *
	 * @since 2015.2
	 */
	function sublistChanged(scriptContext) {

	}

	/**
	 * Function to be executed after line is selected.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 *
	 * @since 2015.2
	 */
	function lineInit(scriptContext) {

	}

	/**
	 * Validation function to be executed when field is changed.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 * @param {string} scriptContext.fieldId - Field name
	 * @param {number} scriptContext.lineNum - Line number. Will be undefined if not a sublist or matrix field
	 * @param {number} scriptContext.columnNum - Line number. Will be undefined if not a matrix field
	 *
	 * @returns {boolean} Return true if field is valid
	 *
	 * @since 2015.2
	 */
	function validateField(scriptContext) {

	}

	/**
	 * Validation function to be executed when sublist line is committed.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 *
	 * @returns {boolean} Return true if sublist line is valid
	 *
	 * @since 2015.2
	 */
	function validateLine(scriptContext) {

	}

	/**
	 * Validation function to be executed when sublist line is inserted.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 *
	 * @returns {boolean} Return true if sublist line is valid
	 *
	 * @since 2015.2
	 */
	function validateInsert(scriptContext) {

	}

	/**
	 * Validation function to be executed when record is deleted.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @param {string} scriptContext.sublistId - Sublist name
	 *
	 * @returns {boolean} Return true if sublist line is valid
	 *
	 * @since 2015.2
	 */
	function validateDelete(scriptContext) {

	}

	/**
	 * Validation function to be executed when record is saved.
	 *
	 * @param {Object} scriptContext
	 * @param {Record} scriptContext.currentRecord - Current form record
	 * @returns {boolean} Return true if record is valid
	 *
	 * @since 2015.2
	 */
	function saveRecord(scriptContext) {
		try{


		}catch(e)
		{
			console.log("Err@ FN saveRecord=",e);
		}

	}
	/*******************************************************************************
	 * Function to open up the suitelet to select
	 * 
	 * @param e
	 * @returns {String}
	 * 
	 * Created on 21-Feb-2019 by aj
	 *******************************************************************************/
	function selectItemCategory()
	{
		try{
			// to get the current record
			var curRec =currentRecord.get();

			var id = curRec.id;
			// to get the type inventoryitem
			var type=curRec.type;
			// to open a Sl 
			var toSL = url.resolveScript({
				scriptId:'customscript_ps13_jj_sl_select_category',
				deploymentId:'customdeploy_ps13_jj_sl_select_category',
				params:{
					recId:id,
					type:type
				},
				returnExternalUrl:false
			});
			window.open(toSL);
		}catch(e)
		{
			console.log("Err@ FN selectItemCategory=",e);
		}
	}

	function runPromise(skipWaitPromise) {
		try {

			skipWaitPromise.then(function(scriptContext) {
				var curRec= scriptContext.currentRecord;

				var pageIndex = assignDefaultValue(curRec.getValue({
					fieldId: 'pageindexfield'
				}), 0);
				var searchValue =curRec.getValue({
					fieldId: 'custpage_search'
				})

				var recID=curRec.getValue({
					fieldId: 'custpage_hidden'
				})
				var toSL = url.resolveScript({
					scriptId:'customscript_ps13_jj_sl_select_category',
					deploymentId:'customdeploy_ps13_jj_sl_select_category',
					params:{
						mode:'post',
						custpage_search:searchValue,
						pageIndex:pageIndex,
						recId:recID

					},
					returnExternalUrl:false
				});
				window.location.href =toSL;
			});
		} catch (e) {
			console.log("Err @runPromise", e);
		}

	}
	/**********************************************
	 *  To check whether a value exists in parameter 
	 *  
	 **********************************************/

	function checkForParameter(parameter, parameterName) {
		if (parameter !== null && parameter !== undefined
				&& parameter !== false && parameter !== "null"
					&& parameter !== "undefined" && parameter !== "false"
						&& parameter != "" && parameter != " ") {
			return true;
		} else {
			if (parameterName)
				console.log('Empty Value found for parameter'
						+ parameterName);
			return false;
		}
	}
	/*********************************************
	 * To assign a default value if the it is empty
	 * @param value
	 * @param defaultValue
	 * @returns
	 ********************************************/
	function assignDefaultValue(value, defaultValue) {
		try{
			if (checkForParameter(value))
				return value;
			else
				return defaultValue;
		}catch(e)
		{
			log.debug("Err@ FN assignDefaultValue",e);
		}
	}

	/*********************************************
	 * To set attribute value 
	 * @param value
	 * @param defaultValue
	 * @returns
	 ********************************************/
	function setAttribute()
	{
		try{

			// to get the current record
			var curRec =currentRecord.get();

			// to get the current selected category
			var trueLineNum = curRec.findSublistLineWithValue({
				sublistId:'custpage_search_sublist',
				fieldId:'custcol_select',
				value:'T'
			});
			// to get the key word used
			var keyWord = curRec.getValue({

				fieldId:'custpage_search',

			});


			// to get the value of category
			var categoryName = curRec.getSublistValue({
				sublistId:'custpage_search_sublist',
				fieldId:'name',
				line:trueLineNum
			});

			var aliasName = curRec.getSublistValue({
				sublistId:'custpage_search_sublist',
				fieldId:'custrecord_jj_ps13_alias_name',
				line:trueLineNum
			});



			// to go to set Attribute page

			var recID=curRec.getValue({
				fieldId: 'custpage_hidden'
			})
			var type = curRec.getValue({
				fieldId: 'custpage_type'
			})


			var setAttributePage = url.resolveScript({
				scriptId: "customscript_jj_ps_14_set_attribute_item",
				deploymentId: "customdeploy_jj_ps_14_set_attribute_item",
				params:{
					mode:'post',
					categoryName:categoryName,
					recId:recID,
					type:type,
					keyWord:keyWord
				},
				returnExternalUrl: false

			});

			window.location.href =setAttributePage;





		}catch(e)
		{
			console.log("Err@ FN setAttribute",e);
		}
	}


	/*********************************************
	 * To set attribute value 
	 * @param value
	 * @param defaultValue
	 * @returns
	 ********************************************/
	function backButton()
	{
		try{


			// to get the current record
			var curRec =currentRecord.get();
			// search value
			var searchValue = curRec.getValue({
				fieldId: 'custpage_key'
			})
			var type = curRec.getValue({
				fieldId: 'custpage_type'
			})
			var recID = curRec.getValue({
				fieldId: 'custpage_recid'
			})
			// to go to  Attribute page
			var toSL = url.resolveScript({
				scriptId:'customscript_ps13_jj_sl_select_category',
				deploymentId:'customdeploy_ps13_jj_sl_select_category',
				params:{
					mode:'post',
					custpage_search:searchValue,
					pageIndex:0,
					recId:recID,
					type:type

				},
				returnExternalUrl:false
			});
			window.location.href =toSL;




		}catch(e)
		{
			console.log("Err@ FN backButton",e);
		}
	}
	/*********************************************
	 * To get the parameter from a url
	 * @param value
	 * @param defaultValue
	 * @returns
	 ********************************************/

	function getParameterByName(name, url) {
		if (!url)
			url = window.location.href;
		name = name.replace(/[\[\]]/g, "\\$&");
		var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
		results = regex
		.exec(url);
		if (!results)
			return null;
		if (!results[2])
			return ' ';
		return decodeURIComponent(results[2].replace(/\+/g, " "));
	}


	/*********************************************
	 * To search for item id
	 * @param value
	 * @param defaultValue
	 * @returns
	 ********************************************/
	function checkRecExisting(id)
	{
		try{
			// to create a search
			var customrecord_jj_ps15_item_attributeSearchObj = search.create({
				type: "customrecord_jj_ps15_item_attribute",
				filters:
					[
						["custrecord_ps15_child_item","anyof",id]
						],
						columns:
							[
								search.createColumn({
									name: "id",
									sort: search.Sort.ASC,
									label: "ID"
								}),
								search.createColumn({name: "custrecord_ps15_child_item", label: "Item"})
								]
			});
			var searchResultCount = customrecord_jj_ps15_item_attributeSearchObj.runPaged().count;
			log.debug("customrecord_jj_ps15_item_attributeSearchObj result count",searchResultCount);
			if(searchResultCount>0)
			{
				var searchResult = customrecord_jj_ps15_item_attributeSearchObj.run().getRange({
					start:0,
					end:1
				}); 
				var itemId = searchResult[0].getValue({
					name: "id",
					label: "ID"
				});
				return itemId;
			}
			else
				return false;


		}catch(e)
		{
			console.log("Err@ FN checkRecExisting",e);
		}

	}

	function closeWindow()
	{
		if (window.onbeforeunload) {
			window.onbeforeunload = function() {
				null;
			};
		}
		window.close();
	}

	return {
		pageInit: pageInit,
		fieldChanged: fieldChanged,
		selectItemCategory:selectItemCategory,
		setAttribute:setAttribute,

		backButton:backButton
	};

});

Set Attribute Suitelet

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * CLIENTNAME:PARKSLOPE PS 14 - Automating the Attribute fields based on the Category ID
 * ************************************************************************ Date :
 * 25/02/2019
 * 
 * Author: Jobin & Jismi IT Services LLP Script Description : This is to show
 * item category
 * 
 * Date created : 25/02/2019
 * 
 * REVISION HISTORY
 * 
 * Revision 1.0 ${25/02/2019} marg : created
 * 			1.1 ${26/02/2019} aj : modified : to set fields according to the req
 * 
 * 
 ******************************************************************************/
define(['N/record', 'N/search', 'N/ui/serverWidget', 'N/url', 'N/runtime', 'N/file'],

		function(record, search, serverWidget, url,runtime,file) {

	/**
	 * Definition of the Suitelet script trigger point.
	 *
	 * @param {Object} context
	 * @param {ServerRequest} context.request - Encapsulation of the incoming request
	 * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
	 * @Since 2015.2
	 */
	function onRequest(context) {

		try{

			var categoryId =assignDefaultValue(context.request.parameters.custpage_category,context.request.parameters.categoryName);



			var recId = context.request.parameters.recId;
			var keyWord = context.request.parameters.keyWord;
			var type = assignDefaultValue(context.request.parameters.custpage_type,context.request.parameters.type);



			var form = serverWidget.createForm({
				title: 'Attribute List'
			});
			var attributeArray;
			if(context.request.method=='GET')
			{
				attributeArray ={};






				var attributeSearch = search.create({
					type: "customrecord_ps14_attribute_category_map",
					filters:
						[
							["custrecord_ps14_category_id","is",categoryId]
							],
							columns:
								[
									search.createColumn({
										name: "id",

										sort: search.Sort.ASC,
										label: "ID"
									}),
									search.createColumn({name: "custrecord_ps14_category_id", label: "Category ID"}),
									search.createColumn({name: "custrecord_ps14_attribute", label: "Attribute"}),
									search.createColumn({name: "custrecord_ps14_required", label: "Required?"}),
									search.createColumn({name: "custrecord_ps14_allow_text", label: "Allow Free Text?"}),
									search.createColumn({name: "custrecord_ps14_custom", label: "Can Be Custom?"}),
									search.createColumn({name: "custrecord_ps14_distinguishing", label: "Distinguishing?"}),
									search.createColumn({name: "custrecord_ps14_attachment", label: "Attachment?"}),
									search.createColumn({name: "custrecord_ps14_display_name", label: "Display Name (UI & Site)"})
									]
				});
				var searchResult = attributeSearch.run().getRange({
					start:0,
					end:1000
				}); 


				var total = form.addField({
					id : 'custpage_total',
					type : serverWidget.FieldType.TEXT,
					label : 'total'
				});
				total.defaultValue=searchResult.length;	
				total.updateDisplayType({
					displayType: serverWidget.FieldDisplayType.HIDDEN
				});
				for(var i= 0; i< searchResult.length; i++)
				{


					var categoryId = searchResult[i].getValue({
						name: "custrecord_ps14_category_id"
					}); 


					var attribute = searchResult[i].getValue({
						name: "custrecord_ps14_attribute"
					}); 

					var required = searchResult[i].getValue({
						name: "custrecord_ps14_required"
					}); 


					var allowText = searchResult[i].getValue({
						name: "custrecord_ps14_allow_text"
					}); 


					var custom = searchResult[i].getValue({
						name: "custrecord_ps14_custom"
					}); 


					var distinguishing = searchResult[i].getValue({
						name: "custrecord_ps14_distinguishing"
					}); 


					var attachment = searchResult[i].getValue({
						name: "custrecord_ps14_attachment"
					}); 


					var displayName = searchResult[i].getValue({
						name: "custrecord_ps14_display_name"
					}); 



					var attributeObj = {};

					// to add  attachment

					if(attachment==true)
					{
						var attributeValue = form.addField({
							id : 'custpage_'+i,
							type : serverWidget.FieldType.FILE,
							label : attribute
						});

						attributeObj ={id : 'custpage_'+i,type :'file',label :attribute}
						attributeArray[i] = attributeObj;
					}
					else
					{
						if(allowText==false &&custom==true)
						{
							var sourceId = findListId(attribute);
							var attributeValue = form.addField({
								id : 'custpage_'+i,
								type : serverWidget.FieldType.SELECT,
								label : attribute,
								source:sourceId
							});
							attributeObj ={id : 'custpage_'+i,type :'list',label :attribute}
							attributeArray[i] = attributeObj;

						}
						else
						{
							var attributeValue = form.addField({
								id : 'custpage_'+i,
								type : serverWidget.FieldType.TEXT,
								label : attribute
							});
							attributeObj ={id : 'custpage_'+i,type :'text',label :attribute}
							attributeArray[i] = attributeObj;
						}



					}


					// to make mandatory
					if(required==true)
						attributeValue.isMandatory = true;
					attributeValue.updateLayoutType({
						layoutType: serverWidget.FieldLayoutType.NORMAL
					});


				}

				var attributeArrayField = form.addField({
					id : 'custpage_array',
					type : serverWidget.FieldType.LONGTEXT,
					label : 'attributeArray'
				});
				var array = [];
				array.push(attributeArray);
				attributeArrayField.defaultValue = JSON.stringify(attributeArray);
				attributeArrayField.updateDisplayType({
					displayType: serverWidget.FieldDisplayType.HIDDEN
				});

				var recIdField = form.addField({
					id : 'custpage_recid',
					type : serverWidget.FieldType.TEXT,
					label : 'Rec Id'
				});
				recIdField.defaultValue = recId;
				recIdField.updateDisplayType({
					displayType: serverWidget.FieldDisplayType.HIDDEN
				});
				var typeField = form.addField({
					id : 'custpage_type',
					type : serverWidget.FieldType.TEXT,
					label : 'Type'
				});
				typeField.defaultValue = type;

				typeField.updateDisplayType({
					displayType: serverWidget.FieldDisplayType.HIDDEN
				});

				// category id
				var categoryField = form.addField({
					id : 'custpage_category',
					type : serverWidget.FieldType.TEXT,
					label : 'Category'
				});
				categoryField.defaultValue = categoryId;

				categoryField.updateDisplayType({
					displayType: serverWidget.FieldDisplayType.HIDDEN
				});
				// keyword
				var keyField = form.addField({
					id : 'custpage_key',
					type : serverWidget.FieldType.TEXT,
					label : 'Key'
				});
				keyField.defaultValue = keyWord;

				keyField.updateDisplayType({
					displayType: serverWidget.FieldDisplayType.HIDDEN
				});

				form.addSubmitButton({
					label : 'Save to Attributes for Item'
				});

//				back button

				form.addButton({
					label : 'Go Back',
					id:'custpage_back',
					functionName:'backButton'

				});
				form.clientScriptFileId = 11705;
				context.response.writePage(form);
			}
			if(context.request.method=='POST'){

				var itemId = context.request.parameters.custpage_recid;
				var itemType = context.request.parameters.custpage_type;
				var category = context.request.parameters.custpage_category;
				// to set item category
				var itemRec=record.load({
					type:itemType,
					id:itemId
				});
				itemRec.setText({
					fieldId:'custitemgrpncategoryid',
					text:category
				});
				var id = itemRec.save({ignoreMandatoryFields:true});

				var attributeArray = context.request.parameters.custpage_array;


				// to set the values to custom record
				var recId = context.request.parameters.custpage_recid;
				// check existing id
				var isexist = checkRecExisting(recId);

				if(isexist==false)
				{
					// to create an entry
					var customRec =record.create({
						type: 'customrecord_jj_ps15_item_attribute'
					});
					// to set the item
					var item=customRec.setValue({
						fieldId:'custrecord_ps15_child_item',
						value:parseInt(recId)
					});
				}
				else
				{
					var customRec=record.load({
						type:'customrecord_jj_ps15_item_attribute',
						id:isexist
					}); 
				}
				attributeArray = JSON.parse(attributeArray);
				var j;
				// to get the all fields
				for (var key in attributeArray) {

					j=parseInt(key)+1;

					// to set the attribute name
					customRec.setText({
						fieldId:'custrecord_ps15_attribute'+j,
						text:attributeArray[key]["label"]
					});
					var userId = runtime.getCurrentUser().id;
					// to set the attribute value
					if(attributeArray[key]["type"]=='file')
					{
						var fieldIdEntered =attributeArray[key]["id"];

						var file1 = context.request.files[fieldIdEntered];

						if(file1!=null && file1!=undefined && file1!="" && file1!=" " && file1!='null')
						{
							file1.folder = 2196;
							var id1 = file1.save();

							record.attach({
								record: {
									type: 'file',
									id: id1
								},
								to: {
									type: 'employee',
									id: userId
								}
							});
							customRec.setText({
								fieldId:'custrecord_ps15_attribute'+j+'_value',
								text:file1.name
							});

						}else
							customRec.setText({
								fieldId:'custrecord_ps15_attribute'+j+'_value',
								text:null
							});

						// }
					}
					else if(attributeArray[key]["type"]=='list')
					{

						var fieldIdEntered = 'inpt_'+attributeArray[key]["id"];


						customRec.setValue({
							fieldId:'custrecord_ps15_attribute'+j+'_value',
							value:context.request.parameters[fieldIdEntered]
						});


					}
					else
					{

						customRec.setValue({
							fieldId:'custrecord_ps15_attribute'+j+'_value',
							value:context.request.parameters[attributeArray[key]['id']]
						});



					}
				}	
				// to make other label & value empty

				for(var i=j+1;i<26;i++)
				{
					customRec.setText({
						fieldId:'custrecord_ps15_attribute'+i,
						text:null
					});
					customRec.setText({
						fieldId:'custrecord_ps15_attribute'+i+'_value',
						text:null
					});
				}
				var idSaved = customRec.save();

				var formObj = serverWidget.createForm({
					title: 'Saved to Attribute item record!!'
				});
				formObj.clientScriptFileId = 11705;
				context.response.writePage(formObj);

				//closeWindow();
			}

		}catch(e){

			log.debug("error", e);


		}




	}
	/*********************************************
	 * To search for item id
	 * @param value
	 * @param defaultValue
	 * @returns
	 ********************************************/
	function checkRecExisting(id)
	{
		try{
			// to create a search
			var customrecord_jj_ps15_item_attributeSearchObj = search.create({
				type: "customrecord_jj_ps15_item_attribute",
				filters:
					[
						["custrecord_ps15_child_item","anyof",id]
						],
						columns:
							[
								search.createColumn({
									name: "id",
									sort: search.Sort.ASC,
									label: "ID"
								}),
								search.createColumn({name: "custrecord_ps15_child_item", label: "Item"})
								]
			});
			var searchResultCount = customrecord_jj_ps15_item_attributeSearchObj.runPaged().count;

			if(searchResultCount>0)
			{
				var searchResult = customrecord_jj_ps15_item_attributeSearchObj.run().getRange({
					start:0,
					end:1
				}); 
				var itemId = searchResult[0].getValue({
					name: "id",
					label: "ID"
				});
				return itemId;
			}
			else
				return false;


		}catch(e)
		{
			log.debug("Err@ FN checkRecExisting",e);
		}

	}
	/*******************************************************************
	 * To assign a default value if the it is empty
	 * 
	 * @param value
	 * @param defaultValue
	 * @returns
	 ******************************************************************/
	function assignDefaultValue(value, defaultValue) {
		try {
			if (checkForParameter(value))
				return value;
			else
				return defaultValue;
		} catch (e) {
			log.debug("Err@ FN assignDefaultValue", e);
		}
	}
	/**********************************************
	 *  To check whether a value exists in parameter 
	 *  
	 **********************************************/

	function checkForParameter(parameter, parameterName) {
		if (parameter !== null && parameter !== undefined
				&& parameter !== false && parameter !== "null"
					&& parameter !== "undefined" && parameter !== "false"
						&& parameter != "" && parameter != " ") {
			return true;
		} else {
			if (parameterName)
				console.log('Empty Value found for parameter'
						+ parameterName);
			return false;
		}
	}

	/***
	 * 
	 */
	function findListId(attributeName){
		try{



			var customrecord_ps17_attr_list_mappingSearchObj = search.create({
				type: "customrecord_ps17_attr_list_mapping",
				filters:
					[
						["name","is",attributeName]
						],
						columns:
							[
								search.createColumn({
									name: "name",
									sort: search.Sort.ASC,
									label: "Name"
								}),
								search.createColumn({name: "scriptid", label: "Script ID"}),
								search.createColumn({name: "custrecord143", label: "List name"}),
								search.createColumn({name: "custrecord_list_id", label: "List ID"})
								]
			});
			var searchResultCount = customrecord_ps17_attr_list_mappingSearchObj.runPaged().count;

			customrecord_ps17_attr_list_mappingSearchObj.run().each(function(result){
				// .run().each has a limit of 4,000 results
				return true;
			});
			if(searchResultCount>0)
			{
				var searchResult = customrecord_ps17_attr_list_mappingSearchObj.run().getRange({
					start:0,
					end:1
				}); 
				var listId = searchResult[0].getValue({name: "custrecord_list_id", label: "List ID"});
				return listId;
			}
		}catch (e) {
			log.debug("Err@ FN findListId", e);
		}

	}
	return {
		onRequest: onRequest
	};

});

Suitelet for searching Category

/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
/*******************************************************************************
 * CLIENTNAME:PARKSLOPE PS 13 - Alias Naming In Category ID
 * ************************************************************************ Date :
 * 21/02/2019
 * 
 * Author: Jobin & Jismi IT Services LLP Script Description : This is to show
 * item category
 * 
 * Date created : 21/02/2019
 * 
 * REVISION HISTORY
 * 
 * Revision 1.0 ${21/02/2019} aj : created
 * 
 * 
 ******************************************************************************/
define(
		[ 'N/record', 'N/search', 'N/ui/serverWidget', 'N/url' ],
		/**
		 * @param {record}
		 *            record
		 * @param {search}
		 *            search
		 * @param {serverWidget}
		 *            serverWidget
		 * @param {url}
		 *            url
		 */
		function(record, search, serverWidget, url) {

			/**
			 * Definition of the Suitelet script trigger point.
			 * 
			 * @param {Object}
			 *            context
			 * @param {ServerRequest}
			 *            context.request - Encapsulation of the incoming
			 *            request
			 * @param {ServerResponse}
			 *            context.response - Encapsulation of the Suitelet
			 *            response
			 * @Since 2015.2
			 */
			function onRequest(context) {
				try {
					var itemId = context.request.parameters.id;
					var mode = context.request.parameters.mode;
					var keyword = context.request.parameters.custpage_search;
					
					var pageIndex = assignDefaultValue(
							context.request.parameters.pageIndex, 0);
					var recId = assignDefaultValue(context.request.parameters.custpage_hidden,context.request.parameters.recId);
					var type = assignDefaultValue(context.request.parameters.custpage_type,context.request.parameters.type);
					
					// to add a form
					var form = serverWidget.createForm({

						title : 'Item Category'
					});

					var searchField = form.addField({
						id : 'custpage_search',
						label : 'Item Category',
						type : serverWidget.FieldType.TEXT
					});
					if(checkForParameter(keyword))
						searchField.defaultValue =keyword; 
					
					var hiddenField = form.addField({
						id : 'custpage_hidden',
						label : 'Rec Id',
						type : serverWidget.FieldType.TEXT
					});
					hiddenField.defaultValue =recId; 
					hiddenField.updateDisplayType({
				  	    displayType: serverWidget.FieldDisplayType.HIDDEN
				  		});
					
					var hiddenType = form.addField({
						id : 'custpage_type',
						label : 'Type',
						type : serverWidget.FieldType.TEXT
					});
					hiddenType.defaultValue =type; 
					hiddenType.updateDisplayType({
				  	    displayType: serverWidget.FieldDisplayType.HIDDEN
				  		});
					var addOptionalButton = form.addSubmitButton({
						label : 'Search'
					});

					// show form

					
					if (context.request.method === 'POST'||mode=='post') {
						form.addButton({
							id : 'custpage_select_attribute',
							label : 'Set Attribute',
							functionName : 'setAttribute'
						});
						// to show the result
						var searchValue = context.request.parameters.custpage_search;
                     searchValue= searchValue.replace(/>/g, ">");
						
						if (checkForParameter(searchValue))
							searchField.defaultValue = searchValue;

						
						var pageIndexField = form.addField({
							id : 'pageindexfield',
							type : serverWidget.FieldType.SELECT,
							label : 'Page Index'
						}).updateLayoutType({
							layoutType : serverWidget.FieldLayoutType.STARTROW
						});
						pageIndexField.defaultValue = pageIndex;
						
						// to search the results
						var runSearchObj = searchMatchingItemCategory(
								searchValue, pageIndexField, pageIndex);

						// to show the result
						if (checkForParameter(runSearchObj)) {

							// Sublist
							var searchSublist = form.addSublist({
								id : 'custpage_search_sublist',
								type : serverWidget.SublistType.LIST,
								label : 'Matching Item Categories'
							});

							// dynamically define the column list based on the
							// saved
							var select = searchSublist.addField({
								id : 'custcol_select',
								label : 'Select',
								type : serverWidget.FieldType.CHECKBOX
							});

							// search definition
							var columns = runSearchObj.columns;

							for ( var key in columns) {
								if (columns[key].label != 'nodisplay') {
									searchSublist.addField({
										id : key,
										label : columns[key].label,
										type : serverWidget.FieldType.TEXT
									});
								}
							}

							var fieldValue;
							
							runSearchObj.result
									.forEach(function(eachRow, index) {
										for ( var key in columns) {
											if (columns[key].label != 'nodisplay') {
												fieldValue = (eachRow
														.getText(columns[key])) ? eachRow
														.getText(columns[key])
														: eachRow
																.getValue(columns[key]);
												searchSublist.setSublistValue({
													id : key,
													value : assignDefaultValue(
															fieldValue, " - "),
													line : index
												});
											}
										}
									});
						}
						log
								.debug(
										'context.request.parameters',
										JSON
												.stringify(context.request.parameters.custpage_search_sublistdata));
						form.clientScriptFileId = 11705;

					}
					
					context.response.writePage(form);

				} catch (e) {
					log.debug("Err@ FN onAction", e);
					// log.error("Err@ onAction FN ",e);

				}

			}
			/*******************************************************************
			 * Function to search the matching item category
			 * 
			 * @param e
			 * @returns {String}
			 * 
			 * Created on 21-Feb-2019 by aj
			 ******************************************************************/
			function searchMatchingItemCategory(searchValue, pageIndexField,
					pageIndex) {
				try {
					var customrecord_jj_ps13_item_categorySearchObj = search
							.create({
								type : "customrecord_jj_ps13_item_category",
								filters : [ [ "custrecord_jj_ps13_alias_name",
										"contains", searchValue ] ],
								columns : [ search.createColumn({
									name : "name",
									sort : search.Sort.ASC,
									label : "Name"
								}), search.createColumn({
									name : "custrecord_jj_ps13_alias_name",
									label : "Alias Name"
								}) ]
							});
					var searchResultCount = customrecord_jj_ps13_item_categorySearchObj
							.runPaged().count;
					log
							.debug(
									"customrecord_jj_ps13_item_categorySearchObj result count",
									searchResultCount);
					customrecord_jj_ps13_item_categorySearchObj.run().each(
							function(result) {
								// .run().each has a limit of 4,000 results
								return true;
							});

					return formatSavedSearch(
							customrecord_jj_ps13_item_categorySearchObj,
							pageIndexField, pageIndex);

				} catch (e) {
					log.debug("Err@ FN selectItemCategory", e);
					// log.error("Err@ selectItemCategory FN ",e);

				}
			}
			/*******************************************************************
			 * To assign a default value if the it is empty
			 * 
			 * @param value
			 * @param defaultValue
			 * @returns
			 ******************************************************************/
			function assignDefaultValue(value, defaultValue) {
				try {
					if (checkForParameter(value))
						return value;
					else
						return defaultValue;
				} catch (e) {
					log.debug("Err@ FN assignDefaultValue", e);
				}
			}

			/*******************************************************************
			 * To format the search according to page Index
			 ******************************************************************/
			function formatSavedSearch(savedSearchObj, pageIndexField,
					pageIndex) {
				try {
					var columns = savedSearchObj.columns;
					var columnsData = {};
					columns.forEach(function(result, counter) {
						// columnsData['custpage_col_' + counter] = result;
						columnsData[(columnsData[result.name]) ? (result.name
								+ '_' + counter) : (result.name)] = result;
					});
					// Paginating Results
					var searchPageRanges, size;
					try {
						if (savedSearchObj.length < 100) {
							size = savedSearchObj.length;
						} else {
							size = 100;
						}

						searchPageRanges = savedSearchObj.runPaged({
							pageSize : size
						});
					} catch (err) {
						return {
							status : true,
							columns : columnsData,
							result : []
						};
					}
				
					if (searchPageRanges.pageRanges.length < 1)
						return {
							status : true,
							columns : columnsData,
							result : []
						};
					for (var i = 0, j = searchPageRanges.pageRanges.length; i < j; i++) {
						pageIndexField.addSelectOption({
							value : i,
							text : i + 1 + ' of ' + j + ' Pages'
						});
					}
					// Fetching Row Data
					var rowData = [];
					searchPageRanges.fetch({
						index : pageIndex
					}).data.forEach(function(result) {
						rowData.push(result);
					});

					return {
						status : true,
						columns : columnsData,
						result : rowData
					};

				} catch (e) {
					log.debug("Err@ FN formatSavedSearch", e.message);
					// log.error("Err@ onAction FN ",e.message);
					// console.log("Err@ FN =",e.message);
				}

			}
			/*******************************************************************
			 * To check whether a value exists in parameter
			 ******************************************************************/
			function checkForParameter(parameter, parameterName) {
				try {
					if (parameter !== null && parameter !== undefined
							&& parameter !== false && parameter !== "null"
							&& parameter !== "undefined"
							&& parameter !== "false" && parameter != ""
							&& parameter != " ") {
						return true;
					} else {
						if (parameterName)
							log.debug('Empty Value found',
									'Empty Value for parameter '
											+ parameterName);
						return false;
					}
				} catch (e) {
					log.debug("Err@ FN checkForParameter", e);
				}
			}

			return {
				onRequest : onRequest,
				searchMatchingItemCategory : searchMatchingItemCategory
			};

		});

Leave a comment

Your email address will not be published. Required fields are marked *