B4J Code Snippet [BANano]: Sharing the goodness

Discussion in 'B4J Code Snippets' started by Mashiane, Jan 8, 2019.

  1. Mashiane

    Mashiane Expert Licensed User


    Thought I should create my own easy reference list of stuff I've posted here about BANano.

    Creation: Create your UX with MaterializeCSS using UOEBANano
    Creation: Waking up the JQuery Mobile Dino for a rest api experiment

    Tutorial: BANanoSQL - Crudying around with BANanoSQLUtils
    Tutorial: Exploring BANano Events
    Tutorial: Creating a Hotel Reservation App with BANanoJQM
    Tutorial: Distributing & Accessing an existing SQLite Database - Part 1
    Tutorial: Creating a CRUD app with LocalStorage Backend

    Question: [SOLVED] Extending Event Driven BANanoSQL with own CallBacks?
    Question: [SOLVED] How to maintain element events?
    Question: [SOLVED] How to set BANanoEvent Bubbling Off?
    Question: [SOLVED] BANanoMaterial Error Fix
    Question: [SOLVED] How can I run a JavaScript Method and wait for it to finish?
    Question: [SOLVED] Returning all list items in For Each
    Question: [SOLVED] How does one use Header.AddMeta?
    Question: [SOLVED] How to turn minify off/on
    Question: [SOLVED] Empty string passed to getElementID('')
    Question: [SOLVED] How to find element existence
    Question: [SOLVED] How to CallSub inside #If JavaScript
    Question: [SOLVED] Library Compilation FileNotFound Exception
    Question: [SOLVED] Map.Initialize inclusion of map keys
    Question: [SOLVED] How to transvese elements by name and return attributes
    Question: [SOLVED] How to call different subs for different elements
    Question: [SOLVED] RangeError: Maximum Stacktrace exceeded
    Question: [SOLVED] How do I refresh a page
    Question: [SOLVED] FloatingActionButton iif method not defined
    Question: [SOLVED] Enumeration Initialization Assignments
    Question: [SOLVED] Else If Transpiling Error
    Question: [SOLVED] Map Object Enhancements
    Question: [SOLVED] Support for String()
    Question: [SOLVED] Using / Converting Own B4J Classes
    Question: [SOLVED] Ajax Calls: How to convert B4J Http Calls

    To relook at these *unresolved

    Question: How to embed & read a json file / rather use BANanoSQL to load it?
    Question: How can I upload a file using Php?
    Question: CRUD bug using wait
    Question: Using MySQL / MSSQL with PHP
    Question: How to add dynamic css / injectcss to my app
    Question: How to AddJavascriptFile and AddCSSFile on demand

    Now for some code snippets...

    Removing Attributes

    One of the elusive attributes is the 'disabled' attributes for elements. Apparently whether you set this to true/false to enable your element, the status quo stays the same. It seems the only way to toggle this is to remove it to enable your element.

    The code snippet here is to remove attributes from elements.

    'remove an attribute
    Sub removeAttr(elID As String, attrName As String)
        elID = elID.tolowercase
    Dim jQ As BANanoObject
    End Sub

    Update: 30 Jan 2019

    A new method to remove attribute has been added as BANano.BANanoElement.RemoveAttr
    Last edited: Feb 8, 2019
    aeric likes this.
  2. Kiffi

    Kiffi Active Member Licensed User

    I know you're already using jQuery in your current project. However, the recommended way for users who can't or don't want to use jQuery is to use the built-in Umbrella.js in BANano.

    Sub removeAttr(elID As String, attrName As String)
    End Sub
    amaxco, Mashiane and alwaysbusy like this.
  3. Mashiane

    Mashiane Expert Licensed User

    Thanks Kiffi. Setting the disabled attribute however does not enable my button and I also don't want to use JQuery for such a mandane task.
  4. alwaysbusy

    alwaysbusy Expert Licensed User

    @Kiffi solution is the correct one for non-boolean attributes. The build-in Umbrella.js (4kb) does 95% of what jQuery does (250Kb). This can highly affect the speed of your website/webapp especially on mobile devices so avoid (if possible).

    However in this case of disabled, this is one of those weird boolean attributes that cannot be assigned with true or false (go figure!) and do effectively need to be removed to have any effect. In the next version, I will make a RemoveAttr on BANanoElement
    Last edited: Jan 17, 2019
  5. Mashiane

    Mashiane Expert Licensed User

    Calling B4J methods directly

    There are more than one ways to skin a cat, it is said, so yesterday I made an assumption and it turned out to be true. I needed to call a b4j method that was no linked to an event handler in my class module, turns out, I can.

    Application Name: ATM
    B4J Class Name: pgIndex
    B4J Method To Call: DeleteMember
    Problem Statement: This does not have an event handler
    My Scenario: When I click a delete button, the user should be prompted with a confirm dialog (this uses sweet dialog), when the user selects Yes, a B4J method should be fired to actually delete the record else No. The generated Yes / No button for the sweetmodal are automatically generated and they dont have IDs to I cannot assign an event handler, however you can pass javascript to execute onYes and onNo. So I need a B4J method to be executed and not javascript, this B4J method anyway will be transpiled to BANano javascript subroutine.

    The aha moment!

    Solution: pass _banano_atm_pgindex.deletemember(); to the Yes script of sweetmodal. Yes, you can define your own buttons for the sweetmodal but I didnt want to add buttons, yet.

    Below is my DeleteMember sub routine in B4J in my pgIndex class, this class is like a 'page' for my BANano project.

    user clicked yes on confirmation, process the deletion
    Sub DeleteMember
    'get the memberid to delete
        Dim memberid As String = Page.GetLocalStorage("memberid")
    'get the existing members
        Dim strMembers As String = Page.GetLocalStorage("members")
    If strMembers = "" Then
    'this will store all unmatching records
            Dim nList As List
    'convert existing members to a list
            Dim lstM As List = App.Json2List(strMembers)
    'each member is a json string
            Dim mTot As Int = lstM.Size - 1
    Dim mCnt As Int
    For mCnt = 0 To mTot
    Dim strMember As String = lstM.Get(mCnt)
    Dim memberM As Map = App.Json2Map(strMember)
    'the id number is the key
                Dim sidnumber As String = memberM.Get("idnumber")
    If sidnumber <> memberid Then
    End If
    'convert the list and save it back
            strMembers = App.List2Json(nList)
    Page.setlocalstorage("members", strMembers)
    'create the table
    End If
    End Sub
    This code below, which traps the eventid, when a deleterow_ linked element is clicked, a sweetmodal prompt is displayed for the user to confirm, when they click 'Yes', the code to delete the member is executed.

    Case "deleterow"
    Dim rowPos As String = App.mvfield(thisEvent,2,"_")
    Dim rowKey As String = App.MvField(thisEvent,3,"_")
    'ask the user
                'save this memberid for later retrieval
                Page.SetLocalStorage("memberid", rowKey)     'BANano.setLocalStorage
                'save the table row for later retrieval
                Page.SetLocalStorage("index", rowPos)
    'call a method existing in this application
                Dim onYes As String = Page.CallMethod(App.AppName,moduleName,"deletemember();")
    'code to generate the sweet modal confirm script (this returns javascript code only)
                Dim msg As String = Page.SweetModalConfirm($"Confirm Delete: ${rowKey}"$, _
    "Are you sure that you want to delete this record? You will not be able to undo your changes.""_banano_atm_pgindex.deletemember();""")
    'same as banano.eval(javascript)


    Update: 30 Jan 2019

    A new method has been added to BANano as BANano.CallSub
    Last edited: Jan 30, 2019
    joulongleu likes this.
  6. Mashiane

    Mashiane Expert Licensed User

    Problem Statement

    1. Publish to XAMPP and open the webapp in release mode
    2. Publish to DirApp and open webapp in debug mode

    I'm realizing that I have not been productive with my code, so I try out something that is working for me. On App_Start, i detect if I am in release or debug mode.
    If release mode i build my app to the XAMPP folder and if in debug mode I build my my to File.DirApp. I want to open the webapp irrespective on the default browser

    In Process_Globals...

    Private jx As JFX
    Somewhere in App_Start of my app after I have added css and js files I have...

    Dim url As String
    #if release
            'save to xampp folder
            url = $"${AppName}/index.html"$
            Dim appPath As String = File.Combine(File.DirApp,AppName)
            url = File.GetUri(appPath,"index.html")
    #end if
    This way either way of publishing works just like I want it. AppName is the 'short name' of my app.

    joulongleu likes this.
  7. Mashiane

    Mashiane Expert Licensed User

    TIP: I have been wondering why I coud'nt read my records from the db. CaseSensiTivity..


    I need to remember that stuff here is caseSensitive eish...
  8. Mashiane

    Mashiane Expert Licensed User

    A collection of some of my quick methods to set/get element stuff on a banano project. This is specific to using the ID of an element.

    'change the image that shows to another using data url
    Sub ChangeImage(imgid As String, dataurl As String)
    End Sub

    'banano empty call
    Sub Empty(elID As String)
        elID = elID.tolowercase
    End Sub

    'banano append call
    Sub Append(elID As String, elContent As String)
        elID = elID.tolowercase
    End Sub

    'banano settext call
    Sub SetText(elID As String, elContent As String)
        elID = elID.tolowercase
    End Sub
    'banano get the checked value
    Sub GetChecked(elID As StringAs Boolean
        elID = elID.tolowercase
    Return BANano.GetElement($"#${elID}"$).GetChecked
    End Sub

    'banano set the checked value
    Sub SetChecked(elID As String, value As Boolean)
        elID = elID.ToLowerCase
    End Sub

    'banano setvalue call
    Sub SetValue(elID As String, elContent As String)
        elID = elID.tolowercase
    End Sub

    'banano get value call
    Sub GetValue(elID As StringAs String
        elID = elID.tolowercase
    Dim sValue As String = BANano.GetElement($"#${elID}"$).GetValue
    Return sValue
    End Sub

    'banano getstyle
    Sub SetStyle(elID As String, elContent As String)
        elID = elID.tolowercase
    End Sub

    'banano addclass
    Sub AddClass(elID As String, elContent As String)
        elID = elID.tolowercase
    End Sub

    'banano set attribute
    Sub SetAttr(elID As String, elProp As String, elContent As String)
        elID = elID.tolowercase
    End Sub
    'get text value
    Sub GetText(elID As StringAs String
        elID = elID.tolowercase
    Dim elKey As String = $"#${elID}"$
    Dim sText As String = BANano.GetElement(elKey).GetText
        sText = sText.trim
    Return sText
    End Sub
    'set values from elements and save as map
    Sub SetValues(record As Map)
    For Each strfld As String In record.keys
    Dim strv As String = record.Get(strfld)
    End Sub

    'set values to zero
    Sub SetValuesToZero(flds As List)
    For Each strfld As String In flds
    End Sub

    'clear text fields
    Sub ClearValues(flds As List)
    For Each strfld As String In flds
    End Sub

    'get values from elements and save as map
    Sub GetValues(flds As ListAs Map
    Dim rec As Map
    For Each strfld As String In flds
    Dim strv As String = BANano.GetElement($"#${strfld}"$).GetValue
    Return rec
    End Sub
    'get text value
    Sub GetTextBox(elID As StringAs String
        elID = elID.tolowercase
    Dim elKey As String = $"#${elID}"$
    Dim sText As String = BANano.GetElement(elKey).GetValue
        sText = sText.trim
    Return sText
    End Sub

    'set the text
    Sub SetTextBox(elID As String, txtValue As String)
        elID = elID.ToLowerCase
        elID = 
    Dim el As BANanoElement = BANano.GetElement(elID)
    End Sub

    ''set radiovalue by name
    Sub SetRadio(elID As String,elValue As String)
    "setRadio",Array As String(elID,elValue))
    End Sub

    'get element by name
    Sub GetElementByName(elID As StringAs BANanoElement
    Dim el As BANanoElement = BANano.GetElement($"[name='${elID}']"$)
    Return el
    End Sub

    'get radiovalue by name
    Sub GetRadio(elID As StringAs String
        elID = elID.tolowercase
    Dim sValue As String  
        sValue = BANano.RunJavascriptMethod(
    "getRadio",Array As String(elID))
    Return sValue
    End Sub
    #If JavaScript
    function setRadio(vRadioObj, vValue) {
        var radios = document.getElementsByName(vRadioObj);
        for (var j = 0; j < radios.length; j++) {
            if (radios[j].value == vValue) {
                radios[j].checked = true;

    function getRadio(vRadioObj) {
        var radios = document.getElementsByName(vRadioObj);
        for (var j = 0; j < radios.length; j++) {
            if (radios[j].checked) {
                return radios[j].value;

        return "";
    #End If
    The code above for the radio boxes works based on the 'name' of the radio controls which could be multiple for the same name, so for radio controls the name is used and not the id. This is useful for radiogroup controls etc. One can also just write the javascript code above in BANano however at the end it will achieve the same result.

    Last edited: Mar 27, 2019
    joulongleu likes this.
  9. Mashiane

    Mashiane Expert Licensed User

    The SetStyle method for BANano expects a JSON string. You can however have a wrapper for this that you can pass a map to and then it generates the required JSON string for SetStyle. Well, I find it easier to use.

    First we need a method that one can pass a map and it generates a JSON string.

    'convert a map to a json string
    Sub Map2Json(mp As MapAs String
    Dim JSON As BANanoJSONGenerator
    Return JSON.ToString
    End Sub
    So that we can then write our SetStyle method that we can use to set our element styles using a map.

    Sub SetStyle(elID As String, styleMap As Map)
    Dim strStyle As String = Map2Json(styleMap)
    End Sub
    Then we can use this as:

    SetStyle("th",CreateMap("font-weight""bold""background-color""#acf",    "border-bottom""1px solid #cef"))
    "td,th", CreateMap("padding""4px 5px"))
    Works like a charm!

    joulongleu likes this.
  10. Mashiane

    Mashiane Expert Licensed User

    You have created a form element with other input controls inside. This piece of code will serialize your form to an object i.e. Map

    NB: Each element on the form MUST HAVE a name property.

    #if javascript
    function Form2Json(form) {
        // convert form name value attributes to json
        var array = $(form).serializeArray();
        var json = {};
        $.each(array, function () {
            if (typeof json[this.name] == 'undefined') {
                json[this.name] = this.value || '';
            } else {
                json[this.name] += "," + this.value;
        return json;
    #End If
    Lets define the method to get the Form data and save it to a map variable.

    get the form data
    Sub GetForm(frmName As StringAs Map
        frmName = frmName.tolowercase
    Dim frmKey As String = $"#${frmName}"$
    Dim bo As BANanoObject = BANano.RunJavascriptMethod("Form2Json"Array(frmKey))
    Dim res As Map = bo.Result
    Return res
    End Sub

    Dim fd As Map = GetForm("registerform")
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice