Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Saturday, August 27, 2011

Script Parameters: Where have you been all my life??

We've MOVED!!!! www.codeboxllc.com/ksc

Ok. perhaps script parameters been around for a while. I just failed to see the usefulness of it. You can read all about script parameters by going to NetSuite Help > SuiteFlex > SuiteScript > Creating Script Parameters (Custom Fields)

While back, I had one of NetSuite Custom Script guy review my codes. I asked him, "Please, imagine you are paying me to do your work and you are doing a code review of my work. Just rip it part and be very critical".
And he did just that. One of the suggestion he gave me was to utilize Script Parameters to turn my scripts into "Configurable" script.

What does configuration give you? Re-usability. As you see your script library grow, re-usability plays very important role in keeping your NetSuite account clean and organized.

Think of following situations where you can use power of configuration
1. Script that applies to multiple entity record types that sets same fields depending on the situation:
- You could hard code multiple entity  record types in to the script but that's not scalable. If you end up wanting to add new record, you need update the script and deploy.

- An alternative would be to create one script that takes record types as a parameter and DEPLOY it multiple times. It can easily be extended out to other entity record types by creating another deployment of the script with value of parameter as records internal id.

2. Script that takes different saved searches but ultimately does same thing for each records:
- You could hard code different types of saved searches but again, how scalable is that?

- An alternative would be to create one script that takes internal id of a saved search and DEPLOY it multiple times.

I think you are starting to see the trend here. Whats really cool about script parameter is that it can be text field, drop down list or a check box. Why is this cool? It's easy to set the parameters. Typing in internal ID might not be too user friendly but what if you want to set list of items, departments, or custom record as your parameter? Instead of looking up the internal ID of those records, you simply set it. EASY RIGHT!!!!

Keep in mind, if you want to set custom parameter specific for your script, you leave the Preference as blank.
You have two other options for this preference; Company and User. You can see full details by going to NetSuite Help > SuiteFlex > SuiteScript > Setting Script Parameter Preferences


You create your parameter(s) during your script creation stage. You set values for those parameters when you deploy your script. 

ID of your custom parameter starts with custscript prefix. Once you know what your ID is going to be, you can gain access to it with following code:
nlapiGetContext().getSetting('SCRIPT','YOUR CUSTOM FIELD ID');
On my screen shot above, I named my parameter _testparam. Full sample code will look like this:

 nlapiGetContext().getSetting('SCRIPT','custscript_testparam');
I can't wait to go back and rewrite all my scripts. Happy coding everyone!




Monday, August 8, 2011

Scriptable Cart - Full Sample By Jason K

We've MOVED!!!! www.codeboxllc.com/ksc

Hey Guys. I've been meaning to post this up but lost track of time due to extermination work I've been doing.
Couple months ago, I've worked with Jason K from NetSuite to trouble shoot remove/add issues I was having with my particular scriptable cart process. What this code is SUPPOSED to do:
When an item is added with certain country, it pro grammatically adds country specific surcharge item to the cart. In increments existing surcharge item in the cart if it already exists, it adds new country item if it doesn't exists. Removing parent item will also either increments or decrements the surcharge item.
I have not tried out his code personally but he assures me that it worked for him when he was fully testing out the process in his environment.

I'm hoping this will help in your effort to implement Webstore Scriptable Cart/Checkout form:


/*
Summary:  A custom item option is attached to a certificate which allows the shopper to choose a country.
When the shopper does this, a surcharge will be added to the cart based on the country chosen.  The shopper
can also add another certificate to the cart with a different country and there will be a separate line item
for each surcharge for each country.


This script also syncs up quantities for each cert-country combination.  For example, if the shopper increments,
decrements, or adds another Canada certificate to the cart, the quantity of the canadian surcharge will follow
that quantity.  This will NOT affect the quantity of other surcharges that are not the same country.


Finally, when a certificate is removed from the cart, the associated surcharge is also removed.


There are two customizations that were done to the sales order to support this script:


1) a new custom body field "custbody_processing", a text field, was added to ensure that no infinite looping
is seen.


2) a new custom body field "custbody_deletedcountry", a text field, is added and used by the validateDelete
event. The problem with recalc during a deletion is that we don't know what was deleted.  But, in our
custom validateDelete, if a cert was deleted, we save the cert's country in this custom field.  Then, during
recalc, we can just look up what surcharge needs to be removed and remove it.


There are also a couple of utility functions included below, including safeSelectNewLineItem and safeSelectLineItem.
In some cases, I've noticed that selectNewLineItem and selectLineItem throws an error if the script left the current
item row in an uncommitted state.  Using these functions will ensure that a commit will be done if need be before
a new row is selected.  The other functions should be self-explanatory.


*/
var certId = "74"; // ID of the general certificate, will including an item option custcol_certcountry
var certCountry = "custcol_certcountry"; // name of the custom column


// Map to define what surcharge item ID belongs to which country.
// In this case, I've only set up two countries along with two non inventory items.
var surchargeMap = {"US":"76", "CA":"75"};


// In order to make things easier for us, we will track the type of cert
// that is deleted via a validateDelete.  Will get the country
function validateDelete(type)
{
if (type == 'item')
{
var itemId = nlapiGetCurrentLineItemValue('item','item');
if (itemId == certId)
{
// if we get here, we know a certificate is being deleted.  Store the country in our
// custom body field for use in recalc.
var country = nlapiGetCurrentLineItemValue('item', certCountry);
log('Item ID '+itemId+' being deleted for country '+country+' - storing this in custom field');
nlapiSetFieldValue('custbody_deletedcountry', country);
}
}


return true; // Always return either true or false during validation
}


function onRecalc(type, action)
{
if (type != 'item') { return; }


try
{
var processing = nlapiGetFieldValue('custbody_processing');
if (processing != null && processing == 'T')
{
// We are in a secondary recalc, so exit
return;
}


// If we've passed the previous check, we are in the first
// level of recalc, so set processing flag
nlapiSetFieldValue('custbody_processing', 'T');


if (action=='commit')
{
doCommit();
}


if (action=='remove')
{
doRemove();
}
}
catch (err)
{
log("General Error: "+err.message);
}
finally
{
// Now, even with an error, we want to reset the processing flag
// so use a finally-clause to ensure this happens no matter what
nlapiSetFieldValue('custbody_processing', 'F');
}
}




// Called when a commit is done for recalc
function doCommit()
{
var thisItem = nlapiGetCurrentLineItemValue('item','item');


// Ignore any add-to-carts that are not certifications
if (thisItem != certId) { return; }


var thisQty = nlapiGetCurrentLineItemValue('item','quantity');
log("Current qty of cert = "+thisQty);


var thisCountry = nlapiGetCurrentLineItemValue('item', certCountry);
log("Current country of cert: "+thisCountry);


var surchargeId = surchargeMap[thisCountry];


if (isEmpty(surchargeId))
{
log("No surcharge ID found for country "+thisCountry+" - skipping processing");
return;
}


var surchargeLine = findItem(surchargeId);


if (surchargeLine == -1)
{
// We need to add a surcharge here
log("surcharge not found - adding surcharge");
addItem(surchargeId, thisQty);
}
else
{
surchargeQty = nlapiGetLineItemValue('item', 'quantity', surchargeLine);
log("Surcharge found - current Surcharge qty "+surchargeQty);


if (surchargeQty != thisQty)
{
log("updating quantity of surcharge");
safeSelectLineItem(surchargeLine);
nlapiSetCurrentLineItemValue('item', 'quantity', thisQty);
nlapiCommitLineItem('item');
}
}
}


// Called when a remove is done for recalc.  We have tracked the country that was
// deleted in the custom field, so this should be straightforward.  If there's no
// value in the custom field, don't do anything.
function doRemove()
{
// First, we get the deleted country from custbody_deleteditem
var deletedCountry= nlapiGetFieldValue('custbody_deletedcountry');


// If it's empty, this means that the item that was deleted was not a cert, so ignore.
if (isEmpty(deletedCountry))
{
return;
}


// Start a try-block here so after the remove we are sure that custbody_deletedcountry
// is cleared out even during an error
try
{
log('Country '+deletedCountry+' has been deleted, finding related surcharge');


var surchargeId = surchargeMap[deletedCountry];
var surchargeLine = findItem(surchargeId);


// only delete if appropriate surcharge is found
if (surchargeLine > 0)
{
log('Surcharge item for country '+deletedCountry+' found on line '+surchargeLine+' - removing');
safeSelectLineItem(surchargeLine);
nlapiRemoveLineItem('item', surchargeLine);
}
}
finally
{
nlapiSetFieldValue('custbody_deletedcountry', '');
}
}


