new Cart()

Description

The Cart component provides ways to work with the cart, for example, adding lines, getting the cart summary, and applying promotions. It also exposes before and after events for several methods. For example, the beforeAddLine and afterAddLine events let you add event listeners before lines are added to the cart, and after lines are added to the cart respectively.

Get an instance of this component by calling container.getComponent("Cart").

Members


componentName :String

Description

A unique name that identifies the component. Use the component name when getting a component, for example, application.getComponent(componentName).

Details
String

CART_VIEW :String

Description

Name of the cart main view. Use this name to reference views in methods such as addChildView() and addToViewContextDefinition().


CART_MINI_VIEW :String

Description

Name of the mini-cart main view. Use this name to reference views in methods such as addChildView() and addToViewContextDefinition().


application :ComponentContainer

Description

The name which identify this kind of component. This name is used both for registering a new component and
getting a component implementation with ComponentContainer


WIZARD_VIEW :String

Methods


cancelableOn( event_name, handler ) → {void}

Description

Attaches an event handler to an event.

Parameters
Name Type Description
event_name String

The name of the event to which the event handler will be attached.

handler function

The event handler method that will be invoked when event_name is triggered. This function can receive optionally one parameter representing the action parameter. Besides optionally can return a Deferred to details the execution of the trigger's callback. If the returned Deferred is rejected the trigger's callback wont be called

Returns

cancelableOff( event_name, handler ) → {void}

Description

Detaches an event handler from an event.

Parameters
Name Type Description
event_name String

The name of the event from which to detach the event handler. This argument is required.

handler function

The event handler that will be removed from the list of handlers attached to the event. This argument is required.

Returns

extend( componentDefinition ) → {BaseComponent}

Description

Extends the current component and creates a child component.

Parameters
Name Type Description
componentDefinition Object

An object with the appropriate properties and methods to create the component.

Returns
Details

closeMessage( messageId )

Description

Lets you close a message on the page. To close a message, you must have the ID of the message, as returned by showMessage() when the message was first shown.

		var layout = container.getComponent('Layout');
			var message_vat_no;
			
			if (layout) {
				
				// Check if a VAT number was entered. If not, display a message.
				if ($('#vat_no').val() == '') {
					message_vat_no = layout.showMessage({message: 'You must enter a VAT number to register as a business customer.', type: 'error'});
				}
			}
			
			// Clear the VAT number error message when the VAT number field gets focus.
			$('#vat_no').focus(function() {
				layout.closeMessage(message_vat_no);
			});
			
Parameters
Name Type Description
messageId string

The ID of the message to close. Get the ID of a message by assigning the return value of showMessage() to a variable.


cancelableDisable( event_name ) → {void}

Description

Disables all the event handlers attached to an event.

Parameters
Name Type Description
event_name String

The name of the event.

Returns

on( event_name, handler ) → {void}

Description

Attaches an event handler to an event name. Alias for CancelableEvents#cancelableOn.

Parameters
Name Type Description
event_name String

The name of the event to attach to

handler function
Returns
Details

cancelableEnable( event_name ) → {Void}

Description

Re-enables all the event handlers attached to an event.

Parameters
Name Type Description
event_name String

The name of the event.

Returns

off( event_name, handler ) → {void}

Description

Detaches an event handler from an event name. Alias for CancelableEvents#cancelableOff.

Parameters
Name Type Description
event_name String

The name of the event from which to detach the event handler.

handler function
Returns
Details

addLine( line ) → {Deferred}

Description

Adds a line (item) to the cart. This method takes an object as its argument, which has a single property called line. The value of line is a Line object. Line has properties to specify the item and item quantity to add to the cart. You must know the internal ID of an item to add it to the cart.

If the item is already in the cart, the quantity of the line is increased by the value of the quantity property.

			var cart = container.getComponent('Cart');
			cart.addLine({
				line: {
					quantity: 1, 
					item: {
						internalid: 8058
					}
				}
			}).then(function() {
				alert(Utils.translate('Item added.'))
			});
			

Note: The addLine() method does not trigger a visible confirmation when an item is added to the cart. To trigger the default add to cart behavior of the website, use triggerAddToCartConfirmation().

Parameters
Name Type Description
line AddLineData

The item to add to the cart. line is an AddLineData object.

Returns

Returns a Deferred object. If the promise is resolved, the line is added to the cart.


cancelableTrigger( event_name, ...args ) → {Deferred}

Description

Triggers an event with a set of arguments. If an event handler is rejected, the event handler callbacks will not be executed.

Parameters
Name Type Attributes Description
event_name String

The name of the event to trigger.

args params <repeatable>

One or more arguments that will be broadcast to all event handlers attached to the event.

Returns

Returns a Deferred object. Because event handlers are sometimes asynchronous, any callbacks in the event handlers will also be asynchronous.


