Happy New Year folks,
I modified the Page Code provided here (https://support.wix.com/en/article/wix-code-tutorial-sending-an-email-on-form-submission) with an onBeforeSave that checks if the email address being inputted in the form already exists in the Users collection.
The console shows that the onBeforeSave is correctly identifying duplicate emails, but somehow the 'return false;' is not cancelling the save and the items are still being copied the "#dataset2" Collection, which in turns calls the onAfterSave that sends the SendGrid email.
How do I cancel the save when the email is deemed to be a duplicate?
One small additional problem is that '$w('#errorText').show();' is consolled as 'Unreacheable code' and the error message does not show.
Here is the onReady code I wrote:
$w.onReady(function () {
//check existing members to stop referral if email is already signed up in "Users" $w("#dataset2").onBeforeSave( () => {
//create variable to compare query results with the value of the input field let emailcheck = $w('#iReferral').value; console.log(emailcheck);
//run data query in "Users" collection to find possible duplicate wixData.query("Users") .eq("email", emailcheck) .find() .then((results) => { let items = results.items; console.log(items); if (results.length > 0) {
//email is not unique. show error and stop the save function console.log("Cancelling save"); return false;
//show message to alert user that email they are referring is already signed up $w('#errorText').show(); } }).catch((err) => { let errorMsg = err; }); } ); //if save is successful send the SendGrid email accordingly
$w("#dataset2").onAfterSave(sendFormData); });
"#dataset2" = the collection into which the page form sends data
"#iReferral" = the input field into which users type new email addresses
"#errorText" = the text string to appear if 'save' is cancelled
Here is the Page Code for the onClick, which eventually worked fully....
export function sendButton_click(event) { let emailToCheck = $w('#iReferral').value; checkDuplicateEmail(emailToCheck) .then (results => { if (results === "NOTHING") { let toInsert = { "referredEmail": $w('#iReferral').value }; wixData.save("Referrals", toInsert) .catch((err) => { let errorMsg = err; console.log(errorMsg); }) $w('#errorText').hide(); $w('#successText').show(); sendFormData(); } else { $w('#errorText').show(); $w('#successText').hide(); } }) }
I solved the original request and now the script properly checks for duplicate emails and saves new data to the collection when necessary.
It turns out that the way I was writing the 'toInsert' variable was not a Javascript object and it therefore could not be saved to the collection. I changed it from
let toInsert = $w('#iReferral').value;
to
let toInsert = { "referredEmail": $w('#iReferral').value };
and voila!
Unfortunately, however, now the sendGrid email is no longer sent after the value is added to the Collection on save().
upon investigation, I found that the onAfterSave() is listed under wix-dataset, which in turn has a save() function that looks like this
$w("#myDataset").save() .then( (item) => { let fieldValue = item.fieldName; } ) .catch( (err) => { let errMsg = err; } );
whilest I used the save() function under wix-data that looks like this
wixData.save("myCollection", toSave) .then( (results) => { let item = results; //see item below } ) .catch( (err) => { let errorMsg = err; } );
Is this the reason why the onAfterSave is not sending the sendGrid email?
If so, how do I trigger it?
I extracted the code to demonstrate that I was importing the web module correctly, that page includes additional code for other functionalities and it includes several other 'import', including wixData.
I don't know it is useful, but here is the whole page:
import {sendEmail, sendEmailWithRecipient} from 'backend/email'; import {checkDuplicateEmail} from 'backend/referral'; import wixUsers from 'wix-users'; import wixData from 'wix-data'; import wixLocation from 'wix-location'; let picture; let url; let filename; function sendFormData() { //create email subject string with name of logged in member const subject = `${$w("#text53").text} bla bla bla`; console.log("email subject" + " " + subject); //create email body including name and email of logged in member const body = ` <p><font size="3" face="Arial">bla bla bla,</p> <p>bla bla bla</p> <p>bla bla bla</p> <p> bla bla bla</p> <p>bla bla bla</p></font>`; console.log("email body" + " " + body); //set the email recepient as the input field value const recipient = $w("#iReferral").value; console.log("email recepient" + " " + recipient); //executes the SendGrid function to send email sendEmailWithRecipient(subject, body, recipient) .then(response => console.log(response)); } $w.onReady(function () { /* //this is the old onBeforeSave function that was not woring //check existing members to stop referral if email is already signed up in "Users" $w("#dataset2").onBeforeSave( () => { //create variable to compare query results with the value of the input field let emailcheck = $w('#iReferral').value; console.log("03 - Checking email uniqueness" + " " + emailcheck); //run data query in "Users" collection to find possible duplicate wixData.query("Users") .eq("email", emailcheck) .find() .then((results) => { let items = results.items; console.log(items); if (results.length > 0) { //id is not unique. show error and stop the save function console.log("03a - Cancelling save"); return false; //show message to alert user that email they are referring is already signed up $w('#errorText').show(); } }).catch((err) => { let errorMsg = err; }); } ); */ //if save is successful send the SendGrid email accordingly $w("#dataset2").onAfterSave(sendFormData); //get logged in user name and email to add to the SendGrid body $w("#dataset3").onReady( () => { if(wixUsers.currentUser.loggedIn) { let name = $w('#dataset3').getCurrentItem().firstName; console.log("01 - On ready getting name of logged in user"); console.log("01a" + name); $w('#text53').text = name; let email = $w('#dataset3').getCurrentItem().email; console.log("02 - On ready getting email of logged in user"); console.log("02a" + email); $w('#text54').text = email; } }) //create social share link for each of the images on the page let link = "https://www.essence-rooms.com/referralsignup"; $w("#twitterShare").link = `https://twitter.com/share?url=${link}`; $w("#facebookShare").link = `https://www.facebook.com/sharer/sharer.php?u=${link}`; $w("#mailShare").link = `mailto:?subject=blablabla`; $w("#whatsappShare").link = `https://api.whatsapp.com/send?phone=&text={link}`; $w("#googleShare").link = `https://plus.google.com/share?url=${link}`; $w("#linkedinShare").link = `https://www.linkedin.com/sharing/share-offsite/?url=${link}`; $w("#redditShare").link = `http://www.reddit.com/submit?url=${link}`; $w("#messengerShare").link = `https://www.facebook.com/dialog/send?link=${link}&app_id=1234&redirect_uri=https%3A%2F%2Fwww.babla.coml`; }); export function twitterShare_click(event) { $w("#twitterShare").target = "_blank"; } export function facebookShare_click(event) { $w("#facebookShare").target = "_blank"; } export function mailShare_click(event) { $w("#mailShare").target = "_blank"; } export function whatsappShare_click(event) { $w("#whatsappShare").target = "_blank"; } export function googleShare_click(event) { $w("#googleShare").target = "_blank"; } export function linkedinShare_click(event) { $w("#linkedinShare").target = "_blank"; } export function redditShare_click(event) { $w("#redditShare").target = "_blank"; } export function messengerShare_click(event) { $w("#messengerShare").target = "_blank"; } export function sendButton_click(event) { let emailToCheck = $w('#iReferral').value; checkDuplicateEmail(emailToCheck) .then (results => { if (results === "NORESULTS") { let toInsert = $w('#iReferral').value; wixData.save("Referrals", toInsert) .then ((results) => { let item = results; }) .catch((err) => { let errorMsg = err; }) } else { console.log("This is a duplicate email and cannot be added"); $w('#errorText').show(); } }) }
I don´t see an import of Wix Data in Page Code, like:
import wixData from 'wix-data';
Hello Giri, thank you for the suggestion. I tried and experiencing a similar problem and given my limited coded experience I can't figure our where I am going wrong.
Here is the .jsw webmodule code:
// Filename: backend/referral.jsw (web modules need to have a .jsw extension) import wixData from 'wix-data'; export function checkDuplicateEmail (duplicateEmail) { return wixData.query("Users") .eq("email", duplicateEmail) .limit(1000) .find() .then((results) => { if (results.totalCount > 0) { return results.items; } else { return "NORESULTS" } }); }
This seems to correctly return results.
On the Page Code, I tried two things. First I left the Submit button connected to the dataset and imported the webmodule in the onReady. This did not seem to work at all, with the webmodule seemingly not being called at all.
Then I removed the button connection to the dataset, and I instead wrote an onClick function for it. Here is the code:
import {checkDuplicateEmail} from 'backend/referral'; export function sendButton_click(event) { let emailToCheck = $w('#iReferral').value; checkDuplicateEmail(emailToCheck) .then (results => { if (results === "NORESULTS") { let toInsert = $w('#iReferral').value; wixData.save("Referrals", toInsert) .then ((results) => { let item = results; }) .catch((err) => { let errorMsg = err; }) } else { console.log("This is a duplicate email and cannot be added"); $w('#errorText').show(); } }) }
In this case, the script works as expected if there is a duplicate email. However, if the email is new nothing happens when I click the button. I tried also by changing the line wixData.save("Referrals", toInsert) to wixData.insert"Referrals", toInsert), but still, nothing happens.
Oberdan, I THINK (have not tried it), that you are placing the logic in the wrong spot. Once you do a .save(), you can do all kind of pre-processing, but you cannot back out of the .save() itself.
Why don´t you try this (assuming you have a standard button that does a .save())
1) write a front- or backend function that does the checking for an existing email address
2) if that function returns true (email exists), .show() the error text
3) if not, do a .save()