### Creating Reusable Helper Modules
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Provides an example of a helper module that encapsulates shared utility logic. These modules can be imported across various views and models to keep the codebase DRY and maintainable.
```javascript
define('Example.UserPreferences.Helper', ['Utils'], function (Utils) {
'use strict';
return {
getTypeOptions: function getTypeOptions() {
return [
{ internalid: '1', name: Utils.translate('Color') },
{ internalid: '2', name: Utils.translate('Size') }
];
},
getTypeOptionIds: function getTypeOptionIds() {
var ids = [];
this.getTypeOptions().forEach(function (option) {
ids.push(option.internalid);
});
return ids
}
}
});
```
--------------------------------
### NetSuite CRUD Operations with N/record and N/search (SuiteScript)
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
This SuiteScript 2.x code defines a backend model for managing 'customrecord_user_preferences'. It includes functions for GET (read with filtering), POST (create), PUT (update), and DELETE operations on records. It leverages the N/record module for record manipulation and the N/search module for querying records. The model is designed to be used within a NetSuite environment.
```javascript
// Example.UserPreferences.Model.js - SuiteScript backend model
/**
* @NApiVersion 2.x
* @NModuleScope TargetAccount
*/
define([
'N/record',
'N/runtime',
'N/search'
], function (
record,
runtime,
search
) {
'use strict';
var ExampleUserPreferencesModel = {
// GET - Read records with optional filtering
get: function (request) {
var type = 'customrecord_user_preferences';
var filters = [
['custrecord_user_preferences_owner', search.Operator.ANYOF, runtime.getCurrentUser().id]
];
var columns = ['internalid', 'custrecord_user_preferences_type', 'custrecord_user_preferences_value'];
// Add filter for single record fetch
if (request.parameters.internalid) {
filters.push('and', [
['internalid', search.Operator.IS, request.parameters.internalid]
]);
}
var searchResults = search.create({
type: type,
filters: filters,
columns: columns
}).run().getRange({ start: 0, end: 1000 });
var mappedResults = searchResults.map(function (result) {
return {
internalid: result.getValue('internalid'),
type: result.getValue('custrecord_user_preferences_type'),
value: result.getValue('custrecord_user_preferences_value')
}
});
// Return single object or array
return mappedResults.length == 1 ? mappedResults[0] : mappedResults
},
// POST - Create new record
post: function (request) {
var body = JSON.parse(request.body);
var userPreferences = record.create({
type: 'customrecord_user_preferences'
});
userPreferences.setValue({
fieldId: 'custrecord_user_preferences_owner',
value: runtime.getCurrentUser().id
});
userPreferences.setValue({
fieldId: 'custrecord_user_preferences_type',
value: body.type
});
userPreferences.setValue({
fieldId: 'custrecord_user_preferences_value',
value: body.value
});
return userPreferences.save()
},
// PUT - Update existing record
put: function (request) {
var body = JSON.parse(request.body);
var userPreferences = record.load({
type: 'customrecord_user_preferences',
id: request.parameters.internalid
});
userPreferences.setValue({
fieldId: 'custrecord_user_preferences_type',
value: body.type
});
userPreferences.setValue({
fieldId: 'custrecord_user_preferences_value',
value: body.value
});
return userPreferences.save()
},
// DELETE - Remove record
delete: function (request) {
return record.delete({
type: 'customrecord_user_preferences',
id: request.parameters.internalid
})
}
}
return ExampleUserPreferencesModel
});
```
--------------------------------
### NetSuite Entry Point Module with mountToApp (JavaScript)
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Demonstrates the entry point module for SuiteCommerce extensions, registering page types, routes, and menu items. It utilizes the `mountToApp` function to interact with the extension container and register components like PageType and MyAccountMenu. This code is essential for initializing custom functionality within the SuiteCommerce application.
```javascript
define('Example.UserPreferences', [
'Example.UserPreferences.List.View',
'Example.UserPreferences.Edit.View',
'Utils'
], function (
ExampleUserPreferencesListView,
ExampleUserPreferencesEditView,
Utils
) {
'use strict';
return {
mountToApp: function (container) {
var PageType = container.getComponent('PageType');
// Register list page
PageType.registerPageType({
name: 'example_userpreferences_list',
routes: ['preferences'],
view: ExampleUserPreferencesListView,
defaultTemplate: {
name: 'example_userpreferences_list.tpl',
displayName: 'User Preferences List'
}
});
// Register edit page with dynamic route parameter
PageType.registerPageType({
name: 'example_userpreferences_edit',
routes: ['preferences/add', 'preferences/:id'],
view: ExampleUserPreferencesEditView,
defaultTemplate: {
name: 'example_userpreferences_edit.tpl',
displayName: 'User Preferences Edit'
}
});
// Add menu item to My Account navigation
var MyAccountMenu = container.getComponent('MyAccountMenu');
MyAccountMenu.addGroupEntry({
groupid: 'settings',
id: 'userpreferenceslist',
name: Utils.translate('User Preferences'),
url: 'preferences',
index: 99
});
}
}
});
```
--------------------------------
### Implementing SCCollectionView for List Rendering
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Shows how to use SCCollectionView to render collections of items. It includes logic for automatic re-rendering on collection changes and mapping collection models to individual cell views.
```javascript
define('Example.UserPreferences.Collection.View', ['SCCollectionView', 'Example.UserPreferences.Details.View', 'example_userpreferences_collection.tpl', 'jQuery'], function (SCCollectionViewModule, ExampleUserPreferencesDetailsView, example_userpreferences_collection_tpl, jQuery) {
'use strict';
var SCCollectionView = SCCollectionViewModule.SCCollectionView;
function ExampleUserPreferencesCollectionView(options) {
SCCollectionView.call(this, options.collection);
this.collection = options.collection;
this.template = example_userpreferences_collection_tpl;
var self = this;
this.collection.on('reset sync add remove change destroy', function () {
self.render();
});
this.removeUserPreference = function (e) {
e.preventDefault();
var id = jQuery(e.target).data('id');
var model = this.collection.get(id);
model.destroy();
}
}
ExampleUserPreferencesCollectionView.prototype = Object.create(SCCollectionView.prototype);
ExampleUserPreferencesCollectionView.prototype.constructor = ExampleUserPreferencesCollectionView;
ExampleUserPreferencesCollectionView.prototype.getCellViewsPerRow = function () {
return 1
}
ExampleUserPreferencesCollectionView.prototype.getCellViewInstance = function (model) {
return new ExampleUserPreferencesDetailsView({ model: model })
}
ExampleUserPreferencesCollectionView.prototype.getEvents = function () {
return { 'click button[data-action="delete"]': 'removeUserPreference' }
}
return ExampleUserPreferencesCollectionView
});
```
--------------------------------
### Implement REST Service Controller in SuiteScript 2.x
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
This snippet demonstrates a standard SuiteScript 2.x service module. It validates user authentication and routes incoming HTTP requests to the appropriate model methods based on the request type.
```javascript
define([
'./Example.UserPreferences.Model',
'N/runtime'
], function (
ExampleUserPreferencesModel,
runtime
) {
'use strict';
function isLoggedIn() {
var user = runtime.getCurrentUser();
return user.id > 0 && user.role !== 17;
}
function service(context) {
var response = {};
if (isLoggedIn()) {
switch (context.request.method) {
case 'GET':
response = ExampleUserPreferencesModel.get(context.request);
break;
case 'POST':
response = ExampleUserPreferencesModel.post(context.request);
break;
case 'PUT':
response = ExampleUserPreferencesModel.put(context.request);
break;
case 'DELETE':
response = ExampleUserPreferencesModel.delete(context.request);
break;
default:
response = { type: 'error', message: 'Method not supported: ' + context.request.method };
}
} else {
response = { type: 'error', message: 'You must be logged in to use this service' };
}
context.response.write(JSON.stringify(response));
}
return { service: service };
});
```
--------------------------------
### Implement List View with PageType.Base.View in JavaScript
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Extends PageType.Base.View to create a list view for user preferences. It handles asynchronous data fetching using `beforeShowContent` and registers child views for rendering. Dependencies include collection, collection view, template, and utility modules.
```javascript
define('Example.UserPreferences.List.View', [
'PageType.Base.View',
'Example.UserPreferences.Collection',
'Example.UserPreferences.Collection.View',
'example_userpreferences_list.tpl',
'Utils'
], function (
PageTypeBaseView,
ExampleUserPreferencesCollection,
ExampleUserPreferencesCollectionView,
example_userpreferences_list_tpl,
Utils
) {
'use strict';
return PageTypeBaseView.PageTypeBaseView.extend({
template: example_userpreferences_list_tpl,
initialize: function initialize() {
this.collection = new ExampleUserPreferencesCollection();
},
getSelectedMenu: function getSelectedMenu() {
return 'userpreferenceslist'
},
// Async data loading before view renders
beforeShowContent: function beforeShowContent() {
this.getBreadcrumbPages = function () {
return [{
text: Utils.translate('User Preferences'),
href: '/preferences'
}]
}
this.title = Utils.translate('User Preferences');
// Register child views
this.childViews = {
'Example.UserPreferences.Collection.View': function () {
return new ExampleUserPreferencesCollectionView({
collection: this.collection
})
}
}
// Return promise - view renders after data loads
return this.collection.fetch()
}
})
});
```
--------------------------------
### Styling Components with SuiteCommerce SCSS Variables
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Shows how to extend core SuiteCommerce styles using SCSS variables to ensure UI consistency. This approach leverages existing theme classes and padding variables to maintain design standards.
```scss
.user-preferences-list-header {
@extend .list-header;
display: inline-block;
width: 100%;
}
.user-preferences-list-title {
@extend .list-header-title;
float: left;
}
.user-preferences-list-button-new {
@extend .list-header-button;
}
.user-preferences-list-table {
@extend .recordviews-table;
}
.user-preferences-list-table-header {
@extend .recordviews-row-header;
}
.user-preferences-list-table-header-type,
.user-preferences-list-table-header-value,
.user-preferences-list-table-header-actions {
padding: $sc-padding-lv3;
}
.user-preferences-list-table-header-actions {
width: 30%;
}
.user-preferences-list-table-row {
@extend .recordviews-row;
}
```
--------------------------------
### Injecting Child Views into SuiteCommerce Components
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Demonstrates how to use the addChildViews method on component APIs like PLP to inject custom views into existing commerce pages. This requires a module that implements the mountToApp method to interact with the application container.
```javascript
define('CDRExample', ['CDRExample.View'], function (CDRExampleView) {
'use strict';
return {
mountToApp: function mountToApp(container) {
var PLP = container.getComponent('PLP');
if (PLP) {
PLP.addChildViews(PLP.PLP_VIEW, {
'ItemViews.Price': {
'CDRExample.View': {
childViewIndex: 0,
childViewConstructor: function () {
return new CDRExampleView({ PLP: PLP })
}
}
}
})
}
}
}
});
```
--------------------------------
### Implementing SCFormView for Form Handling
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
Demonstrates how to extend SCFormView to manage form validation, submission, and field change events. It includes custom event handling for form submission and field validation logic.
```javascript
define('Example.UserPreferences.Form.View', ['Backbone', 'SCFormView', 'Example.UserPreferences.Helper', 'Utils', 'example_userpreferences_form.tpl'], function (Backbone, SCFormViewModule, ExampleUserPreferencesHelper, Utils, example_userpreferences_form_tpl) {
'use strict';
var SCFormView = SCFormViewModule.SCFormView;
function ExampleUserPreferencesFormView(options) {
SCFormView.call(this, options.model);
this.formModel.on('sync', function () {
Backbone.history.navigate('preferences', { trigger: true });
});
this.template = example_userpreferences_form_tpl;
}
ExampleUserPreferencesFormView.prototype = Object.create(SCFormView.prototype);
ExampleUserPreferencesFormView.prototype.constructor = ExampleUserPreferencesFormView;
ExampleUserPreferencesFormView.prototype.getEvents = function () {
return { 'submit form': 'saveForm', 'blur :input': 'onFormFieldChange' }
}
ExampleUserPreferencesFormView.prototype.saveForm = function (e) {
e.preventDefault();
return SCFormView.prototype.saveForm.call(this, e);
}
ExampleUserPreferencesFormView.prototype.getFormFieldValue = function (input) {
var field = { name: input.attr('name'), value: input.val() };
if (!this.formModel.validate(field)) {
SCFormView.prototype.removeErrorMessage.call(this, field.name)
}
return field
}
ExampleUserPreferencesFormView.prototype.getFormValues = function (form) {
var formValues = form.serializeObject();
return { type: formValues.type, value: formValues.value }
}
ExampleUserPreferencesFormView.prototype.getContext = function () {
return { isNew: this.formModel.isNew(), model: this.formModel, typeOptions: ExampleUserPreferencesHelper.getTypeOptions() }
}
return ExampleUserPreferencesFormView
});
```
--------------------------------
### Create SCView with Context Data Requests
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
This snippet illustrates how to extend SCView to handle context data requests from parent components. It includes logic for conditional rendering and mapping context data to the template.
```javascript
define('CDRExample.View', [
'SCView',
'cdr_example.tpl'
], function (
SCViewModule,
cdr_example_tpl
) {
'use strict';
var SCView = SCViewModule.SCView;
function CDRExampleView(options) {
SCView.call(this, options);
this.template = cdr_example_tpl;
this.contextDataRequest = ['item'];
this.displayType = options.PLP.getDisplay().id;
}
CDRExampleView.prototype = Object.create(SCView.prototype);
CDRExampleView.prototype.constructor = CDRExampleView;
CDRExampleView.prototype.render = function () {
if (this.displayType == 'list') {
SCView.prototype.render.call(this);
}
}
CDRExampleView.prototype.getContext = function () {
return {
storedetaileddescription: this.contextData.item().storedetaileddescription
}
}
return CDRExampleView
});
```
--------------------------------
### Implement Handlebars Templates for UI Rendering
Source: https://context7.com/oracle-samples/netsuite-commerce/llms.txt
These templates demonstrate the use of Handlebars syntax for rendering lists and forms. They utilize custom helpers like 'translate' and 'ifEquals', and include 'data-view' attributes for child view injection.
```html
{{translate 'User Preferences'}}
{{translate 'Add New'}}
| {{translate 'Internal ID'}} | {{translate 'Type'}} | {{translate 'Value'}} | {{translate 'Actions'}} |
|---|