cancelableTriggerUnsafe( event_name, ...args ) → {Deferred}

Description

Triggers an event with a set of unsanitized arguments. If an event handler is rejected, the event handler callbacks will not be executed.

Parameters
Name Type Attributes Description
event_name String

The name of the event to trigger.

args params <repeatable>

One or more arguments that will be broadcast to all event handlers attached to the event.

Returns

Returns a Deferred object. Because event handlers are sometimes asynchronous, any callbacks in the event handlers will also be asynchronous.


modifyViewJsonLd( view_id, callback ) → {void}

Description

Lets you modify JSON-LD data embedded in the <head> element of a SuiteCommerce product details page. JSON-LD data on SuiteCommerce websites adheres to the structured data schemas, as specified on https://schema.org/Product.

If your extension modifies a view or adds a child view on the product details page, you can use modifyViewJsonLd() to update the related JSON-LD. For example, if you add a child view that displays additional product information, you can update the JSON-LD to ensure the page and its metadata are consistent.

In general, the embedded JSON-LD data should be consistent with the content in the view. SuiteCommerce creates JSON-LD data when a view is rendered. For this reason, you need to pass in a view ID to modifyViewJsonLd() when modifying JSON-LD data.

Note: To use this method, JSON-LD must be selected as the markup type on the SuiteCommerce Configuration page in the NetSuite account. See Structured Data Markup in the NetSuite Help Center for more information.

In the following example, we create an instance of the Layout component and use modifyViewJsonLd() to add a property to the JSON-LD object. We pass in 'ProductDetails.Full.View' as the view ID and a function that returns a Promise. The _.extend function enables you to copy an object and add new properties to it.

			var layout = container.getComponent('Layout');
			
			layout.modifyViewJsonLd('ProductDetails.Full.View', function(json) {
				json = _.extend(json, {
					manufacturer: 'NetSuite Industrial'	
				});
				return jQuery.Deferred().resolve(json);
			});
			
			
Parameters
Name Type Description
view_id string

The identifier of the view that will update the JSON-LD data. For example, if you use the Layout component to modify the ProductDetails.Full.View view in the base theme template, pass in "ProductDetails.Full.View" as the view_id.

callback function

A function that modifies the JSON-LD data. It must return a Promise that resolves with an object.

Returns

Returns null if the operation is successful. Otherwise, it returns an Error. For example, an error is returned if JSON-LD is not selected as the structured markup type on the Configuration page.

Throws
Details

SuiteCommerce 2020.1


setChildViewIndex( view_id, placeholder_selector, view_name, index ) → {void}

Description

Changes the position of a child view inside a container.

Parameters
Name Type Description
view_id string

The identifier of the view of the current component that contains the child view whose position will be changed.

placeholder_selector string

The identifier of a location in the specified view (view_id) where the child view will be added.

view_name string

The identifier of a view in the placeholder.

index number

The index of the child view's position.

Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

addLines( lines ) → {Deferred}

Description

Adds multiple lines to the cart. This method takes a single object as its argument with one property called lines. The value of lines is an array of Line objects.

			var cart = container.getComponent("Cart");
			cart.addLines({
					lines: [
						{
							quantity: 1,
							item: {
								internalid: 4938
							}
						},
						{
							quantity: 1,
							item: {
								internalid: 4936
							}
						}
					]
			});
			
			
Parameters
Name Type Description
lines AddLines

The items to add to the cart. lines is an AddLines object that contains an array of AddLineData objects, each of which represents a line to add to the cart.

Returns

Returns a Deferred object. If the promise is resolved, the lines are added to the cart.


addPayment( data )

Description

Adds a payment method.

			var cart = container.getComponent("Cart");
			cart.addPayment({
				payment_method: {
					internalid: 3
				}
			});
			
			
Parameters
Name Type Description
data PaymentMethod

The payment method to add to the transaction. data is a PaymentMethod object, which contains a single property called payment_method. The value of payment_method is an object that contains payment method data such as the internal ID of the payment method in NetSuite, and credit card details if the payment method type is a credit card.


addPromotion( data ) → {Deferred}

Description

Applies a promotion to the cart. If the promotion code is valid and successfully applied to the order, the promotion appears in the cart automatically and the order total is updated.

			var cart = container.getComponent("Cart");
			
			if (cart) {
				cart.addPromotion({
					promocode: "5OFF"
				}).then(function(promotion) {
					alert("Promotion added.");
					console.log(promotion);
				}, function() {
					console.log("Could not add promotion.");
				});
			}
			
Parameters
Name Type Description
data Object

Contains the data about the promotion.

Name Type Description
promocode String

The promotion code (promocode) of the promotion. The value of promocode is the coupon code on the promotion record in NetSuite.

Returns

Returns a Deferred object. If the promise resolved, it returns a Promise object. If the promise is rejected (because the promotion could not be applied), it returns an error message object in JSON format.


clearEstimateShipping()

Description

Clears the shipping estimation from the order.


showMessage( data ) → {string}

Description

Shows a message in the notifications area of a SuiteCommerce page. The message is displayed by default in the Notifications placeholder (a DIV element in the base theme template with the custom data attribute data-view="Notifications"). You can also choose to display the message in any other placeholder that uses either of the following custom data attributes: data-view or data-cms-area.

Messages can be closed by the user, by setting a timeout in the method, or with the closeMessage() method. If you want to use closeMessage(), first assign the return value of showMessage() to a variable, and then pass the variable to closeMessage().

In the following example, the message is shown and then closed after 5 seconds by setting a timeout.

		var layout = container.getComponent('Layout');
			
			if (layout) {
				var message_shown = false;
				layout.on('afterShowContent', function() {
					
					if (message_shown != false) {
						layout.showMessage({
							message: '',
							type: 'info',
							selector: 'Notifications',
							timeout: 5000
						});
						message_shown = true;
					}
				});
			}
			

In the following example, a message is shown if an invalid VAT number is entered. When the user enters a valid number, the message is closed.

		var layout = container.getComponent('Layout');
			var message_vat_no;
			
			$('#vat_number').blur(function() {
				var vat_number = $(this).val();
			
				if (message_vat_no !== undefined) {
					layout.closeMessage(message_vat_no);
				}
			
				// checkVatNumber() returns false if the number entered is invalid.
				if (!checkVatNumber(vat_number)) {
					message_vat_no = layout.showMessage({
						message: 'You must enter a VAT number to register as a business customer.', 
						type: 'error'
					});
				}
			});
			
Parameters
Name Type Description
data Object

Data required to display the message. data is an object, which can have the following properties:

  • message - Required. The text of the message.
  • type - Required. The type of message. It also determines the appearance of the message on the page. Type can be one of the following: info, warning, error, or success.
  • selector - A placeholder on the page where you want the message to appear.
  • timeout - Specifies the duration in milliseconds of the message on the page. If you do not specify a timeout, you can use closeMessage() to remove the message.
Returns

Returns the message ID as a string.

Details

SuiteCommerce 2019.2


estimateShipping( data ) → {Deferred}

Description

Gets the estimated shipping costs for a particular country and postal code combination. This method accepts an object as its argument. After you call this method, the order summary of the cart is updated with the postal code and the currency amount of the shipping estimate.

			var cart = container.getComponent("Cart");
			cart.estimateShipping({
				address: {
					zip: "10065",
					country: "US"
				}
			});
			
Parameters
Name Type Description
data Object

The address data to use to estimate shipping.

Name Type Description
address Object

The address details.

Name Type Description
zip String

The postal code of the address

country String

The 2-letter country code of the address.

Returns

Returns a Deferred object. The promise returns an object with two properties: address and result. address contains properties related to the shipping address, including the country and postal code. result contains properties related to shipping and handling costs, discount totals, and transaction totals.


addChildViews( view_id, child_views ) → {void}

Description

Adds one or more child views to an existing view. The existing view must already be in the DOM and must have the 'data-view' HTML attribute.

The addChildViews method is flexible, but more complex than addChildView. Use the simpler addChildView() where possible.

checkout.addChildViews(
			    checkout.WIZARD_VIEW
			    , {
			        'Wizard.StepNavigation':
			        {
			            'CheckoutView':
			            {
			                childViewIndex: 1
			            ,   childViewConstructor: function ()
			                {
			                    return new CheckoutExtensionView({checkout:checkout});
			                }
			            }
			        }
			    }
			);
			
Parameters
Name Type Description
view_id string

The identifier of the view of the current component to which the child views will be added.

child_views object
Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

getBillAddress() → {Deferred}

Description

Gets the billing address of the order.

			var cart = container.getComponent("Cart");
			cart.getBillAddress().then(function(billaddress) {
				if (billaddress.isresidential == "T") {
					// Do work related to Sunday shipments for residential addresses.
					// ...
				}
			});
			
Returns

Returns a Deferred object. If the promise is resolved, it returns an Address. If the promise is rejected, it returns an error.


addChildView( data_view, view_constructor ) → {Void}

Description

Adds a child view to a view that already exists in the DOM. Child views can be added to elements that have the data-view or data-cms-area data attribute. If there are multiple elements in a template that have a data-view attribute value of view_id, the child view is added to all elements with that ID. Elements with the data-view attribute act as placeholders in the application. If there is content in the view (which is typically the case), the child view replaces the current content.

If you want to add multiple views at the same time, or if you want to add a child view while preserving the current content in the existing view, use addChildViews.

			layout.addChildView('Header.View', function () {
			  return new HolidayBannerView({});
			});
			