// This function adds the given item to the order
function addItem(itemID, qty)
{
safeSelectNewLineItem();
nlapiSetCurrentLineItemValue('item', 'item', itemID);
nlapiSetCurrentLineItemValue('item', 'quantity', qty);
nlapiCommitLineItem('item');
}




// Sometimes, a selectNewLineItem results in an error if there's uncommitted
// values in the item list.  This makes sure this does not happen.
function safeSelectNewLineItem()
{
if (notEmpty(nlapiGetCurrentLineItemValue('item','item')))
{
nlapiCommitLineItem('item');
}


nlapiSelectNewLineItem('item');
}


// Sometimes, a selectLineItem results in an error if there's uncommitted
// values in the item list.  This makes sure this does not happen.
function safeSelectLineItem(itemLine)
{
if (notEmpty(nlapiGetCurrentLineItemValue('item','item')))
{
nlapiCommitLineItem('item');
}


nlapiSelectLineItem('item', itemLine);
}


// General find function for the item list
function findItem(itemID)
{
var cnt = nlapiGetLineItemCount('item');
for (var i=1; i <= cnt; i++)
{
if (nlapiGetLineItemValue('item','item',i) == itemID)
{
return i;
}
}


return -1; // -1 means not found
}




function isEmpty(tmp)
{
return tmp == null || tmp == '';
}


function notEmpty(tmp)
{
return !isEmpty(tmp);
}




function log(msg)
{
alert(msg);
}


Saturday, July 30, 2011

Webstore Main Menu Customization

We've MOVED!!!! www.codeboxllc.com/ksc

Who uses out of the box template for website any more? If you are using NetSuite Advanced Site Customization, you have the option to custom build the main navigation bar.

I've seen some posting on NetSuite Forum where fellow NetSuite users were asking for ability to build out dynamic menu system on their Webstore without heavy scripting. I am one of them.
Standard "Tabs" just doesn't do justice for my brilliant site layout. (I'm seriously being sarcastic here...)

So, how do you build this in WITHOUT heavy scripting? Well... unfortunately, you still need to do SOME scripting but method I found seems to work out without too much headache.

For my little project, I wanted to build dynamic horizontal menu layout.

In NetSuite, you can use <NLPAGETABS> to generate he horizontal tab menu layout. If you sue this tag nested between <table> and </table> tags in Logo and Tabs Template section under Body tab of your Theme.
As long as you have your tabs marked as "Show on Website", that one tag will render everything for you.

Here is sample menu tree I wanted to achieve:
Home page Products (Presentation Tab 0) Shopping Cart My Account
  Product Page 1 (Presentation Tab A)    
  Product Page 2 (Presentation Tab B)    
  Product Page 3 (Presentation Tab C)    

When visitor mouse over to Products, I want three sub pages to show up. As noted above, each page is a presentation tab with different items. 

If you were to ONLY use out of the box <NLPAGETABS>, those sub pages will get rendered as main navigation and will NOT look good.

Here is how I implemented dynamic custom main menu:
Step 1: Find the script you like.
I found a very handy, easy to use dynamic menu from Dynamic Drive. The script I found is very simple and not much modification is needed. Details of this script can be found here. Be sure to read their Terms of Use before using it. =)
I made some modifications to the CSS file to match the theme of my website. 

Step 2: Upload script files, CSS files and any images to your NetSuite Document folder.
What ever file you decide to use, you need to first upload it to your documents folder to be referenced on your Webstore. Script that I found from Dynamic Drive is fairly small and simple which I really like.

Step 3: Implement. (This is implementation using the Script from Dynamic Drive)
  • Make sure .js and .css files are referenced at the Header. [Your Theme] > General > Additon to <head> section.
Go to [Your Theme] > Body > Logo and Tabs Template section and add in your navigation.
Code Sample:
Main Navigation Code:
<div class="chromestyle" id="chromemenu">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#" rel="dropmenu1">Products</a></li>
<li><a href="#">Shopping Cart</a></li>
<li><a href="#">My Account</a></li>
</ul>
</div>
** red="dropmenu1" indicates a reference to sub menu items.
Sub Menu Navigation Code:
<div id="dropmenu1" class="dropmenudiv">
<a href="#">Product Page 1</a>
<a href="#">Product Page 2</a>
<a href="#">Product Page 3</a>
</div>
Script Tag:
** Add this after you've placed all your menu item
<script type="text/javascript">
cssdropdown.startchrome("chromemenu")
</script>

You can customize it further to your liking. Please read the details on Dynamic Drive regarding this script.

It's not that bad. I changed the CSS just a bit to match my pages' colors and didn't touch the original script file. 

If you'd like to see this page in action, please contact me by email. mhson1978@gmail.com

Oh yah, one note. If you customize the navigation this way, URL to pages will be a bit hard to manage. I've been looking into using Descriptive URL feature but its not working for me at the moment.
I've done some research on the Forum and some one DID say this:
You must have domain set up in order to use it.
I've actually asked my network admin to put in a CNAME for me. So if it works, I'll let you guys know.

Let me know if you have any questions. NetSuite, do you guys know when you'll add this as Part of NetSuite feature?

Saturday, May 28, 2011

Alternate more efficient way to Debug Webstore Scriptable Cart

We've MOVED!!!! www.codeboxllc.com/ksc

Recently, I had a nice email conversation with Jason K. from NetSuite. He thought my workaround for debugging scriptable cart/checkout was very clever. It means alot coming from him. However, he actually came up with even better way of debugging scriptable cart/checkout. Jason, you are the MAN!

His method resolves the issue of eating away at script metering in my version of workaround. Using nlapiRequestURL() eats 10 governance from allowance and it causes issue during form testing. He also mentioned something very important as well. With v2011.1, NetSuite relaxed the rules on type of Sales Order form that can be used for scriptable cart/checkout. This means, you are not restricted to using External Sales Order. You can customize Standard Sales Order and use it for the scriptable cart.

Here is how you go about doing this: Thank you Jason K. for coming up with this workaround!

Step 1: Create custom sales order forms for both Invoice and CashSales from standard invoice sales order and standard cashsale sales order.
Setup > Customization > Transaction Forms
** Make sure you do NOT put anything under custom code tab for both forms!!!
After you create the two new forms, make a note of their Internal IDs. You will need them in step 2.

Step 2: Create alternate version of your scriptable cart script. Keep currently working version as your backup. You may need it.
At the top of every event functions, add following line of code:
if (nlapiGetFieldValue('customform') != '[InternalID of SO Invoice from Step 1]'
&&   nlapiGetFieldValue('customform') != 'InternalID of SO CashSale from Step 1') {
  return;
}
This ensures that script only fires for the sales order forms you are using on Webstore.
Make sure every time you want to print debugging message, you use nlapiLogExecution() call to do so.

Step 3: Create new "Client Script" file and deploy it for all Sales Order.
Creating new script file: Set > Customization > Script > New > Client Script
Don't for get to fill out all your event functions and attach any library scripts. Deploying this script for Sales order is up to your preference. I usually do "Save & Deploy".
When you are deploying your client script for sales order, make sure list of audience includes Customer Center and perhaps most obvious thing, make sure it Applies to Sales Order.

Step 4: Attach newly created Sales Order forms to your webstore
Setup > Web Site > Set up web site. 
Under the Setup Tab > Preferences section, select new invoice sales order for Scripting Template (Invoice) and new cash sale sales order for Scripting Template (Credit Card).

That's it! To view execution logs, you can to go Script or Script Deployment record and click Execution Log tab.

Hope this works out for you guys. Thank you again Jason K for this workaround!

Thursday, May 26, 2011

My Latestest infatuation with JSON - JavaScript Object Notation

We've MOVED!!!! www.codeboxllc.com/ksc

