Prefilled form input fields fill then go blank

I am trying to prefill a form on one page which allows people to apply for a job. On the jobs dynamic page I am trying to read from a job seekers dataset to populate an applicants database.

When I use this code:
function fillform () {
$w( “#dbJobSeeker” ).onReady( () => {
var currentItem = $w( “#dbJobSeeker” ).getCurrentItem()
$w( “#txtFirstName” ).value = currentItem.firstName;
$w( “#txtLastName” ).value = currentItem.lastName;
$w( “#txtPhoneNumber” ).value = currentItem.phone;
$w( “#txtEmail” ).value = currentItem.email;
});
}

it works and the forms fills briefly and then all the input fields blank out. I have tried changing the various input field settings like changing from placeholder to none but it’s not working. Does this mean I will have to disconnect the fields from the applicants dataset and submit my form manually?

Hi, Erin :raised_hand_with_fingers_splayed:

You have couple of syntax issues (not errors), the dataset’s onReady() function needs to be inside the page’s onReady() function, and you don’t even need that function (Links are different).

You don’t need to disconnect anything, just tide up your code as followed and we’ll see if that solved the issue.

$w.onReady(async() => {    
    
     $w("#dbJobSeeker").onReady( () => {
        let item = $w("#dbJobSeeker").getCurrentItem();
        $w("#txtFirstName").value = item.firstName;
        $w("#txtLastName").value = item.lastName;
        $w("#txtPhoneNumber").value = item.phone;
        $w("#txtEmail").value = item.email;
     });
     
     $w("#dbJobSeeker").onBeforeSave(async() => {
        let item = $w("#dbJobs").getCurrentItem();
        
        await uploadFiles().then((result) => {
             if (typeof result !== 'boolean') {
                  $w("#dbApplicants").setFieldValues({
                       jobId: item._id,
                       firstName: $w("#txtFirstName").value,
                       lastName: $w("#txtLastName").value,
                       emailAddress: $w("#txtEmail").value,
                       phoneNumber: $w("#txtPhoneNumber").value,
                       profilePicture: result.items[0].url,
                       cvDoc: result.items[1].url,
                       coverDoc: result.items[2].url,
                       resumeUrl: $w('#uploadResume').value,
                       checkbox: $w('#notARobot').checked
                  }); 
             } else {
                  return false;
             }
        })       
     })
     
     $w("#dbJobSeeker").onAfterSave(() => {
          $w("#txtSuccess").show();
          $w('#txtFirstName').disable();
          $w('#txtLastName').disable();
          $w("#txtPhoneNumber").disable();
          $w("#txtEmail").disable();
          $w("#uploadProfilePic").disable();
          $w("#uploadCoverDoc").disable();
          $w("#uploadResume").disable();
          $w("#uploadCV").disable();
          $w("#notARobot").disable();
          $w("#btnSubmit").disable();   
     })
     
     $w('#btnSubmit').onClick((event) => {
          $w("#dbApplicants").save().then( (item) => {
               console.log(item);
          }).catch( (err) => {
               console.error(err);
               console.warn("Dataset operation save has failed!"); 
          });
     })
})

async function uploadFiles() {
 
   let fileUploaded = 0;
   let elements = [
        {id: "#uploadProfilePic", url: null},
        {id: "#uploadCV", url: null},
        {id: "#uploadCoverDoc", url: null},   
    ]

 for (let i = 0; i < elements.length; i++) {
      let elementId = elements[i].id;

      await $w(elementId).startUpload().then((uploadedFile) => {
            fileUploaded++
            elements[i].url = uploadedFile.url;
        }).catch((uploadError) => {
            console.error(uploadError.errorDescription, uploadError.errorCode);
           return false
        })
    }

       if (fileUploaded === elements.length) {
           return elements;
       } else {
           return false;
       } 
}

Please also take a look at onBeforeSave() and onAfterSave() functions and Dynamic dataset APIs.

Hope that helped~!
Ahmad

It sticks around for longer when I changed it but after about 5 seconds it seems like the page refreshes and the input fields all reset back to blank. I doubt it is any of my other code but here is all the code I have on the page just in case…

import wixData from ‘wix-data’ ;
import wixUsers from ‘wix-users’ ;

$w.onReady( async () => {
$w( “#dbJobSeeker” ).onReady( () => {
let item = $w( “#dbJobSeeker” ).getCurrentItem();
$w( “#txtFirstName” ).value = item.firstName;
$w( “#txtLastName” ).value = item.lastName;
$w( “#txtPhoneNumber” ).value = item.phone;
$w( “#txtEmail” ).value = item.email;
});
})

export function btnSubmit_click(event) {
$w( “#dbApplicants” ).setFieldValue( “jobId” ,$w( “#dbJobs” ).getCurrentItem()._id);
$w( ‘#dbApplicants’ ).save()
.then(() => {
$w( “#txtSuccess” ).show();
$w( ‘#txtFirstName’ ).disable();
$w( ‘#txtLastName’ ).disable();
$w( “#txtPhoneNumber” ).disable();
$w( “#txtEmail” ).disable();
$w( “#uploadProfilePic” ).disable();
$w( “#uploadCoverDoc” ).disable();
$w( “#uploadResume” ).disable();
$w( “#uploadCV” ).disable();
$w( “#notARobot” ).disable();
$w( “#btnSubmit” ).disable();
});
}

Hey, you’re setting the fields incorrectly as well, I’ll update my answer in a few minutes.

Answer updated.

Thanks for the help with setting the fields. However I tried inserting the new code and now the form input fields don’t fill at all even for a few seconds.

Can I do this maybe rather by directly querying the database instead of going through the dataset? It seems to be as if when the information from the dynamic page #dbJobs dataset loads all the information I am filling the form with from #dbJobSeeker disappears.

Remember that when you use onBeforeSave that it will do something before the save and then carry on with the save.

So, it will run your code and then do the save after the onBeforeSave, so when you come to click on the submit button here…

$w('#btnSubmit').onClick((event) => {
          $w('#dbApplicants').save();

… then you are just saving a new blank form again which will have blank inputs.

onBeforeSave( )
Adds an event handler that runs just before a save.

Description
The onBeforeSave() function allows you to optionally perform actions right before a save() operation. When you call save(), the callback is run before the save operation. Any validity checks on the data are run after the callback runs. If the callback function returns either false, a rejected Promise, or it throws an error, the save operation is canceled.

Examples

Register a callback to run before a save and continue with the save

$w("#myDataset").onBeforeSave( () => {
  console.log("Continuing save");
} );

Register a callback to run before a save and cancel the save

$w("#myDataset").onBeforeSave( () => {
  console.log("Canceling save");
  return false;
} );

A simple example is shown here.
https://www.vorbly.com/Vorbly-Code/WIX-CODE-AUTO-FILL-FORM-WITH-USER-INPUTS

I assumed that the button is not connected to the dataset because she left the save() function in her code.

If it is connected to a dataset as a submit button, yeah, it’ll save the changes again (if the dataset was set to R/W), and will create a blank entry if the dataset was set to Write only, I can’t really tell if she needs the save() function or not since I don’t know if the button is connected or not.

Ok so I’ll be honest right now this is just me throwing things at the wall to see what sticks because my client needed to see some results and I just needed a quick workaround for now.

The submit button isn’t connected so I am only using the save() function. The code Ahmad helped me with worked to populate the form and keep it populated, but when I saved it kept showing my catch error message, then I disconnected all the input fields from the dbApplications dataset and it gave me the success message and the fields disabled as they were meant to. There was a single submission but none of the ‘applications’ database fields had been populated with any information besides “jobId” and the boolean field so it wasn’t registering any of the text in the text fields.

This led me to write the code I’m using as my workaround for now which populates the database but I know it’s basically making the first onReady code redundant aside from simply showing people what will be inserted into the database. I also have upload file and image fields that I can’t find information on how to seFieldValue for if I continue to use this method.

import wixData from ‘wix-data’ ;
import wixUsers from ‘wix-users’ ;

$w.onReady( async () => {

 $w( "#dbJobSeeker" ).onReady( () => { 

let item = $w( “#dbJobSeeker” ).getCurrentItem();
$w( “#txtFirstName” ).value = item.firstName;
$w( “#txtLastName” ).value = item.lastName;
$w( “#txtPhoneNumber” ).value = item.phone;
$w( “#txtEmail” ).value = item.email;
});

 $w( "#dbApplicants" ).onBeforeSave(() => { 

let item = $w( “#dbJobs” ).getCurrentItem();
let fields = $w( ‘#dbJobSeeker’ ).getCurrentItem();
$w( “#dbApplicants” ).setFieldValue( “jobId” , item._id);
$w( “#dbApplicants” ).setFieldValue( “firstName” , fields.firstName);
$w( “#dbApplicants” ).setFieldValue( “lastName” , fields.lastName);
$w( “#dbApplicants” ).setFieldValue( “phoneNumber” , fields.phone);
$w( “#dbApplicants” ).setFieldValue( “emailAddress” , fields.email);
})

 $w( "#dbApplicants" ).onAfterSave(() => { 
      $w( "#txtSuccess" ).show(); 
      $w( '#txtFirstName' ).disable(); 
      $w( '#txtLastName' ).disable(); 
      $w( "#txtPhoneNumber" ).disable(); 
      $w( "#txtEmail" ).disable(); 
      $w( "#uploadProfilePic" ).disable(); 
      $w( "#uploadCoverDoc" ).disable(); 
      $w( "#uploadResume" ).disable(); 
      $w( "#uploadCV" ).disable(); 
      $w( "#notARobot" ).disable(); 
      $w( "#btnSubmit" ).disable();    
 }) 

 $w( '#btnSubmit' ).onClick((event) => { 
      $w( '#dbApplicants' ).save(); 
}) 
. **catch** ( (err) => { 

let errorMsg = err;
$w( “#error” ).show();
})
})

What happened in your case is that the dataset was responsible of collecting the other values from their respective fields, but when you disconnected them, the only value that was saved is the jobId because we used the onBeforeSave() function to set its value, what I recommend is reconnecting all the fields except the submit button, and everything will work as expected again, hopefully.

Alright I tweaked and tried a whole bunch of things until I got the majority of my code working. Now my only issue is that I have no experience submitting forms manually and I don’t know what to call my Image and Document field keys. I have tried value, startUpload & fileType but none of those work and I keep getting the database error “Value does not match field type Image/Document”

This is the last of the code I’m battling with:

let toSave = {
“firstName” : $w( “#txtFirstName” ).value,
“lastName” : $w( “#txtLastName” ).value,
“emailAddress” : $w( “#txtEmail” ).value,
“phoneNumber” : $w( “#txtPhoneNumber” ).value,
“profilePicture” : $w( ‘#uploadProfilePic’ ).startUpload(),
“cvDoc” : $w( ‘#uploadCV’ ).startUpload(),
“coverDoc” : $w( ‘#uploadCoverDoc’ ).fileType,
“resumeUrl” : $w( ‘#uploadResume’ ).value,
“checkbox” : $w( ‘#notARobot’ ).checked,
“jobId” : item._id,
};

Hey Erin, for upload buttons, use the value method which returns a list of files that are pending upload, then upload each file and get their URLs and set them as the field values.

I’ve added a function to my answer above that will upload the images, and reject the save if one of the saves failed, that way, you guarantee that all of them are uploaded.

I couldn’t get my save button working using the onaftersave functions inside of the main page onReady function.

This was the only way I could get my information to save to the database. Will I still be able to use your additional functions somehow?

import wixData from ‘wix-data’ ;
import wixUsers from ‘wix-users’ ;
import {sendEmail} from ‘backend/email’ ;

$w.onReady( async () => {
$w( “#dbJobSeeker” ).onReady( () => {
let item = $w( “#dbJobSeeker” ).getCurrentItem();
$w( “#txtFirstName” ).value = item.firstName;
$w( “#txtLastName” ).value = item.lastName;
$w( “#txtPhoneNumber” ).value = item.phone;
$w( “#txtEmail” ).value = item.email;
});

     $w( "#btnSubmit" ).onClick( () => { 
     $w( "#txtWait" ).show(); 
     $w( "#txtWait" ).expand(); 
  }); 

});

export function btnSubmit_click(event) {
let item = $w( “#dbJobs” ).getCurrentItem();
let toSave = {
“firstName” : $w( “#txtFirstName” ).value,
“lastName” : $w( “#txtLastName” ).value,
“emailAddress” : $w( “#txtEmail” ).value,
“phoneNumber” : $w( “#txtPhoneNumber” ).value,
“profilePicture” : $w( ‘#uploadProfilePic’ ).type,
“cvDoc” : $w( ‘#uploadCV’ ).type,
“coverDoc” : $w( ‘#uploadCoverDoc’ ).type,
“resumeUrl” : $w( ‘#uploadResume’ ).value,
“checkbox” : $w( ‘#notARobot’ ).checked,
“jobId” : item._id,
};
wixData.save( ‘Applications’ , toSave)
.then (() => {
afterSave();
})
. catch ( (err) => {
let errorMsg = err;
$w( “#error” ).show();
});
}

function afterSave () {
$w( “#txtSuccess” ).show();
$w( ‘#txtFirstName’ ).disable()
$w( ‘#txtLastName’ ).disable();
$w( “#txtPhoneNumber” ).disable();
$w( “#txtEmail” ).disable();
$w( “#uploadProfilePic” ).disable();
$w( “#uploadCoverDoc” ).disable();
$w( “#uploadResume” ).disable();
$w( “#uploadCV” ).disable();
$w( “#notARobot” ).disable();
$w( “#btnSubmit” ).disable();
}

Your code is all messed up! I can count at least 10 errors and mistakes, please take a look at my answer above and use the exact code, that answer was given specifically for your case, so it should work

Thanks so much for your help. There is one error showing up when I copied and pasted your code though, I get the Parsing error: cannot use the code ‘await’ outside an async function. Where should I add the async?

I’m sorry, because I wrote this code here, I didn’t notice that I’ve missed this error, I’ve corrected my answer, I forgot to change the onBeforeSave() function to an async one.

$w("#dbJobSeeker").onBeforeSave(async() => {

})

Just add the blue async there and you’ll be fine :wink:

With this code are all the input fields meant to be connected or disconnected from the dataset? I have the code now exactly as you have written it, the dataset is set to write-only, all the input fields are disconnected, and when I click the submit button it looks like the files are uploading but none of the information populates the database, and the onAfterSave functions don’t run.

Nothing is meant to be connected to the dataset, nothing at all, we have everything taken care of with code.

Okay well then I’m not sure what the problem is because nothing is connected to the dataset at all.

This is the error I’m getting back from the live site console:

bolt-worker.js:1 Uncaught (in promise)

  1. t

  2. code : " DS_OPERATION_CANCELLED "

  3. Symbol(error was handled) : true

  4. Symbol(error-boundary-scope) : " userCodeZone "

  5. message : " Operation cancelled by user code. TypeError: $w(…).startUpload is not a function "

  6. name : " DatasetError "

  7. stack : " DatasetError: Operation cancelled by user code. TypeError: $w(…).startUpload is not a function↵ at eval (https://static.parastorage.com/services/dbsm-viewer-app/1.1123.0/app.js:6:169032) "

  8. proto : t