VBCS: Using cookies to save user preferences / user input from the UI

Jarvis serves cookies pizza!

Today we will be looking into two examples of using cookies when baking pizza. The first is a hard save of information through a save and get button on a webpage, the second is on the fly saving of information on a webpage (saving fields locally in cookies so a user can leave and re-enter a page without losing data).

This post will also include dynamically showing and hiding table columns, as well as using the afterNavigate event.

PRELUDE

Before starting that we need to realize that Jarvis is in the business of baking pizza and not cookies. This means we will import the cookie functionality using js-cookie:
https://github.com/js-cookie/js-cookie

Lucky for us js-cookie is written in AMD format so we can import it with requireJS (the only format that VBCS “understands”). You can read why here: https://requirejs.org/docs/whyamd.html

So normally we would import the js-cookie files inside the application. I am not a big fan of this however, so I always try to use requireJS towards an external location. I do not want to host my own files though, so after a single Google query I found the following:
https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js

(Please note that cdnjs.cloudflare.com is a very reliable source of common JS libraries).

To be able to use this library inside VBCS we can import it by editing the Source View -> webApps -> your application -> app-flow.json.
Paste the following section:

"requirejs": {
  "paths": {
    "cdnJsCookie":"https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min"
  }
},

Note that VBCS always checks .js files automatically!! So you have to remove .js from the URL.

PART 1

Now we are ready for our first page, saving a preference or information by a button. To do this, we will first create a second page called main-pizza-list. Let’s leave it empty for now and create a button on main-start with the text “Navigate to pizza list”.

Do a standard event ojAction and create an action chain (and rename the action chain to ‘navigateToPizzaListChain‘). Add a Navigate step, choose peer page and pick the main-pizza-list. You can try this out, and you can see in the URL that you navigate to the sub page.

Now before we continue we want a pizza list, the easiest way to do this is adding a BO. I’ve added a BO called Pizza, with columns name (string) and ‘hasCookiesOnPizza’ (boolean). I have filled the BO manually with some rows.

Now let’s design the main-pizza-list. Let’s add a switch component, with the text “Show ‘hasCookiesOnPizza’ column”, two buttons with the text “Save preference” and “Get preference”. Also add a table beneath that. When editing the table, go to the wizard and choose Add Data (it’s greyed out for me because I already did that).

In the wizard choose the BO Pizza, and then choose the id, name and ‘hasCookiesOnPizza’ columns. Ignore the third screen and finish the setup. It should now show you 4 rows in the design mode.

The next step is to define all variables, go to the variable page of the pizza list (it should already show ‘pizzaListSDP‘) and add an array of objects called ‘pizzaListColumns‘. Add the following code to the “default value” field:

[
  {
    "headerText": "id",
    "field": "id"
  },
  {
    "headerText": "name",
    "field": "name"
  },
  {
    "headerText": "hasCookiesOnPizza",
    "field": "hasCookiesOnPizza"
  }
]

Also add a variable ‘showCookiesColumn’ of type Boolean, and set the default value to true.

Now lets get back to the page, click on the switch and change the Data tab -> Value to: ‘{{ $variables.showCookiesColumn }}‘. Now switch to the Code view in the top right, and change the ‘columns=’ part of the table to: ‘columns=”{{ $variables.pizzaListColumns }}”
Now the page should still work, but we have binded our visual objects to our variables.

The next step is to add some logic! Let’s show and hide the column ‘hasCookiesOnPizza’ dynamically. Go to the variable page and select the ‘showCookiesColumn‘, now go the the Events tab to the right and add an event of type ‘onValueChanged‘. Rename the action chain to ‘onShowCookieChangeChain‘.

After this we can do some really smart stuff, but let’s keep the action chain really simple for now:
Add an if statement with condition ‘showCookiesColumn
Add an assign variable step in the true path that assigns ‘pizzaListColumns’ to the following value:

[
  {
    "headerText": "id",
    "field": "id"
  },
  {
    "headerText": "name",
    "field": "name"
  },
  {
    "headerText": "hasCookiesOnPizza",
    "field": "hasCookiesOnPizza"
  }
]

IMPORTANT!! Change the Reset Target to empty (otherwise VBCS adds above entries to ‘pizzaListColumns’ array instead of overwriting the array).
Add an assign variable step in the false path that assigns ‘pizzaListColumns’ to the following value (having removed the ‘hasCookiesOnPizza’ column):