In the above example, the view HolidayBannerView will be added as a child view of an element in any template that has a data-view attribute of Header.View.

			layout.addChildView('cms:header_banner_top', function () {
			  return new HolidayBannerView({});
			});
			

In the above example, a child view is added to a predefined SMT area called 'header_banner_top'. In the template, the header_banner_top SMT area might be in a div tag in the following way: <div data-cms-area="header_banner_top"></div>. Because header_banner_top is a predefined SMT area, the cms: prefix is used before the view_id argument.

Parameters
Name Type Description
data_view String

The view to which the child view will be added. data_view is the value of the 'data-view' or 'data-cms-area' data attributes of an element on the page. For example, the header logo view uses the following data-view data attribute: <div data-view="Header.Logo">.

view_constructor SimpleChildViewConstructor

An instance of a view. Use a constructor function to get an instance of a view.

Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

removeChildView( view_id, placeholder_selector [, view_name ] ) → {void}

Description

Removes a child view from a view.

Parameters
Name Type Attributes Description
view_id string

The identifier of the view of the current component from which the child view will be removed.

placeholder_selector string

The identifier of the location in the specified view (view_id) from which the child view will be removed.

view_name string <optional>

The identifier of the view to be removed.

Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

getLatestAddition() → {Deferred}

Description

Gets the last line added to the cart.

The following example shows how you might use getLatestAddition() to allow a website visitor to remove the last item they added to the cart. When getLatestAddition() is called, it returns a Line object from which we can get the item ID. You can then pass the item ID to the removeLine() method and show a message if the item was removed successfully.

			var cart = container.getComponent('Cart');
				
			cart.getLatestAddition().then(function(line) {
			
				if (line) {
					var lastItemAddedId = line.internalid;	
					var lastItemAddedName = line.item.displayname;
			
					cart.removeLine({
						line_id: lastItemAddedId
					}).then(function() {
						cart.showMessage({
							message: lastItemAddedName + ' was removed from the cart.',
							type: 'info'
						})
					});
				}
			
			});
			
Returns

Returns a Deferred object. If the promise is resolved, it returns the line as a Line object; if the cart is empty, it returns null. Otherwise, the promise returns the rejected state.

Details

SuiteCommerce 2021.1


addToViewContextDefinition( view_id, property_name, type, callback ) → {void}

Description

Adds a property to the UI context of a view to extend interaction with its template.

Parameters
Name Type Description
view_id string

The identifier of the view of the current component to which the context property will be added.

property_name string

The name of the property.

type string

The type of the property. The value returned by the callback function must be of the same type.

callback function

A function that sets the value of the property (property_name).

Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

getLines() → {Deferred.<Array.<Line>>}

Description

Gets the lines in the cart.

var cart = container.getComponent("Cart");
			cart.getLines().then(function(lines) {
			
					if (lines.length > 100) {
						throw new Error("You are ordering a lot of stuff. For high-volume orders, contact our sales team on 555-123-1234.");
					}
			});
			
Returns

Returns a Deferred object. If the promise is resolved, it returns the lines in the cart (an array of Line objects). Otherwise, the promise returns the rejected state.


removeToViewContextDefinition( view_id, property_name ) → {void}

Description

Removes a property from the UI context of a view.

Parameters
Name Type Description
view_id string

The identifier of the view of the current component from which the context property will be removed.

property_name string

The name of the property.

Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

addToViewEventsDefinition( view_id, event_selector, callback ) → {void}

Description

Adds an event handler to an event in a view.

Parameters
Name Type Description
view_id string

The identifier of the view of the current component to which the event handler will be added.

event_selector string
callback function

The event handler function to call when the specified event occurs.

Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

removeToViewEventsDefinition( view_id, event_selector ) → {void}

Description

Removes an event handler from an event in a view.

Parameters
Name Type Description
view_id string

The identifier of the view of the current component to which the event handler will be added.

event_selector string
Returns

Returns null if the operation is successful. Otherwise, it throws an exception.

Throws

getPaymentMethods() → {Deferred}

Description

