Number not being written to CMS database | Unique Identifier Needed

Discussion:
Hi, This is my second thread on the same “unanswered” question. I need someone to show me how to correctly “code” passing a number with a submit button into the CMS database. I have rewritten my code into a simpler and more organized manner to reduce confusion.

(1) I call a function called getApplicationID, It reads a number out of the CMS database. It increments the number by 3.

It writes that number into a session ID that can be retrieved across multiple web pages.

(2) I have an export function SubmitT4_click submit button that performs the following tasks:

a. It validates #firstName and #lastName

b. It creates an object (objTb) this object is nested into (wix_data_obj) and it is sent to the backend (SubmitT4.jsw)

c. (wix_data_obj) has elements:
#firstName,
#lastName,
uniID (a number) | This number UniID is not going into the CMS database
(but #firstName and #lastName are going into the CMS database when submit is
clicked)???

**How do I pass a number (uniID) when I click submit??? Code example please :slight_smile: *

Product:
Wix Studio Editor with Dev Mode enabled

What are you trying to achieve:
Taking the session number after i increment it and use that as a new application ID and upload that into the database as a primary ID key for linking all new applicant data across multiple web pages and CMS database tables.

Additional information:
site: www.PrivateTacticalArmory.com
Page: T4

Front-end Code

import wixData from 'wix-data';
import { session } from 'wix-storage-frontend';
import { process } from 'backend/submitT4.jsw';

//Variables
const collectionAppID = "AppID";
const appIDKey = "bc5e76e2-6b5e-4099-8392-9ede9be72d34";
let appNumberInc = 3;
var newAppID = 0;

function getApplicationID (collectionAppID, appIDKey, appNumberInc){
    wixData.get(collectionAppID, appIDKey) //read base number from CMS
        .then((item) => {

            let newAppID = (item.appId + appNumberInc); //Increment by 3
            session.setItem("AppKey", newAppID); //Set session key with incremented value
            
            return newAppID
        })
}

export function SubmitT4_click(event) {
    //Validate and Send data to T4 DB
    if ($w('#firstName').valid &&
        $w('#lastName').valid) {

        //Create an object 
        let objTb = {
            //Token
            //token: $w('#captcha1').token,
            //nested wix-data obj
            wix_data_obj: {
                firstName: $w('#firstName').value,
                lastName: $w('#lastName').value,
                uniID: newAppID //Send number to CMS as part of the object
                // uniID: uniID: session.getItem("AppKey") //Doesn't work
                // uniID: newAppID //Send number to CMS as part of the object
                // uniID: session.getItem("AppKey")
                // uniId: session.getItem("AppKey").toString()
                // uniID: myNumber  //tried using let, const, var - nothing working?
            }
        };

        //Send object to the backend & receive response
        process(objTb)  
            .then((res) => {
                if (res.success) {
                    $w('#dbSuccessText').show();
                    //wixLocation.to(`${wixLocation.url}`); //refresh page if sucess
                }
            });
    } else {
        $w('#dbErrorText').show();
    }
}

$w.onReady(function () {
    //at page load call function for new application ID
        getApplicationID (collectionAppID, appIDKey, appNumberInc)
    
    //Get session value using key
        $w('#textNumber').text = session.getItem("AppKey"); //Text display
        console.log(session.getItem("AppKey"));
});

Back-end Code (SubmitT4.jsw)

//import wixCaptchaBackend from 'wix-captcha-backend';
import wixData from 'wix-data';

export function processT1(objTb) {
    // Authorize token and insert data
    //return wixCaptchaBackend.authorize(objTb)
        //.then(() => {
            return wixData.insert("T4", objTb.wix_data_obj)
                .then(() => ({ success: true }))
                .catch((error) => ({ success: false }));
        //})
        //.catch((error) => ({ success: false }));
}

Screenshots


T4_WebPage

Well I can’t see any issue with the code but I do believe this might be a logical error rather than a syntax error.

You are fetching the current application id from the DB and then incrementing it by 3.

But on looking at the screenshot you’ve provided, the uniID field appears to be blank :smiley:

So when you’re using code to fetch it for the first time, its probably fetching the uniID as undefined or null and when you do null + 3 it results in a NaN (Non assigned Number) and maybe that is the reason behind the issue. Try adding a 0 in the field and then give it a go, and if it still does not work, try replacing your frontend code with the one I’ve provided below:

import wixData from 'wix-data';
import { session } from 'wix-storage-frontend';
import { process } from 'backend/submitT4.jsw';

//Variables
const collectionAppID = "AppID";
const appIDKey = "bc5e76e2-6b5e-4099-8392-9ede9be72d34";
let appNumberInc = 3;
var newAppID = 0;

function getApplicationID(collectionAppID, appIDKey, appNumberInc) {
    wixData.get(collectionAppID, appIDKey) //read base number from CMS
        .then((item) => {

            if (item.appId) {
                newAppID = (item.appId + appNumberInc); //Increment by 3 after fetching
                session.setItem("AppKey", newAppID); //Set session key with incremented value
            } else {
                newAppID = appNumberInc; // if app id undefined or zero, then set app id as 3
                session.setItem("AppKey", newAppID); //Set session key with incremented value
            }

        })
}

export function SubmitT4_click(event) {
    //Validate and Send data to T4 DB
    if ($w('#firstName').valid &&
        $w('#lastName').valid) {

        //Create an object 
        let objTb = {
            //Token
            //token: $w('#captcha1').token,
            //nested wix-data obj
            wix_data_obj: {
                firstName: $w('#firstName').value,
                lastName: $w('#lastName').value,
                uniID: newAppID //Send number to CMS as part of the object
                // uniID: uniID: session.getItem("AppKey") //Doesn't work
                // uniID: newAppID //Send number to CMS as part of the object
                // uniID: session.getItem("AppKey")
                // uniId: session.getItem("AppKey").toString()
                // uniID: myNumber  //tried using let, const, var - nothing working?
            }
        };

        //Send object to the backend & receive response
        process(objTb)
            .then((res) => {
                if (res.success) {
                    $w('#dbSuccessText').show();
                    //wixLocation.to(`${wixLocation.url}`); //refresh page if sucess
                }
            });
    } else {
        $w('#dbErrorText').show();
    }
}

$w.onReady(function () {
    //at page load call function for new application ID
    getApplicationID(collectionAppID, appIDKey, appNumberInc)

    //Get session value using key
    $w('#textNumber').text = session.getItem("AppKey"); //Text display
    console.log(session.getItem("AppKey"));
});

Hi Pratham, thank you for your comments. I have looked at your example and I think you need more information. Please look at the screenshot of an additional CMS database, you will see it holds my starting number (I have two CMS databases AppID and T4, I am reading from AppID which works and I am trying to write the number I increment into CMS T4 database uniID field, which is not working).

The reason uniID is blank, is because I am unable to write a simple number into the CMS database table T4. This should be simple, but I am coming up on almost 2 weeks and no real answers or solutions, based on my reading, WIX does not unsupported taking a number and updating a database with the value (which is shocking to me)?

References

  • This value will always be of type string, regardless of the text input’s inputType (i.e number).
  • The value returned by the value property of a text input is always a string, regardless of the type set in the Editor. L OK I choose not to use a page element, how do I write an “anything” string into the CMS database “apart from using page elements”?

How do I workaround this WIX limitation? (Thanks to Simen for trying to help J)

  • Wix suggest I use setFieldValue() but it has problems!
  • So if you call setFieldValue() inside the page’s onReady() event handler, the dataset might not be ready yet. Sounds like the solution/workaround is unreliable.
  • To call setFieldValue() as soon as possible after a page loads, use the dataset’s onReady() function inside the page’s onReady() event handler to ensure that both the page and the dataset have finished loading. This really needs more explanation and examples than the limited API doc offers.
  • This solution requires the use of a page element.

conclusions
After almost two weeks of very little support on WIX, I really feel WIX has been a huge waste of my time and money. The Dev community seems very weak. WIX’s is unable to perform a very simple operation “set a value in the database apart from a page element” from a number I assign automatically during form creation. WIX CMS database is missing critical unique key identifier to link relational databases together. If someone at WIX knows how to do this show me please before I dump the site and go elsewhere. Thanks


$w.onReady(function () {
    //at page load call function for new application ID
    getApplicationID(collectionAppID, appIDKey, appNumberInc)

    //Get session value using key
    $w('#textNumber').text = session.getItem("AppKey"); //Text display
    console.log(session.getItem("AppKey"));

    // setFieldValue did not work... 
    //$w("#dataset1").onReady(() => {
    //$w("#dataset1").setFieldValue("uniID", newAppID);
    //$w("#dataset1").save();
    //});
});

I tried to replicate the exact scenario, and upon making a few modifications to the code, it seems to work like a charm for me.

FRONTEND CODE:

import wixData from 'wix-data';
import { session } from 'wix-storage-frontend';
import { addtoDB } from 'backend/submitT4.jsw';

//Variables
const collectionAppID = "AppID";
const appIDKey = "bc5e76e2-6b5e-4099-8392-9ede9be72d34";
var appNumberInc = 3;
var newAppID = 0;

function getApplicationID(collectionAppID, appIDKey, appNumberInc) {
    wixData.get(collectionAppID, appIDKey) //read base number from CMS
        .then((item) => {

            newAppID = (item.appId + appNumberInc); //Increment by 3
            //$w('#new').text = newAppID.toString();
            session.setItem("AppKey", newAppID); //Set session key with incremented value
        })
}

export function SubmitT4_click(event) {
    //Validate and Send data to T4 DB
    if ($w('#firstName').valid &&
        $w('#lastName').valid) {

        //Create an object 
        let objTb = {
            //Token
            //token: $w('#captcha1').token,
            //nested wix-data obj
            //wix_data_obj: {
            title: "TEST",
            firstName: $w('#firstName').value,
            lastName: $w('#lastName').value,
            uniID: newAppID //Send number to CMS as part of the object
            // uniID: uniID: session.getItem("AppKey") //Doesn't work
            // uniID: newAppID //Send number to CMS as part of the object
            // uniID: session.getItem("AppKey")
            // uniId: session.getItem("AppKey").toString()
            // uniID: myNumber  //tried using let, const, var - nothing working?
            //}
        };

        //Send object to the backend & receive response
        var res = addtoDB(objTb);

        console.log(res);

        $w('#dbErrorText').hide();
        $w('#dbSuccessText').show();

        /*
            .then((res) => {
                if (res.success) {
                    //$w('#dbSuccessText').show();
                    //wixLocation.to(`${wixLocation.url}`); //refresh page if sucess
                }
            });
			*/
    } else {
        $w('#dbErrorText').show();
    }
}

$w.onReady(function () {
    //at page load call function for new application ID
    //session.setItem("AppKey", "429460");
    getApplicationID(collectionAppID, appIDKey, appNumberInc)

    //Get session value using key
    $w('#textNumber').text = session.getItem("AppKey"); //Text display
    console.log(session.getItem("AppKey"));
});

BACKEND CODE:

//import wixCaptchaBackend from 'wix-captcha-backend';
import wixData from 'wix-data';

export function addtoDB(objTb) {
    // Authorize token and insert data
    //return wixCaptchaBackend.authorize(objTb)
    //.then(() => {
    //return wixData.insert("T4", objTb.wix_data_obj)
    wixData.insert("T4", objTb)
        .then((item) => {
            return "SUCCESS";
        });
/*
        .catch((err) => {
            return "ERROR";
        });
*/
    //.then(() => ({ success: true }))
    //.catch((error) => ({ success: false }));
    //})
    //.catch((error) => ({ success: false }));
}

Hi Pratham, thank you for your time and work on this, I do appreciate it, i will use it in the short term until I can move off of WIX.

Here are my comments as an application engineer, your solution works, but also creates technical debt which is overall a negative out-come. When a user submit’s data it should only create a single record entry, your solution creates two entries for every submit action.

This means 50% of the data in the database is unwanted, as in my case I only need one record with a uniID. The solution gives two entries, one with a uniID and another record with the uniID absent (which was my original problem and frustration).

I did go back and review your code, I made multiple changes to try and only get the code to create a single record entry, but what I discovered is the CMS database is very fragile and is easily broken.

The choice I see, use a database where 50% of the data will become waste and apply filters to remove the technical debt from my view and work with the data for the short term. But overall since the CMS database isn’t reliable and the coding is not clean (meaning free of technical debt) this means WIX is not a long term solution.

If you come up with a mean’s of entering data in my mock example where it only creates a single record in the CMS database let me know and I might stay with WIX, but as things look now… this is not desirable as a long term solution.

Thank you again for your help and the examples. Have a great day.


Hi there.

The code that I’ve provided and tested does not create any duplicate entries like the one you’ve mentioned. If it was a buggy code, I wouldn’t have provided it here. It tends to work perfectly well on the test site I had created.

So there’s nothing that possibly needs to be edited in the code that I’ve provided, but if you share your code snippet, I might be able to do some debugging in that.

It might be that the submit button is connected to a dataset and both the events are firing simultaneously, resulting in multiple duplicate entries. Make sure to delete any datasets or connections with the CMS from the editor itself.

Thank you Pratham, I understand now. I thought the Submit button had to be connected to the CMS database. :slight_smile: Yes your code works correctly. I think I can get this function correctly now. Greatly appreciate your time and help. :slight_smile:

1 Like