I'm in love with JSON, JavaScript Object Notation. It's old news, I know this and I'm not that proud of it. But wise man once said, "It's better late than never". I'm currently addicted to using it. I am starting to go back to all NetSuite scripts I've created to this date and seeing where I can incorporate JSON.

I first used it when I worked on workaround for NetSuite Webstore Registration Process. The online Suitelet returns a JSON object which contains the result of search. I've started using it since.

I started using JSON as Mapping Table. I used JavaScript Arrays to store list of values and get them out but as you know, it's very inefficient. I also used JavaScript Objects as well to store attributes.

JavaScript Object to store Address info:
var addr1=new Object();
addr1.label='Company Address';
addr1.add1='1234 Hello World';
addr1.add2='#303';
addr1.city='My City';
addr1.state='My State';
addr1.zip='99999';
//second address
var addr2=new Object();
addr2.label='Home Address';
addr2.add1='999 Home World';
addr2.add2='';
addr2.city='My City';
addr2.state='My State';
addr2.zip='44444';


document.write(addr1.label);
//This will write out Company Address on the screen
document.write(addr2.label);
//This will write out Home Address on the screen
JSON to store Address info:
var addr={
  "CompanyAddress": {
    "label":"Company Address",
    "add1":"1234 Hello World",
    "add2":"#303",
    "city":"My City",
    "state":"My State",
    "zip":"99999"
  },
  "HomeAddress": {
    "label":"Home Address",
    "add1":"999 Home World",
    "add2":"",
    "city":"My City",
    "state":"My State",
    "zip":"44444"
  }
}


document.write(addr['CompanyAddress'].label);
//This will write out Company Address on the screen
document.write(addr['HomeAddress'].label);
//This will write out Home Address on the screen
What I like about using JSON approach is that it is already treated as an Array. Array with unique id. I can also have Server side Suitelet to generate something like this and use eval(); to parse it as JSON.

Take this as an example. Let's say someone registered from your website and provided series of addresses. If you have know exactly what you are looking for, you don't have to run a loop to find the right address. You can simply reference unique ID you gave and get related attributes for it just like above.

You can also run loop against your JSON object by doing this:
for (_v in myJsonObj) {
  document.write(myJsonObj[_v].attribute);
}
//above will loop through all elements in myJsonObj and print out value for attribute
Anyway, pretty simple yet powerful. Love LOVE using it!!!

Tuesday, May 24, 2011

Advanced Webstore Item templates

We've MOVED!!!! www.codeboxllc.com/ksc

I learned something cool last night. Do join me in celebrating my slow learning process of NetSuite.

Did you know you can set custom drill down webstore template at an individual item level?


Route I took to customizing look and feel of our webstore is to take a pre-designed template from NetSuite and modifying it. I can set default product drill down template for both Welcome and Product layouts.
For most folks, product drill down template doesn't have to be "Special", but for me, it had to be special. Especially when item options varies and you have to apply special validations against it.

If items in your webstore requires special attention for item detail page, definitely look into using this.

Try to abstract out different types of item detail page you'd need and group them together. When you create your drill down templates, it'll be based on these grouping.

You can gain access to creating different templates by going to Web Site Item/Category Templates page.
Setup > Web Site > Item/Category Templates


