Hello team, I am trying to accomplish the followin...
# suitescript
i
Hello team, I am trying to accomplish the following business process using the following code: I have created a form (with the suitelet) named "Customer Equipment" which allows to register a set of items for use on a given vehicle of a customer. On this form I have a customer type field in which we select a given customer and several item and serialized item type fields. Currently the item and serialized item fields return all items contained in stock. However, business logic would like us to have in its fields only the items sold to the customer (therefore available in the customer's stock) and when a serialized item is selected, it is deleted from the list when creating a a new "Customer equipment". So I wrote a "User Event Script" type script to do this. However, the mapping between the "Customer" field and the "Item" field does not work, as does the removal of the selected "Serialized item". Can you take a look at my code and give me your ideas?
Copy code
/**
 * @NApiVersion 2.x
 * @NScriptType UserEventScript
 * @NModuleScope SameAccount
 */
define(['N/record', 'N/search','N/log', 'N/ui/serverWidget'],
function(record, search, log, serverWidget) {
   
	function getInputData(bmId){
	    var bm = {
	        internalid: -1,
	        solditem: " ",
	        clientname: " ",
	    }


	    if(bmId > 0){
	    	var transactionSearchObj = search.create({
	    		   type: "transaction",
	    		   filters:
	    		   [
	    		      ["itemsubof","anyof","2054"], 
	    		      "AND", 
	    		      ["status","anyof","ItemShip:C"]
	    		   ],
	    		   columns:
	    		   [
	    		      search.createColumn({name: "internalid", label: "Internal ID"}),
	    		      search.createColumn({
	    		         name: "formulatext",
	    		         formula: "SUBSTR({item}, 13, 10)",
	    		         label: "Formula (Text)"
	    		      }),
	    		      search.createColumn({name: "entity", label: "Name"})
	    		   ]
	    		});
	    		var searchResultCount = transactionSearchObj.runPaged().count; // Nombre total de résultats de toutes les pages
	    		log.debug("transactionSearchObj result count",searchResultCount);
	    		transactionSearchObj.run().each(function(result){
	    			bm.internalid = result.getValue({name: 'internalid'});
		            bm.solditem = result.getValue({name: 'item'});
		            bm.clientname = result.getValue({name: 'entity'});
	    		});
	    }
	    return bm;
	}
	
    function beforeLoad(scriptContext) {
    	var form = scriptContext.form;

    	//Création d'un nouveau champ pour stocker les types de boitiers vendu au client X
    	var field = form.addField({id : 'custpage_new_boitier_field', type : serverWidget.FieldType.SELECT, label : 'Type de boitier disponible dans le stock du client' });
    	field.defaultValue = '';
    	if(scriptContext.type == 'edit' || scriptContext.type == 'view'){
    	    var cRecord = scriptContext.newRecord;
    	    var bm = getInputData(cRecord.getValue({fieldId: 'id'}));
    	    
    	    if(bm.internalid > 0){
    	       field.defaultValue = bm.solditem;
    	    }
    	}

    }

    function beforeSubmit(scriptContext) {
        //Enregistrer les données liées à l'Equipement client existant en cas de modification
        try{
            var cRecord = scriptContext.newRecord;
            var toSave = false;
            var bm = getInputData(scriptContext.newRecord.id);
            var currentCustomer = cRecord.getValue({fieldId: 'custrecord_cam_customername'});

            //On ajoute les équipement recueillis dans le Saved search dans le champ précédemment créé
            if(currentCustomer != ''){
            	for(var i = 0; i < bm.length; i++){
            		if(currentCustomer == bm.clientname[i]){
            			if(bm.solditem[i] != bm.solditem[i-1]){
            				field.insertSelectOption({
                			    value: bm.solditem[i]
                			});
            				
            			}
            		}
            	}
            	selectedBoitier = cRecord.getValue({fieldId:'custrecord_cam_serialized_number'});
            	
            }

            //Si on supprime l'Equipement client, alors on supprime l'enregistrement associé
            if(scriptContext.type == 'delete'){
                var bm = getInputData(scriptContext.oldRecord.id);
                if(bm.internalid > 0){
                    record.delete({
                        type: 'customrecord_cam_equipment_client',
                        id: bm.internalid,
                     });
                }
            }


            //Vérifier et enregistrer les modifications de l'Equipement client
            if((scriptContext.type == 'edit' || scriptContext.type == 'view') && bm.internalid > 0){
                var bmFields = record.load({
                    type: 'customrecord_cam_equipment_client', 
                    id: bm.internalid,
                    isDynamic: true,
                });
                
                var newType = cRecord.getValue({fieldId: 'custpage_new_boitier_field'});


                if(newType != bm.type){
                    toSave = true;
                    bmFields.setValue({
                        fieldId: 'custrecord_yourco_bin_move_type',
                        value: newType
                    });
                }


                if(toSave == true){
                    bmFields.save();
                }
            }
        }catch(e){
            log.error({
                title: "Erreur d'enregistrement des données liées à l'éauipement client",
                details: e.message
            });
        }

    }

   
    function afterSubmit(scriptContext) {
        //Données liées à la création d'un nouvel équipement client
        try{
            if(scriptContext.type == 'create'){
                var cRecord = scriptContext.newRecord;


                var bmFields = record.create({
                    type: 'customrecord_cam_equipment_client', 
                    isDynamic: false
                });
                bmFields.setValue({
                    fieldId: 'custpage_new_boitier_field',
                    value: scriptContext.newRecord.id
                });
                bmFields.setValue({
                    fieldId: 'custpage_new_boitier_field',
                    value: cRecord.getValue({fieldId: 'internalid'})
                });


                bmFields.save();
            }
        }catch(e){
            log.error({
                title: "Erreur d'enregistrement des données liées à l'éauipement client",
                details: e.message
            });
        }

    }

    return {
        beforeLoad: beforeLoad,
        beforeSubmit: beforeSubmit,
        afterSubmit: afterSubmit
    };
    
});
b
your code is weird
and doesnt match your description
if you are starting from a suitelet, then your user event script will not interact with the suitelet's form
i
it interacts however since in this script I dynamically created a field and this takes effect during the deployment
What approach do you suggest to me?
b
not really sure what you are doing, so cant suggest anything
again, none of your code looks like it could work
mostly becuase nothing triggers anything else
for example, your after submit function tries setting custpage fields, that approach is doomed
user event scripts dont trigger other user event scripts
your before submit script tries to add select options to a field
that approach is doomed, those options are for a record that has already been submitted
the before submit does a bunch of other stuff, but i dont really know what the user event script is deployed to, so i can tell how relevant it is
all of this is moot if you are trying to make this code interact with the select options available in your suitelet
i
so the User Event Script type is not appropriate right
b
i would say so, but i dont understand your code enough to tell
my suggestion would be a client script added to your suitelets form via Form.clientScriptModulePath
your other choice is to control the select options in the suitelet while you are generating the form
i
If I give you a rundown. In fact, each time we take delivery of a customer's vehicle to install tracking equipment, he is provided with a summary sheet of the equipment that will be installed on his vehicle. However, the equipment to be installed is that purchased by the customer. Currently, the form that I produced gives all the equipment that we have in stock, which makes the task complex for the technician who develops this task. It is therefore a question first of all of filtering the content of the item fields according to the selected customer. and subsequently with the same principle of transferring serialized items to the customer's stock, automatically deleting the selected serialized item. I am sending you a picture of the form here. The form is of type item
b
um, this doesnt match what you first described
at no point here do i see a suitelet
the form also does not look like a form for a item record
i
In red we have the customer selection field, in blue the item type field which contains the list of item types we have, in black a serialized item type field linked to the item type field and containing the serialized items attached to an item type
yeah it's a custom record type
b
The form is of type item
and what is that supposed to mean then
i
it's a form created using the approach describe in this link https://www.linkedin.com/pulse/netsuite-bin-transfer-custom-fields-andre-cameron
if you can look at it
b
same problem
i see no relation between what you are describing and his code
his code described a way to use a custom record to extend a native record without customization options
i
ok assuming no code has already suggested what approach would you suggest please?
b
the first attempt should be trying to use Sourcing or Filtering on the custom fields to get its select options to work how you want it to
if that fails, then you use a beforeLoad user event entry point to add your own fields
use a Client Script fieldChanged (and potentially pageInit if you didnt add options in the beforeLoad) to insert or remove your select options on the fields you added in the user event script
finally, use the saveRecord entry point to copy the values from your scripted fields to the real fields (alternativly you can do this in the beforeSubmit)
if you want to overengineer the solution, then you would also make the beforeSubmit check that the values in your native custom fields are valid according to your restrictions and throw an error if they dont validate
i
either the Sourcing or Filtering option doesn't allow me to join the transaction type (item fullfillment or Sales order) then with that option, I can't have the list of purchased items in a item field
Good morning
ok thanks @battk let me try that I give you a feedback