Code for Notification Badge on new Layout Menu

image
If anyone has the ability to generate/correct some javascript code to replace the notification badge number with the number of records in a table (with one or more conditions preferably). Ive spent a couple of hours with chat gpt to no avail.

If i´m not mistaken the code should call the records with a condition from the datatable using the ollowing API script:

var myHeaders = new Headers();
myHeaders.append(“X-Tadabase-App-id”, “{{appId}}”);
myHeaders.append(“X-Tadabase-App-Key”, “{{appKey}}”);
myHeaders.append(“X-Tadabase-App-Secret”, “{{appSecret}}”);

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("https://api.tadabase.io/api/v1/data-tables/{{tableId}}/records?filters[items][0][field_id]=field_36&filters[items][0][operator]=is&filters[items][0][val]=Test 2", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

after this the javascript should count the number of records and replace the notification badge.

I guess in my use case I expect several notifications per minute at certain times of the month so if feasible the script would ideally run every set period of time (in my case every 5 mins).

The following is what i´ve got chatgpt to churn out upto now and it´s unclear after checking the console log even if the API is working:

// Ensure the DOM is loaded before running the script
document.addEventListener("DOMContentLoaded", function() {
    // API credentials
    var myHeaders = new Headers();
    myHeaders.append("X-Tadabase-App-id", "XXXXXXXXX");
    myHeaders.append("X-Tadabase-App-Key", "XXXXXXXXX");
    myHeaders.append("X-Tadabase-App-Secret", "XXXXXXXXX");

    var requestOptions = {
        method: 'GET',
        headers: myHeaders,
        redirect: 'follow'
    };

    // Fetch the data from Tadabase API
    fetch("https://api.tadabase.io/api/v1/data-tables/LX6QawrZk4/records?filters[items][0][field_id]=field_285&filters[items][0][operator]=is&filters[items][0][val]=En%20Proceso%20TPV%20Virtual", requestOptions)
        .then(response => {
            if (!response.ok) {
                throw new Error("Network response was not ok");
            }
            return response.json(); // Convert response to JSON
        })
        .then(result => {
            console.log(result); // Debug: Log the entire API result

            // Check if the result has items and count them
            if (result.items && result.items.length) {
                let numberOfPayments = result.items.length; // Get the number of items (payments)
                console.log('Number of payments:', numberOfPayments); // Debug: Log the number of payments

                // Update the badge with the dynamic number of payments
                let notificationBadge = document.querySelector('.tb-notification-badge');
                if (notificationBadge) {
                    notificationBadge.textContent = numberOfPayments; // Update badge
                } else {
                    console.log("Notification badge element not found."); // Log if the element is not found
                }
            } else {
                console.log("No records found or result structure is unexpected.");
                document.querySelector('.tb-notification-badge').textContent = "0"; // Default to 0 if no items are returned
            }
        })
        .catch(error => console.log('Fetch error:', error)); // Log any fetch errors
});

Any help with this highly appreciated and I imagine other will benefit from such script :slight_smile:

Greetings TB Community-

This video will depict how I have created a show/hide workflow for the notification badge. Feel free to use it as a guide when you design your application.

Instructional Video:

Javascript Code for Layout Dashboard:
Change the selector to your application/layout’s selector.

try {
    var openMessages = "{loggedInUser.Open Messages}"; 
    if (openMessages === "0") {
        document.querySelector('#layout_floating > div > header > nav > div.tb-menus > ul.tb-profile-menu-items > li.tb-notification-icon > a > span').classList.add('hide');
    }
} catch (error) {
    console.error('Error processing Open Messages:', error);
}

Hope this helps for all,
Adam

2 Likes

@SafetyUniversity, this looks great but keep in mind in the value you can simply put in the variable there:

@Ashley, saving your API details in the JS is very much not recommended. You can create an App Variable or user variable which you enter into this value.

You can see this video at around 4:10 on how you can define values directly in the layout menu:

2 Likes

Thankyou very much @moe this seems by far the easiest way for my case, by just adding an app variable. The only downside is that app variables dont allow you to apply conditions to the “count record” formula function which seems a shame as I imagine this would come in very handy for many. Another idea might be to encorporate a checkbox to hide notification when value is zero/blank. Only ideas :wink:

Just wanted to share what ive learnt from this post and how I applied that learning. Screenshot contains 4 different approach to achieving the same thing. Ive also attached a page link to the bell icon so the user can go to record set to acknowledge the open action request.

@Ashley - I know what you mean, in my case, I added a complex formula field in the Users table to count how many ‘open’ status risk mitigation actions are assigned to the user and then I used the user variables instead of ‘formula’ type of App variable. I did notice though when I created a ‘static’ app variable it didnt work. it shouldve just picked up the field value but for some reason that route didnt work. Also I notice the table shows ‘0’ when there are no open actions but on the front end it shows nothing, ideally for my case I would want ‘0’ to show instead of hidding notification title and/or icon.

1 Like

@Shumon I have the same issue with the new layouts. I thought it was because I did something wrong. No pictogram is showing-up.

image

@Peter I followed the video (3.10) above from @moe and it does work. Like me, you probably got the old image field in your Users table which is now discontinued.

Step 1: Add ‘attachment’ (file) field (ProfileImage) and upload profile image into record.
Step 2: On the layout, ensure you preview as ‘Any Logged In User’
Step 3: Under Users Menu, you will now see a new option ‘Use image field’, add field name from step 1 as shown in screenshots below:

2 Likes

1 Like

I have written a short post regarding the idea of being able to filter through data conditions App variables using “Count Record” formula functions. Your support would be appreciated if you think this would be a helpful feature in Tadabase.