You can set individual drill down template per item by following these steps:

  1. List > Accounting > Items > Select the webstore item you wish to add custom drill down template
  2. Click on Store or Webstore tab. (This depends on the item you've selected)
  3. Next to "Item Drilldown Template", select your newly created template
  4. Save
It's a small things that makes me happy these days. This saved me from coding different javascript validation for each items with varying item options.



Saturday, May 21, 2011

Helpful JavaScript functions you may want to include in your Library Script

We've MOVED!!!! www.codeboxllc.com/ksc

We all need help sometimes. For me, I am not ashamed to look for help on the NetSuite Forum. Through out my experience with NetSuite deployment and customizations, I've found following JavaScript functions to be extremely helpful and I hope it provides you with some help as well.

Contains function: I found this script from CSS-Tricks website.
It is most useful when you have array of objects, strings, numbers and you wish to check for existence of a value you pass it.
Array.prototype.contains = function(arg) {
  for (i in this) {
    if (this[i]==arg) return true;
  }
  return false;
};
Here is how you use it.
var myArray = new Array("123","555","888","999"); //internal id of items
var itm = nlapiGetCurrentLineItemValue('item','item'); //get item id of current line item
if (myArray.contains(itm)) {
  alert('This Item exists in the Array!');
}
It makes your code lot simpler and easy to read.

Empty filter value checker: While writing custom search, I came across some odd errors here and there. Turns out, when search filter value is null or empty, it throws an error. After reading documentation, it turns out that you have to use @NONE@ in place of empty or null value.
function emptyFilterCheck(_val) {
  if (_val) {
    return _val;
  } else {
    return '@NONE@';
  }
}
 Send Email Function: I'm sure most of you have this function separated out. This is my version of the send email. It takes 6 parameters. From ID, To ID, Subject, Message, Attach to Record ID, Record Type.
Script will attach email to a record if the value is passed in.
function sendNotificationEmails(fromId, toId, strSbj, strMsg, attachToRecId, recType) {
  //check for sandbox
  if (env == 'SANDBOX') {
    strSbj='[SANDBOX] - '+strSbj;
  }


  try {
    //attach this email to record if defined
    if (attachToRecId != null) {
      var rec = new Object();
      if (recType==null) {
        rec['entity']=attachToRecId;
      } else if (recType=='transaction' || recType=='activity') {
        rec[recType]=attachToRecId;
      } else {
        //This is custom record
        nlapiLogExecution('DEBUG','msg','This is custom record:');
        rec['recordtype']=recType;
        rec['record']=attachToRecId;
      }
      nlapiSendEmail(fromId, toId, strSbj, strMsg, null, null, rec);
    } else {
      nlapiSendEmail(fromId, toId, strSbj, strMsg);
    }
    return true;
  } catch(e) {
    if (e instanceof nlobjError) {
      //Do your error handling here for e.getCode()and e.getDetails()
    } else {
      //Do your error handling for JavaScript issue: e.toString()
    }
  }
}
There are few others I'm trying to put it. Just to give you an idea, here are list of potential helper functions I am creating:

  • Search function which takes array of filter fields, values, and records' internal ID.
    I found myself writing these codes over and over again.
  • Specialized Pardot API library sets.
    If you use Pardot along with NetSuite, it's a good idea to create common function calls to Pardot. For example, LookupProspect(email), AddOrUpdProspect(email, JSONfldValObj), UpdProspectList(email, newList), UpdProspectCamp(email, newCampaign), GetActivities(email) just to name a few.
    I plan to write some sample Pardot API calls from NetSuite that I've written later.
  • Sublist related functions. 
What are some of your helper functions you are using?

Thursday, May 19, 2011

Working with Scriptable Cart in NetSuite Webstore - Lessons Learned

We've MOVED!!!! www.codeboxllc.com/ksc

It's been a while since my last post. I have a good reason. I've been struggling with Scriptable Cart feature in NetSuite advanced Webstore. After close to 9 days of none stop work, I think I've finally have it working.

This is new feature NetSuite released and it's still in an infant stage yet very powerful when coded correctly.
First thing I struggled with the most was not being able to see scripts' behavior when executed from the Webstore. You can read about on "How to debug NetSuite Webstore Scriptable Cart".

This gave me some major insight as to how NetSuite Webstore processes each addition/subtraction of items in the cart.

I want to give shout out to Jason K. for providing massive assistance in getting my cart script to work properly!

Here are some things I've found out that could help you:
  1. You can get execution environment variable using nlapiGetContext().getEnvironment() call. I didn't think this was possible but using this in your cart script actually returns SANDBOX, BETA or PRODUCTION from webstore.
     This will be very handy if you have to switch item ID depending on the environments.

  2. nlapiCommitLineItem('item') Is a MUST Call if you want your recalc to correctly recalculate totals. I tried taking the easy way out by not calling commit. What a newb mistake that was.

  3. nlapiLookupField() call can not be used. Obviously right? Well, I made this mistake as well. You may have an instance where you need to create item list table to add pro grammatically. I highly recommend using JSON object to create your item look up table.

  4. User selected items will ALWAYS be at line number 1 of the cart. The order of items may change after you've been to check out summary page but when it's added to the cart by the user; not script, it'll always be on the first line of item list.

  5. Jason K's trick 1: nlapiSelectLineItem results in an error if there's uncommitted values in the item list. He recommended to commit all items before adding new.
    I especially had issues with this. My work around was to use nlapiInsertLineItem with nlapiSetCurrentLinetItemValue method.

  6. Not sure if this will apply to everyone but IF you end up getting NetSuite Script Notice page during your execution of cart script or you end up getting Webstore maint. screen, it usually means there is an error in your script. For me, it was infinite loop issue. If you see your form re-initializing, it usually indicates error.

  7. Jason K's trick 2: Using global variable in the cart script sometimes fails. The workaround is to create custom body field on your form and use that as temporary global field that you set and get using nlapiGetFieldValue() call.
  8. Jason K's trick 3: When doing extra commit, always check for valid item in the current row. 
Some quick sample code from Jason K on safeSelectLine and safeSelectNewLine

** notEmpty is a custom function which simply checks to see if passed in value is null or empty string

safeSelectNewLine function:
function safeSelectNewLineItem() {
  if (notEmpty(nlapiGetCurrentLineItemValue('item','item'))) {
    nlapiCommitLineItem('item');
  }
  nlapiSelectNewLineItem('item');
}
safeSelectLine function:
function safeSelectLineItem(itemLine) {
  if (notEmpty(nlapiGetCurrentLineItemValue('item','item'))) {
    nlapiCommitLineItem('item');
  }
  nlapiSelectLineItem('item', itemLine);
}
Most important lesson I've learned is that cart script behaves differently in webstore. Do test your code on the external form but be extra careful not to fully trust the result. When testing on webstore, keep close eye on your log execution files. If you ever see page init more than once, you know you have an error somewhere.

As I mentioned before on my previous post, turning on logging on webstore will slow down your cart since it's calling to your external suitelet so keep that in mind as well. 

Hope this helps you. Let me know if you get stuck. I'll try my best to help you out.

Saturday, May 14, 2011

How to debug Netsuite Webstore Scriptable Cart

We've MOVED!!!! www.codeboxllc.com/ksc


Notice:
Blogspot had issues with their server and post I originally wrote got deleted. I do apologize for missing link:

Important Update on this Post: 5/17/2011:
nlapiRequestURL() eats up API Governance meter by 10 points. Testing on External Form, if you have this turned on, you only have 1000 limit. On Webstore, you seem to have 2147483647. Don't ask me where that number came from.

So, Here I go again. How DO you debug scriptable cart executing on webstore? The script itself is attached to the External Sales Order form you create which implies is client level script. You can't use Firebug to step through it either.So how do you debug when your script is not returning the results you want?

I began using this workaround and it has helped me alot.
Workaround: Create Suitelet (Available without Login) to track printing of debug messages and call it using nlapiRequestURL() from your scriptable cart script.

Write Suitelet Script: Save as "sl_writelog.js" and push out to Netsuite 
** Please note, for simplicity, I've written my script to use GET event.
function slExecLog(request, response){
  if (request.getMethod() == 'GET') {
    var log = filterUserInput(request.getParameter('log'));
    var title=filterUserInput(request.getParameter('title'));
    writeLog('DEBUG',title,log);
    response.write('called back');
  }
}
Deploy your script:
  1. Login to Netsuite and go to Setup > Customization > Scripts > Click New
  2. Select Suitelet as script type
  3. Provide Name and ID for this script.
  4. Under Scripts tab, select "sl_writelog.js" for Script File and "slExecLog" as Function
  5. Select "Save and Deploy" option.
  6. Provide Name and ID for this script deployment
  7. Check "Available Without Login" 
  8. Select GET Request as Event Type.
    If you choose to use Post, you should change your script to check for POST and also select POST Request as Event Type
  9. Under Audience tab, select "All Roles"
  10. Save
Once you've deployed your script, copy the External URL for this deployment. According to NetSuite documentation, nlapiRequestURL() does NOT send User Session information. 

Link to your Suitelet from Scriptable cart script:
Open your scriptable cart script and create a function which will call your suitelet. This is how I did it:
Please note that anything enclosed in [ and ] is to be replaced by your code including the brackets.
function wslog(_txt) {
  if (!_txt) {
    return;
  }
  var loginUrl = '[External URL for your Suitelet]&title=[Value of title]&log='+_txt;
  if (wsdebug) {
    nlapiRequestURL(loginUrl, null, null);
    return;
  }else{
    alert(_txt);
  }
}
You will notice above that I check for wsdebug value. This is global boolean value I created so that I can turn on/off calling of my debug suitelet.
When I'm testing on the form, I set this value to false so that I can see the alert messages. Testing/deployment on webstore, I set this value to true.
Check your debug messages:
Once everything is doen, go to your Webstore and add items to your cart so that your scriptable cart script will fire.
To check the log messages, open your Suitelet script record and click on Execution Log.


Friday, May 6, 2011

Separating Name field to First and Last Name in NetSuite Webstore

We've MOVED!!!! www.codeboxllc.com/ksc

NetSuite, I have bones to pick with you! Why would you just put Name field on e-commerce registration form? WHY???!?!?!?!

Well, until they put in a fix for it, I do have a work around for those who wish to use it.
If you have already customized your webstore, most likely you have script files you are placing on the header of your web site theme.

For this purpose, create a new JavaScript file. For now create a function called checkPage().
function checkPage() {
}
 Save and load it to your live hosting folder and place a reference to it at the header of your website theme.

Append functions to body tag:
Open your theme by going to Setup > Website > Theme > [Your Theme]
Under General tab, please reference to your new javascript file on "Addition to <head>".
Also under general tab, append your new function call next to "page_init()".

Your body tags' onload call should look like this: onload="page_init(); checkPage();"

Doing this will call your checkPage() every time different sections of your webstore is loaded.

Finding field info:
The name text box should have id and name of "name".

Sudo Coding:
What we wanna do is this:
1. Find name text box and do the following:
- Change type from text to hidden
- Clear onfocus and onchange. This may not be necessary
2. Create first name text box element
- Add id of fname (your choice)
3. Create last name text box element
- Add id of lname(your choice)
4. Place the two elements where original name text box was
5. Write validation script to check for missing values for the two.
6. IF validation passes, set the value of now HIDDEN name field with first and last name provided. (VERY IMPORTANT STEP)

Lets add the meat to our script:
I found that registration page has specific form called "newcust". Checking for existence of this form will be our queue to begin our modification process.
Oh BTW, if you know jQuery, more power to ya. It'll be much easier

Here is the code:

function checkPage() {
//find out if registration form exists
var regform = document.forms['newcust'];
if (regform !=null) {
var ntx = regform.name;
ntx.setAttribute('type','hidden');
ntx.onfocus='';
ntx.onchange='';
//get span node that wraps name text box
var cellspan = ntx.parentNode;


var fnamebox = document.createElement('input');
var txtNode = document.createTextNode(' ');
var lnamebox = document.createElement('input');
fnamebox.setAttribute('type','text');
fnamebox.setAttribute('id','fname');
fnamebox.setAttribute('onfocus',"txtChange('fname','First Name');");
fnamebox.setAttribute('onblur',"txtChange('fname','First Name');");
fnamebox.value='First Name';
lnamebox.setAttribute('type','text');
lnamebox.setAttribute('id','lname');
lnamebox.value='Last Name';
lnamebox.setAttribute('onfocus',"txtChange('lname','Last Name');");
lnamebox.setAttribute('onblur',"txtChange('lname','Last Name');");
cellspan.appendChild(fnamebox);
cellspan.appendChild(txtNode);
cellspan.appendChild(lnamebox);
}
}


//just helper function to switch between default values.
function txtChange(_id, _text) {
var el = document.getElementById(_id);
if (el && el.value == _text) {
el.value='';
}else if(el && el.value=='') {
el.value=_text;
}
}

This should do it. You just need to now add validation script (Sudo code step 5 & 6) for onsubmit.
If validtion passes, you can do something like this.

var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
document.getElementById('name').value = fname+' '+lname;

This isn't the only way you can do this. I just wanted to show you guys that it IS possible to do this.