[
  {
    "headerText": "id",
    "field": "id"
  },
  {
    "headerText": "name",
    "field": "name"
  }
]

Now go back to the page and press Live or Play, slide the switch and the column should disappear and reappear!!

The last step is to use cookie functionality. We start with the code first, as this is easier. Go to the JavaScript page of the main-pizza-list. Here we want to import our js cookie library, so we can use the library to save and get cookies. We do this by editing the top of the JavaScript file, where we import our “cdnJsCookie” and give it a name cookies to access inside this file:
define([“cdnJsCookie”], function(cookies) {

Now for the methods, add the following code:

/**
*
* @param {String} cookieName
* @param {String} cookieValue
*/
PageModule.prototype.SetCookie = function (cookieName, cookieValue) {
  var expiresInFiveMinutes = new Date(new Date().getTime() + 5 * 60 * 1000);
  cookies.set(cookieName, cookieValue, {"expires":expiresInFiveMinutes});
};

/**
*
* @param {String} cookieName
* @return {Boolean}
*/
PageModule.prototype.GetCookie = function (cookieName) {
  return cookies.get(cookieName);
};

Note that I have let the cookies expire every 5 minutes for testing purposes. For experience purposes, it is nice to show that auto-completion works inside the editor because of the AMD format. One can try and type: ‘cookies.‘ inside a method and wait a second, you can see that all methods provided by the js-cookie library will be listed.

Now we want to use this functionality in the UI. Create two events type ojAction and their action chains respectively. I have called them ‘saveShowCookiePreference’ and ‘getCookiePreferenceAndSetBoolean‘. Start with the ‘saveShowCookiePreference‘, add a Call Module Function step and pick ‘setCookie‘. Click on one of the field input mappings to the right, change cookieName to ‘vbcsJarvisPizzaShowCookies’ and link ‘showCookiesColumn’ on the left side to the cookieValue on the right side. This action chain is now finished.

The second action chain is the ‘getCookiePreferenceAndSetBoolean‘. Add another Call Module Function, call it ‘getCookieValue‘, map the cookieName to ‘vbcsJarvisPizzaShowCookies’ and pick Boolean as return type. Also add an assign variable step, and assign ‘getCookieValue’ to ‘showCookiesColumn‘.

That’s it! Now we have a working cookie setter and getter. Try running the page, disabling the cookies column, save preference, refresh the page and pushing the get preference button. The switch and cookie column should be disabled!! One can imagine this is extra powerful when it’s done automatically, which I will partially show in the next part of the blog.

PART 2

Imagine after you picked your pizza you are rerouted to our order form. Create a page called main-pizza-order-form, also add a button to the main application that is able to navigate us to this order form. Create a form on the main-pizza-order-form page with two input fields, name, address and extra order info. Bind them to three String variables name, address and extraInfo (see above for more info).

Now I find one save cookie action chain better, so create an action chain manually called ‘setCookieForField‘. Add one input variable type Object called eventDetails. Add event listeners to name, address and extraInfo String variables that call the ‘setCookieForField’ with the complete event mapped.

Now we need to call the set cookie library again, follow the above js-cookie steps for this page or copy paste it from your main-pizza-list page.

In the ‘setCookieForField’ action chain, do a callModuleFunction and pick the ‘setCookie’ method. As name do the following with expression on:
“vbcsPizzaOrderForm_” + $chain.variables.eventDetails.name

This will ensure that we get the variable name (so we are saving cookies ‘vbcsPizzaOrderForm_name‘, ‘vbcsPizzaOrderForm_address’ and ‘vbcsPizzaOrderForm_extraInfo‘). Map the ‘cookieValue’ to ‘$chain.variables.eventDetails.value

Now create an action chain called ‘getCookieForFields‘, for simplicity I have done this manually, one could do this with JavaScript dynamically. Add a Run in Parallel and add three call module functions calling ‘GetCookie‘, map them to ‘vbcsPizzaOrderForm_name‘, ‘vbcsPizzaOrderForm_address’ and ‘vbcsPizzaOrderForm_extraInfo‘. Add one assign variable step per branch, assigning the result of the module function to the correct variable.

Lastly we add an event on vbAfterNavigate and pick the ‘getCookieForFields’ action chain. We are finished with out page! It will now save all input when a value from one field is committed (so you can also fill just 1 input and it will save it inside the cookie). Try typing and reloading the page!

Join the Conversation

1 Comment

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: