How do I store a value that was set using a pageInit function? - netsuite

I have a client script that sets a field value based on a joined record. I can display the desired value in edit mode in the browser, but on save, the value disappears from the UI.
function pageInit(context) {
var currentRecord = context.currentRecord;
var cusRec = currentRecord.getValue({
fieldId: 'custrecord3'
});
var cdrCus = record.load({
type: record.Type.CUSTOMER,
id: cusRec
});
var cdrAddr = cdrCus.getValue('defaultaddress');
console.log(cdrAddr);
currentRecord.setValue({
fieldId: 'custrecord_cdr_bill_to',
value: cdrAddr
});
}
On save, the value set at currentRecord.setValue({}); disappears from the UI. I would like to set this value on page load and persist it to the database on save. I attempted to add currentRecord.save(); but this resulted in an error: "currentRecord.save(); is not a function"
Thank you in advance for any assistance you are able to provide!

function pageInit(context)
{
log.debug('Mode:', context.mode);
var currentRecord = context.currentRecord;
if (context.mode == 'edit')
{
var cdrAddr = currentRecord.getValue('defaultaddress');
console.log(cdrAddr);
currentRecord.setValue({
fieldId: 'custrecord_cdr_bill_to',
value: cdrAddr
});
}
}
Try this approach. As client script is UI script no need to load the record.Here I am using edit mode so this script should only trigger in edit mode.

Related

Set line_item list value in before Load of form in NetSuite

I am trying to update the date of a field if "item_id is 900",
define(['N/record', 'N/search'],
function(record, search){
function salesorderbeforeload(context){
var currentRecord = context.newRecord;
var sublistName="item";
var start_Date="custcol_atlas_contract_start_date";
var end_date="custcol_atlas_contract_end_date";
var lines = currentRecord.getLineCount({sublistId: 'item'});
log.debug({title:'lines',details:lines});
for (var i = 0; i < lines; i++) {
var itemId = (currentRecord.getSublistValue({
sublistId: "item",
fieldId: "item",
line: i
}));
var value=itemId;
if(value=="900")
{
currentRecord.setSublistValue({
sublistId: "item",
fieldId: "custcol_atlas_contract_start_date",
line: 0,
value: "2021-09-09T07:00:00.000Z"
});
}
}
}
return{
beforeLoad: salesorderbeforeload
};
}
);
The above code will fetch the line item id as value , and if the value is 900 it will set the date to the following
Evrything is working perfectly except for this code,
currentRecord.setSublistValue({
sublistId: "item",
fieldId: "custcol_atlas_contract_start_date",
line: 0,
value: "2021-09-09T07:00:00.000Z"
});
record=currentRecord.setSublistValue({
sublistId: "item",
fieldId: "quantity",
line: 0,
value: "3"
});
Even the quantity is not updating.
Thanks in advance
You cannot update existing records so that ultimately will be your issue.
You may be able to fix this in a before submit event when the record is saved or in a Client Event script.
As far as the code supplied though you are not advancing the line index. You should have:
currentRecord.setSublistValue({
sublistId: "item",
fieldId: "custcol_atlas_contract_start_date",
line: i, // NOT 0
value: "2021-09-09T07:00:00.000Z"
});
but after that is your custom field an actual date time or is it a text field?
if you are trying to store a date you'll need to parse your ISO formatted date string to an actual date. This is different from SS1 where dates had to be date formatted strings.
As far as item groups go the custom field needs to be configured to save the value for group items.
There is a checkbox, "Store with Item Groups" on the field definition
Did you try saving the record after all the updates?
You can try this approach where you load the record first, then check for your conditions, accordingly update the fields and then perform a record save.
var objRecord = record.load({
type: record.Type.SALES_ORDER,
id: 157,
isDynamic: true,
});
Then you can iterate over the line items. Use FOR LOOP
for(var j=0; j<numLines; j++) {
//fetch the item_id using getCurrentSublistValue
if(item_id == 900) {
//Perform the setSublistValue
}
}
And finally,
objRecord.save();
Give this a try, even I'm not sure of this approach. Let me know in case of any issues.

Netsuite SS 2.0 - Populating Sublist data on Suitelet

