/** *@NApiVersion 2.x *@NScriptType restlet */ define(['N/record', 'N/search', 'N/error', 'N/log'], function (record, search, error) { function findById(type, id) { return record.load({ type: type, id: id, isDynamic: true }); } function overwriteSublistLine(rec, sublistId, lineNumber, item) { // Select the existing line rec.selectLine({ sublistId: sublistId, line: lineNumber }); // Update all fields in the line for (var subField in item) { rec.setCurrentSublistValue({ sublistId: sublistId, fieldId: subField, value: item[subField] }); } // Commit the line to save changes rec.commitLine({ sublistId: sublistId }); log.debug('Overwritten line', 'Line ' + lineNumber + ' in sublist ' + sublistId + ' has been overwritten.'); } function post(context) { context.errors = []; for (var i = 0; i < context.records.length; i++) { var r = context.records[i]; var rec = null; try { if (!!r.id) { rec = findById(context.recordType, r.id); log.debug('Found record with ID ' + rec.id); } else { rec = record.create({ type: context.recordType, isDynamic: true }); log.debug('Creating new record'); } for (var field in r) { if (field !== 'id') { log.debug('Getting field ' + field); var f = rec.getField({fieldId: field}); if (f) { if (f.type === 'date') { if (r[field]) { rec.setValue(field, new Date(r[field])); }else{ rec.setValue(field,null); } } else if (f.type === 'checkbox') { rec.setValue(field, r[field] === 't' || r[field] === 'T' || r[field] === 'true' || r[field] === 'True'); } else { rec.setValue(field, r[field]); } } else { log.debug('Getting sublist for field ' + field); var list = rec.getSublist({sublistId: field}) if (list) { var items = JSON.parse(r[field]); for (var j = 0; j < items.length; j++) { var item = items[j]; // Check if lineNumber is provided for overwriting if (item.lineNumber !== undefined) { overwriteSublistLine(rec, field, item.lineNumber, item); } else { // If no lineNumber is provided, create a new line rec.selectNewLine({ sublistId: field }); for (var subField in item) { rec.setCurrentSublistValue({ sublistId: field, fieldId: subField, value: item[subField] }); } rec.commitLine({ sublistId: field }); log.debug('Created new line', 'New line created in sublist ' + field); } } } } } } rec.save(); log.debug('Successfully saved record'); } catch (e) { context.errors.push({ message: e.message, index: i }); if (!context.continueOnError) { break; } } } context.records = null; return context; } return { post: post } });