Gets the currently selected payment method on the order.

			var cart = container.getComponent('Cart');
			cart.getPaymentMethods().then(function(paymentmethods) {
				var paymentmethodtype = paymentmethods[0].type;
				var paymentmethodexpiry = paymentmethods[0].creditcard.expyear;
			
				if (paymentmethodexpiry == todayyear) {
					// Do work related to payment method expiry date
					// ...
				}
			});
			
			// Example of the object returned by this method:
			{
				"extras": {...},
				"type": "creditcard",
				"creditcard": {
				"ccexpiredate": "11/1/2022",
				"ccname": "John Smith",
				"ccnumber": "************2780",
				"expmonth": "11",
				"expyear": "2022",
				"extras": {...},  
				"paymentmethod": {...}
			}
			
Returns

Returns a Deferred object. If the promise is resolved, it returns an array of PaymentMethod objects. If the promise is rejected, it returns an error.


getPromotions() → {Deferred}

Description

Gets the promotions in the cart.

			var cart = container.getComponent("Cart");
			cart.getPromotions().then(function(promotions) {
				if (promotions.length >= 3) {
					console.log("Too many promotions on this order!");
				}	
			});
			
Returns

Returns a Deferred object. If the promise is resolved, it returns an array of Promotion objects. If the promise is rejected, it returns an error.
The Promotion object contains a property called internalid, which you can use with the removePromotion() method to remove a promotion from the cart.


getPurchaseOrderNumber() → {Deferred}

Description

Gets the purchase order number from the Enter Purchase Order Number field on the order. You can set the purchase order number with setPurchaseOrderNumber().

Note: To get the purchase order number, the 'Display Purchase Order Field on Payment Info Page' option must be checked on the website settings page in the NetSuite account. See the Shopping Preferences topic in the Help Center for more information.

			var cart = container.getComponent('Cart');
			var purchaseOrderNumber = '';			
			
			cart.getPurchaseOrderNumber().then(function(ponumber) {
				purchaseOrderNumber = ponumber;
			
				if (purchaseOrderNumber != '') {
					console.log('Purchase order number: ' + ponumber);
				}
			});
			
Returns

Returns a Deferred object. If the promise is resolved, it returns the purchase order number as a string. If the promise is rejected, it returns an error.

Details

SuiteCommerce 2021.1


getShipAddress() → {Deferred}

Description

Gets the shipping address of the order.

			var cart = container.getComponent("Cart");
			cart.getShipAddress().then(function(shipaddress) {
				
				if (shipaddress.country != "US") {
					alert("Shipping of this item outside the US may incur delays due to export regulations.");
				}
			})
			
			// Example of the Address object returned by this method:
			{
				addr1: "1 Main Street",
				addr2: "",
				addr3: "",
				city: "New York",
				company: null,
				country: "US",
				defaultbilling: "F",
				defaultshipping: "T",
				extras: {...},
				fullname: "John Smith",
				internalid: "42",
				isresidential: "F",
				isvalid: "T",
				phone: "555-123-1234",
				state: "NY",
				zip: "10065"
			}
			
Returns

Returns a Deferred object. If the promise is resolved, it returns an Address object. If the promise is rejected, it returns an error.


getShipMethod() → {Deferred}

Description

Gets the selected shipping method on the order. If a shipping method is not yet set on the order, it returns an object with a single property called extras with an empty object as its value.

Note: This method is only available on the Checkout pages of a SuiteCommerce website.

			var cart = container.getComponent("Cart");
			cart.getShipMethod().then(function(shipmethod) {
				if (shipmethod.internalid == "105") {
					alert("Delivery tracking for this ship method is available on www.example.com/track");
				}
			});
			

Example of the ShipMethod object returned by this method:

			{
				extras: {},
				internalid: "105",
				name: "2-day shipping",
				rate: 10,
				rate_formatted: "$10.00",
				shipcarrier: "nonups"
			}
			
Returns

Returns a Deferred object. If the promise is resolved, it returns a ShipMethod object. If the promise is rejected, it returns an error.


getShipMethods() → {Deferred}

Description

Gets all shipping methods available on the order.

Note: This method is only available on the Checkout pages of a SuiteCommerce website.

			var cart = container.getComponent("Cart");
			cart.getShipMethods().then(function(shipmethods) {
				alert(shipmethods.length + " shipping methods are available on this order.");
			});
			
Returns

Returns a Deferred object. If the promise is resolved, it returns an array of ShipMethod objects. If the promise is rejected, it returns an error.


getSummary() → {Deferred}

Description

Gets a summary of the cart including information such as the total currency amount, number of items in the transaction, tax amounts, and discounts applied.

		var cart = container.getComponent("Cart");
			cart.getSummary().then(function(summary) {
				if (summary.total > 10000) {
					throw new Error("Contact our sales team on 555-123-1234 for order amounts above 10,000 USD.");
				}
			});
			

Example of the Summary object returned by this method. Note that the list of properties in the extras property may differ depending on the configuration of your account.

			{
				discounttotal: 0,
				estimatedshipping: 0,
				extras: {
					discountedsubtotal: 260.88,
					discountedsubtotal_formatted: "$260.88",
					discountrate: 0,
					discountrate_formatted: "",
					discounttotal_formatted: "($0.00)",
					estimatedshipping_formatted: "$0.00",
					giftcertapplied_formatted: "($0.00)",
					handlingcost_formatted: "$0.00",
					itemcount: 3,
					shippingcost_formatted: "$0.00",
					subtotal_formatted: "$260.88",
					tax2total_formatted: "$0.00",
					taxondiscount: 0,
					taxondiscount_formatted: "$0.00",
					taxonhandling: 0,
					taxonhandling_formatted: "$0.00",
					taxonshipping: 0,
					taxonshipping_formatted: "$0.00",
					taxtotal_formatted: "$0.00",
					total_formatted: "$260.88",
					totalcombinedtaxes: 0,
					totalcombinedtaxes_formatted: "$0.00"
				}
				giftcertapplied: 0,
				handlingcost: 0,
				shippingcost: 0,
				subtotal: 260.88,
				tax2total: 0,
				taxtotal: 0,
				total: 260.88
			}
			
Returns

Returns a Deferred object. If the promise is resolved, it returns a Summary object. If the promise is rejected, it returns an error.


removeLine( line ) → {Deferred}

Description

Removes a line from the cart. To decrease (or increase) the line quantity, use updateLine() instead. To remove lines from the cart, you need to know the internal line ID of the item in the cart. You can use getLines() to get extensive information about lines in the cart, including the line ID.

In the following example, removeLine() is used to remove all lines in the cart. To get the line IDs of each item, getLine() is called first, which returns a promise. We can then use the then() method of the promise and loop through the lines, removing each one with a call to removeLine(). To determine if all lines were removed successfully, we can chain the first then() with another then() and display an appropriate message.

Note: Removing lines in this manner requires a call to removeLine() for each line in the cart. You can remove lines in other ways that may be more efficient, however, as described on the developers.suitecommerce.com website.

				var cart = container.getComponent("Cart");
			
			var lines = cart.getLines();
			var removed = 0;
			
			lines.then(function(lines, removed) {
				for (i=0; i < lines.length; i++) {
					cart.removeLine({
						line_id: lines[i].internalid
					}).then(function() {
						removed++;
					});
				}
			}).then(function(removed) {
				if (removed == lines.length) {
					console.log("All lines removed successfully");
				}
				else {
					alert("Some lines could not be removed.");
				}
			});
			
Parameters
Name Type Description
line Object

The line to remove from the cart. line is an object with a single property line_id. The value of line_id is the internal ID of the line, which is generated dynamically by the cart when an item is added. Note that if you remove a line from the cart and then add it again, a new line ID is generated for the item.

Returns

Returns a Deferred object. If the promise is resolved, it indicates the operation was successful.


removePromotion( data ) → {Deferred}

Description

Removes a promotion from the cart. If the promotion is removed sucessfully, the cart total is updated and the promotion no longer appears in the cart.

			var cart = container.getComponent("Cart");
			
			if (cart) {
				cart.removePromotion({promocode_internalid: "22"}).fail(function() {
					console.log("Could not remove promotion.");
				});
			}
			
Parameters
Name Type Description
data Object

The promotion to remove from the cart. data is an object with a single property promocode_internalid. The value of promocode_internalid is the internal ID of the promotion. You can use the getPromotions() method to get the internal IDs of all promotions currently applied.

Returns

Returns a Deferred object. If the promise is resolved, it indicates the promotion was removed successfully. Otherwise, if the promise fails, it returns an error message.


setPurchaseOrderNumber( purchase_order_number [, save_order ] ) → {Deferred}

Description

Sets the purchase order number on the order, and displays it in the Enter Purchase Order Number field. You can pass in a parameter to optionally save the purchase order number in the user session. Saving the purchase order number in the user session does not save the order itself.

This method only works when the web store visitor is on the checkout page. Calling this method on any other page in the application will not set the purchase order number.

Note: To set the purchase order number, the 'Display Purchase Order Field on Payment Info Page' option must be checked on the website settings page in the NetSuite account. See the Shopping Preferences topic in the Help Center for more information.

You can get the purchase order number with getPurchaseOrderNumber().

			var cart = container.getComponent('Cart');
			
			cart.setPurchaseOrderNumber('PO123456').then(function() {
				console.log('Purchase order number added.');
			}, function() {
				cart.showMessage({
					message: 'Purchase order number could not be added to the order.',
					type: 'error'
				});
			});
			
Parameters
Name Type Attributes Description
purchase_order_number String

The purchase order number to set on the order.

save_order Boolean <optional>

Indicates whether to save the purchase order number in the user session. If set to true, reloading the page or navigating away from the checkout page (for example, to add more items to the cart) maintains the purchase order number on the order.

Returns

Returns a Deferred object. If the promise is resolved, it indicates the operation was successful. If the promise is rejected, it returns an error.

Details

SuiteCommerce 2021.1


setShipMethod( ShipMethodData ) → {Deferred}

Description

Sets a shipping method on the order for all items in the cart. Use getShipMethods() to get available shipping methods. If you pass in an invalid ship method ID, an error is returned.

This method will not work if the Multiple Ship To feature is enabled in the NetSuite account. More information about Multiple Ship To is available in the Help Center.

Note: This method is only available on the Checkout pages of a SuiteCommerce website.

			var cart = container.getComponent("Cart");
			var shipMethodId = '2910';
			var shipMethodData = {ship_method: {internalid: shipMethodId}};
			
			cart.setShipMethod(shipMethodData).then(function() {
				cart.showMessage({
					message: 'Shipping method of the order was updated.',
					type: 'info'
				})
			});
			
Parameters
Name Type Description
ShipMethodData Object
Name Type Description
ship_method Object

The shipping method to set on the order.

Name Type Description
internalid String

The internal ID of the shipping method in the NetSuite account, for example, '2910'.

Returns

Returns a Deferred object. If the promise is resolved, it returns a ShipMethod object. If the promise is rejected, it returns an error. For example, if Multiple Ship To is enabled in the NetSuite account, an error is returned (INVALID_METHOD).

Details

SuiteCommerce 2021.1


setTransactionBodyField( data ) → {Deferred}

Description

Sets the value of a custom transaction body field on the order. To use this method, pass in an object that contains the field ID, its type, and the value you want to set.

The following table shows which types of NetSuite fields are supported for each data type:

Data TypeNetSuite Field Type
stringtext
textarea
richtext
longtext
select
URL
inlinehtml
phone
email
multiselect
numbercurrency
float
integer
percent
booleancheckbox
datedate
 

See the Custom Transaction Body Fields topic in the Help Center for more information about how to create custom transaction body fields in NetSuite.

Any of the following circumstances will cause this method to fail and return an error:

  • If there are no transaction body fields on the page.
  • If the specified transaction body field is not on the page.
  • If the value of value does not match the specified type in the TransactionBodyFieldData object.
  • If the value of type in the TransactionBodyFieldData object does not match the field type in NetSuite.

In the following example, setTransactionBodyField() is used to set the value of a custom field called 'custbody_customerref' to 'C123456', and then log success or fail messages to the console.

			var cart = container.getComponent('Cart');
			var data = {
				fieldId: "custbody_customerref",
				type: "string",
				value: "C123456"
			}
			
			cart.setTransactionBodyField(data).then(function() {
				console.log(data.fieldId + ' was set to ' + data.value);
			}).fail(function(error) {
				console.log('setTransactionBodyField failed.');
			});
			
Parameters
Name Type Description
data TransactionBodyFieldData

Specifies the ID of the custom transaction body field, its type, and its value.

Returns

Returns a Deferred object. If the promise is resolved, it indicates the operation was successful. If the promise is rejected, it returns an error.

Details

SuiteCommerce 2021.1


submit() → {Deferred}

Description

Submits the order. The user must be logged in on the web store to submit an order. If information required to submit the order is missing or incomplete, this method returns an error message. This method only works on a secure domain.

			var cart = container.getComponent("Cart");
			cart.submit();
			
			
Returns

Returns a Deferred object. If the promise is resolved, it returns a ConfirmationSubmit. If the promise is rejected, it returns an error.


triggerAddToCartConfirmation() → {Deferred}

Description

Triggers the add to cart behavior of the website.

You can select the add to cart behavior on the configuration page of the website in your NetSuite account. You can choose one of the following options as the add to cart behavior:

  1. goToCart - Redirects to the cart page.
  2. showMiniCart - Shows the mini cart popup at the top of the page.
  3. showCartConfirmationModal - Shows the cart modal, which the website visitor must dismiss to continue.

See the Shopping Catalog Tab topic in the Help Center for more information about configuring the add to cart behavior.

You can use this method with the addLine() method. If you use addLine() on its own, it does not trigger a visible confirmation. So if you want to trigger a confirmation message when an item is added to the cart, use triggerAddToCartConfirmation() in the promise returned by addLine(). If the cart is empty, an error message is returned.

var cart = container.getComponent('Cart');
			
			cart.addLine({
				line: {
					quantity: 1,
					item: {
						internalid: 1234
					}
				}
			}).then(function() {
				cart.triggerAddToCartConfirmation().then(function() {
					console.log('Add to cart confirmation was triggered.');
				})
			});
			

 

Note: This method does not allow you to choose which of the three behaviors to trigger; it always uses the selected behavior in the website configuration.

Returns

Returns a Deferred object. If the promise is resolved, the confirmation is shown. If the promise is rejected, it returns an error.

Details

SuiteCommerce 2021.2


updateLine( line ) → {Deferred}

Description

Updates the quantity of a line in the cart. Setting the quantity to zero will remove the line from the cart.

			var cart = container.getComponent("Cart");
			cart.updateLine({
				line: {
					internalid: "i123",
					quantity: 2
				}
			}).then(function() {
				console.log("Line updated successfully");
			});
			
Parameters
Name Type Description
line Line

The line in the cart to update. line is an object with a single property called line. The value of the line property is a Line object. You only need to specify two properties in the Line object: internalid and quantity. All other properties of the Line object are ignored when updating the line.

Returns

Returns a Deferred object. If the promise is resolved, it returns the line as a Line object. Otherwise, the promise returns the rejected state.

Events


afterShowContent

Description

Event triggered after content has been rendered in the main view. This event is available in components that extend VisualComponent (such as PDP, PLP, or Layout) and is triggered by the showContent() method.

See the Work with Events help topic in the NetSuite Help Center for more information.


beforeShowContent

Description

Event triggered before content in the main view is rendered. This event is available in components that extend VisualComponent (such as PDP, PLP, or Layout) and is triggered by the showContent() method. For example, if the URL changes in the application, the showContent() method is called, which triggers the event.


beforeAddLine

Description

Cancelable event triggered before a line is added to the cart. See CancelableEvents.

Properties
Type Description
boolean

beforeAddPayment

Description

Cancelable event triggered before a payment method is added to the order. See CancelableEvents.

Properties
Type Description
boolean

beforeAddPromotion

Description

Cancelable event triggered before a promotion is applied to the cart. See CancelableEvents.

Properties
Type Description
boolean

beforeClearEstimateShipping

Description

Cancelable event triggered before clearing shipping estimates for the cart. See CancelableEvents.

Properties
Type Description
boolean

beforeEstimateShipping

Description

Cancelable event triggered before getting shipping esimates for the cart. See CancelableEvents.

Properties
Type Description
boolean

beforeRemoveLine

Description

Cancelable event triggered before a line in the cart is removed. See CancelableEvents.

Properties
Type Description
boolean

beforeRemovePromotion

Description

Cancelable event triggered before a promotion is removed from the cart. See CancelableEvents.

Properties
Type Description
boolean

beforeSetPurchaseOrderNumber

Description

Cancelable event triggered before the purchase order number is set on the order. The event data is an object with a single property purchase_order_number.

Properties
Name Type Description
purchase_order_number String

The purchase order number passed to the setPurchaseOrderNumber() method.


beforeSetShipMethod

Description

A cancelable event triggered before a ship method is set on the order. Listen for this event with the on() method of the Cart component.

			var cart = container.getComponent('Cart');
			cart.on('beforeSetShipMethod', function(shipping_method) {
				console.log('setShipMethod fired.');
				console.log(shipping_method);
			});
			
Properties
Name Type Description
internalid String

The internal ID of the shipping method.


beforeSetTransactionBodyField

Description

A cancelable event triggered before a custom transaction body field is updated with setTransactionBodyField().

Properties
Name Type Description
TransactionBodyFieldData Object

The data to set on the custom transaction body field.


beforeSubmit

Description

Cancelable event triggered before the order is submitted. See CancelableEvents.

Properties
Type Description
boolean

beforeUpdateLine

Description

Cancelable event triggered before a line in the cart is updated. See CancelableEvents.


afterAddLine

Description

Event triggered after a line is added to the cart.

Properties
Type Description
boolean

afterAddPayment

Description

Event triggered after a payment method is added to the order.

Properties
Type Description
boolean

afterAddPromotion

Description

Event triggered after a promotion is applied to the cart.

Properties
Type Description
boolean

afterClearEstimateShipping

Description

Event triggered after shipping estimates are cleared.

Properties
Type Description
boolean

afterEstimateShipping

Description

Event triggered after shipping estimates retrieved.

Properties
Type Description
boolean

afterRemoveLine

Description

Event triggered after a line in the cart is removed.

Properties
Type Description
boolean

afterRemovePromotion

Description

Event triggered after a promotion is removed fromt the cart.

Properties
Type Description
boolean

afterSetPurchaseOrderNumber

Description

An event triggered after the purchase order number is set on the order with setPurchaseOrderNumber(). The event data is an object with a single property purchase_order_number.

Properties
Name Type Description
purchase_order_number String

The purchase order number passed to the setPurchaseOrderNumber() method.


afterSetShipMethod

Description

An event triggered after the ship method is set on the order with setShipMethod(). The event data is a ShipMethod.


afterSetTransactionBodyField

Description

An event triggered after a custom transaction body field is updated with setTransactionBodyField().

Properties
Name Type Description
TransactionBodyFieldData Object

The data that was set on the custom transaction body field.


afterSubmit

Description

Event triggered after the order is submitted.

Properties
Type Description
boolean

afterUpdateLine

Description

Event triggered after a line in the cart is updated.

Properties
Type Description
boolean