I have a Suitelet that returns a form page that a user can specify data on, and when it’s retrieved, the default values are populated based on the data the user entered the previous time.ie. Data is saved on and sourced from a Custom Record.
I decided to add an Inline Editor Sublist (don't know what I was sniffing).However I haven’t been able to populate data onto the Sublist when the Suitelet is retrieved.I am aware it was possible in SS 1.0, but I refuse to use 1.0 😉
Basically the question is: When adding an Inline Editor Sublist to a Suitelet, how can I then populate it with data?
Please create a Client script for your Suitelet and the client script as a reference in your suitelet as given example. In your client Script on pageInit Function run a saved search and populate the Sublist.
Client Script:
var rec = context.currentRecord;
var objSublistSearch = search.load({ id: 'customsearch11208' });
var filter = search.createFilter({ name: 'custrecordzab_s_customer', operator: search.Operator.ANYOF, values: customerid }); objSublistSearch.filters.push(filter);
var sublist_count = 0 objSublistSearch.run().each(function(result) {
var internalid = result.getValue('internalid');
rec.setCurrentSublistValue({ sublistId: 'custpage_contractsublist', fieldId: 'custpage_internalcontractid', value: internalid, line: sublistCount, ignoreFieldChange: true });
rec.commitLine({
sublistId: 'custpage_contractsublist'
});
sublist_count++;
}

How to dynamically filter sublist based on addField?

I have a Suitelet that calls a sublist but I would like to trigger a filter when an "addButton" is clicked.
Suitelet:
var form = serverWidget.createForm({ title : 'Unbilled Orders', hideNavBar : false });
form.addField({id: 'name_criteria', label: 'Name', type: serverWidget.FieldType.MULTISELECT, source: 'customer'});
form.addButton({label: 'Filter',id: 'custpage_mybutton',functionName: 'myButtonFunction()'});
var name_field = context.request.parameters.name_criteria;
//# Filter does not work as name_field='' #
var objSublistSearch = search.load({ id: SEARCH_ID });
var filterArray = objSublistSearch.filters;
filterArray.push(search.createFilter({ name: 'entity', operator: search.Operator.ANYOF, values: name_field }));
objSublistSearch.filters = filterArray;
var SublistSearch = objSublistSearch.run();
...
context.response.writePage(form);
Client script (does not update the sublist):
function myButtonFunction() {
// Load current record in order to manipulate it
var objRecord = currentRecord.get()
var field2 = objRecord.getValue({
fieldId: 'name_criteria',
});
log.debug("field2",field2 );}
You can use currentRecord's insertLine and removeLine methods to update the sublist but please note that they will only work for editable sublists (INLINEEDITOR and EDITOR).
If you are using SublistType.LIST, you will have to reload the suitelet in your myButtonFunction().
You're only looking at the "body" field not a sublist.
Try using sublist functions within the client script.
var lines = objRecord.getLineCount({sublistId:'custpage_sublistid'});
for (line = 0; line < lines; line++) {
objRecord.selectLine({sublistId:'custpage_sublistid', line:line });
var existingValue = objRecord.getSublistValue({sublistId:'custpage_sublistid', fieldId:'custpage_columnid', line: line });
objRecord.setCurrentSublistValue({sublistId:'custpage_sublistid', fieldId:'custpage_columnid', value: 12345 });
// do other stuff
}

How to fix 'Please enter a value for amount.' when creating NetSuite invoice with restlet?

I'm creating a NetSuite invoice in dynamic mode with SuiteScript 2.0, and when I run commitLine on my first item, it errors with 'Please enter a value for amount.' even though I have already supplied it using setCurrentSublistValue.
The relevant section of code is START CREATING ITEM through FINISHED CREATING ITEM, but I've included the full restlet in case the problem is in my setup.
Here's the JSON data I'm using to generate the item:
{"item":26,"amount":5706.48,"custcol_unit_price":"7.863035405","quantity":725735,"description":"July Impressions - 2019 Digital (April-July) - Custom Affinity (CAF) Dynamic CPM 7.5","line":1}
I'm logging a call to getCurrentSublistValue immediately after the setter, to ensure the system is accepting the value I send, and get 5706.48 back out for amount, so I believe setCurrentSublistValue is inserting it.
/**
*#NApiVersion 2.x
*#NScriptType Restlet
*/
define(['N/record', 'N/error', 'N/log'],
function(record, error, log) {
function post(context) {
log.audit("invoice", context);
var rec = record.create({ type: "invoice", isDynamic: true });
for (var fldName in context) {
if (context.hasOwnProperty(fldName)) {
if (fldName === "trandate") {
rec.setValue(fldName, new Date(context[fldName]));
} else if (fldName === "items") {
var items = context[fldName]
for (var idx in items) {
var item = items[idx]
// START CREATING ITEM
log.audit('item', item)
rec.selectNewLine({ sublistId: 'item' });
for (var itemFldName in item) {
log.audit(itemFldName, item[itemFldName])
rec.setCurrentSublistValue({
sublistId: 'item',
fieldId: itemFldName,
value: item[itemFldName]
})
log.audit("current value", rec.getCurrentSublistValue({ sublistId: 'item', fieldId: itemFldName }))
}
rec.commitLine({ sublistId: 'item' });
// FINISHED CREATING ITEM
}
} else {
rec.setValue(fldName, context[fldName]);
}
}
}
var recordId = rec.save();
return { success: true, message: recordId }
}
return {
post: post
};
}
);
This is the error I'm seeing in the logs (line 34 is the commitLine call):
{"type":"error.SuiteScriptError","name":"USER_ERROR","message":"Please enter a value for amount.","stack":["anonymous(N/serverRecordService)","post(/SuiteScripts/api/submitInvoice.js:34)"],"cause":{"type":"internal error","code":"USER_ERROR","details":"Please enter a value for amount.","userEvent":null,"stackTrace":["anonymous(N/serverRecordService)","post(/SuiteScripts/api/submitInvoice.js:34)"],"notifyOff":false},"id":"","notifyOff":false,"userFacing":false}
Thanks in advance for any insight!
Try setting the quantity to 1. System might be overwriting your value with a calculated value of quantity * amount when you commit the line.
You are setting the Amount first, then the Quantity, and you are not setting the Rate. Because you are working with the record in Dynamic mode, you will need to set field values in the exact same order as you would in the UI, otherwise your data will be off.
If you need to continue working in Dynamic mode, then you will likely need to do a few things:
Ensure that sourcing happens when you set the Item field by setting the forceSyncSourcing option of setCurrentSublistValue to true. This should ensure that any columns dependent on the Item are set correctly.
Ensure you are setting the Item columns in the correct order; probably Item, then Quantity, then Amount. This way, Dynamic mode should hopefully not recalculate your Amount.
I generally avoid this problem entirely by working in Standard mode instead of Dynamic. I have found it extremely rare that I need to work in Dynamic mode. In Standard mode, field order no longer matters as you let the server figure it out after you submit the entire record rather than in real-time as you set each field.

suitescript 2.0:When I use removeSelectOption,throw a 'TypeError Cannot read property "removeSelectOption" of null' error

There is a js error When I use the removeSelectOption to remove all of the dropdown list.The code as follow:
function fieldChanged(scriptContext) {
if(scriptContext.fieldId == 'class'){
var currentRecord = scriptContext.currentRecord;
var brand_id = currentRecord.getValue({fieldId:'class'});
if(brand_id){
var itemList = [];
var itemField = currentRecord.getField({
fieldId: 'item'
});
itemField.removeSelectOption({
value: null,
});
search.create({
type: search.Type.INVENTORY_ITEM,
columns:[{name:'internalid'}],
filters:[
['custitem30',search.Operator.ANYOF,brand_id]
]
}).run().each(function(result){
item_id = result.getValue({
name:'internalid'
});
var in_item = record.load({
type: record.Type.SALES_ORDER,
id: item_id,
});
itemList.push(item_id);
itemField.insertSelectOption({
value: item_id,
text: in_item
});
console.log('item_id:' + item_id);
});
console.log('itemList:' + itemList);
}
}
}
And the api document in help center said -- To remove all options from the list, set this field to null, as follows:
field.removeSelectOption({
value: null,
});
If I want to remove all options from the dropdown list,what should I do?
Thanks.
Create a item saved search
2.Transaction form Item Filter field select that Saved Search.
As your question i assumed that you only show inventory item in item Field.
First of all you have get the field object
var field = currentRecord.getField({
fieldId: 'Your Field ID'
});
then use this below code
field.removeSelectOption({
value: null,
});
you cannot remove the field items from the list that are created from UI and have a source.
you can have a alert for it on field change

Resources