How to create database entries when a user sign up ?

Hello guys !

When I used the basic/native sign up form from Wix (email + password only), I added a little piece of code which created automatic entries like user ID and email in my “MemberProfile” database.

Now, I’m using a custom registration form on a lightbox with fisrt name, last name, email and password. When a user sign up, a new contact is created in my contact list but I need, like in the past, to auto-create a new entry in my “MemberProfile” database. The point is, my old code, the one for the native Wix sign up form, doesn’t works on my lightbox. Any solution for me ?

If that can help, here is (one of !) the code I tried but doesn’t work :

import wixUsers from ‘wix-users’;
import wixWindow from ‘wix-window’;
import wixLocation from ‘wix-location’;
import wixData from ‘wix-data’;

$w.onReady( function () {

let user = wixUsers.currentUser;
let userId = user.id;

$w("#registerButton").onClick( (event) => { 

let email = $w(“#email”).value;
let password = $w(“#password”).value;
let first = $w(“#firstName”).value;
let last = $w(“#lastName”).value;

wixUsers.register(email, password, {
contactInfo: {
“firstName”: $w(‘#firstName’).value,
“lastName”: $w(‘#lastName’).value,
}
} )

  .then( () => { 

let toInsert = {
“prenom”: $w(“#firstName”).value,
“nom”: $w(“#lastName”).value,
“email”: $w(“#email”).value,
};
wixData.insert(“MemberProfile”, toInsert)
. catch ( (err) => {
console.log(err);
wixLocation.to(/MemberProfile/Update/${wixUsers.currentUser.id});
} );

} );      
} ); 

});

I use my own custom login and signup lightboxes too and this works perfectly for me and closes after registering details before moving users onto my signup status page, then both names will be saved in Contacts and once site member is manually approved the member details will be added to my own ‘members’ database.

You can simply set you signup form like this.

import wixUsers from 'wix-users';
import wixWindow from 'wix-window';
import wixLocation from 'wix-location';

$w.onReady(function () {
    
    $w("#registerButton").onClick( (event) => {
        
   let email = $w("#email").value;
   let password = $w("#password").value;
   let first = $w("#firstName").value;
   let last = $w("#lastName").value;

   wixUsers.register(email, password, {
       contactInfo: {
        "firstName": $w('#firstName').value,
        "lastName": $w('#lastName').value,
       }
      } )
      .then( (result) => {
        let resultStatus = result.status;
  wixWindow.lightbox.close();
  wixLocation.to("/sign-in-status");  //Change the URL ending to whatever page you want to send the user to after they log in.
      } );     
    } );
    
});

Then on my own Members only page I have used the Wix tutorial for members profile as a base for my code and worked from it so that the member can choose whatever page they go to from this page instead of simply going straight to the member profile update page.
https://support.wix.com/en/article/corvid-tutorial-building-your-own-members-area

import wixUsers from 'wix-users';
import wixData from 'wix-data';
import wixLocation from 'wix-location';

$w.onReady( () => {
if(wixUsers.currentUser.loggedIn) {
$w("#loginbutton").label = "Logout";
$w("#membersareaonlystrip").expand();
$w("#whitegapforfooter").hide();

}
else {
$w("#loginbutton").label = "Login";
$w("#membersareaonlystrip").collapse();
$w("#whitegapforfooter ").show();

}
} );

export function loginbutton_onclick(event) { 
// user is logged in
if(wixUsers.currentUser.loggedIn) {
// log the user out
wixUsers.logout()
.then( () => {
// update buttons accordingly
$w("#loginbutton").label = "Login";
  $w("#membersareaonlystrip").collapse();
  $w("#whitegapforfooter ").show();
  
} );
}
// user is logged out
else {
let userId;
let userEmail;

// prompt the user to log in 
wixUsers.promptLogin( {"mode": "signup"} )
.then( (user) => {

userId = user.id;
return user.getEmail();
} )
.then( (email) => {
// check if there is an item for the user in the collection
userEmail = email;
return wixData.query("Members")
.eq("_id", userId)
.find();
} )
.then( (results) => {
// if an item for the user is not found
if (results.items.length === 0) {
// create an item
const toInsert = {
"_id": userId,
"email": userEmail
};
// add the item to the collection
wixData.insert("Members", toInsert)
.catch( (err) => {
console.log(err);
} );
}
// update buttons accordingly
 $w("#loginbutton").label = "Logout";
 $w("#membersareaonlystrip").expand();
$w("#whitegapforfooter").hide();

} )
.catch( (err) => {
console.log(err);
} );
}
}

export function profilebutton_onclick(event) {
wixLocation.to(`/Members/${wixUsers.currentUser.id}`); 
}

export function entermembersbutton_onclick(event) {
wixLocation.to(`/members-area`); 
}

export function myaccountbutton_onclick(event) {
wixLocation.to(`/account/my-account`); 
}

export function websiteupdatebutton_onclick(event) {
wixLocation.to(`/website-update`); 
}

The login button is only found on my members only page and when users log themselves in the login lightbox automatically closes and refreshes my members only page so that the code for this page is kick started.

import wixUsers from 'wix-users';
import wixLocation from 'wix-location';
import wixWindow from 'wix-window';

$w.onReady(function () {
 $w("#forgotPassword").onClick( (event) => {
    //wixWindow.lightbox.close()
   wixUsers.promptForgotPassword()
   .then( ( ) => {
   //
   } )
    .catch( (err) => {
    let errorMsg = err;  //"The user closed the forgot password dialog"
    });
 });
});

export function loginButton_onclick(event) {

 let email = $w("#email").value;
 let password = $w("#password").value;

 wixUsers.login(email, password)
   .then( () => {
     console.log("User is logged in");
     wixWindow.lightbox.close();
     wixLocation.to(wixLocation.url);  //This reloads the same page and allows code to show hidden member parts.
   } )
    .catch( (err) => {
     console.log(err);
     $w("#errorMessage").expand();  // You can delete this line if you are not going to add an error message.  Use a regular text element set to 'collapse on load' from the Properties Panel.
   } ); 
}

One thing you can ( and should probably do) is save the ID returned in the RegistrationResult User record and use this as the _id value in any record you save locally. Why? Well this is the id that is used by both wix.crm.emailContact and wix.users.emailUser APIs to send triggered email. The benefit of doing this in addition is that you can use wix.crm-backend.getContactById() to get the contact data stored in the CRM and update the contact info using updateContact.

For example your code could look like this:

wixUsers.register(email, password, {
        contactInfo: {  
            "firstName": $w('#firstName').value,
            "lastName": $w('#lastName').value,
        }
})
.then( (registrationResult) => {
        let toInsert = {
            "prenom": $w("#firstName").value,
            "nom": $w("#lastName").value,
            "email": $w("#email").value,
        }; 
        // Make sure we have a valid object to access
        let userId = registrationResult && registrationResult.user ? registrationResult.user.id : null;
        if (userId) {
            // We have a user Id so use it
            toInsert._id = userId;
        }
        // NOTE: This is returned and the catch is moved outside the register .then(). This means ANY error will be caught
        return wixData.insert("MemberProfile", toInsert) ; 
        // NOTE: insert MAY fail if there is a conflicting record. You should try a GET first and THEN insert if the GET fails. This is easier to implement if you use the _id as described above
})
.catch( (err) => {               
        console.log(err);
        return wixLocation.to(`/MemberProfile/Update/${wixUsers.currentUser.id}`);
} );  

Cheers

1 Like

Thanks Steve, I will keep a note of that myself too.

Plus, is this forum ever going to be sorted so that it doesn’t duplicate a code entry :wink:

1 Like

Hi guys ! Thanks for all your support !
To be honest, I’m a the level zero of coding and I don’t understand all your explanations at the moment but, I try to ! :stuck_out_tongue:
In fact, I realized that the code I posted at the top works ! Infos are now appearing in my database by when a new user register BUT he is not redirected to wixLocation.to (/MemberProfile/Update/${ [wixUsers.currentUser.id](http://wixusers.currentuser.id/) }).

It stays on my lightbox and nothing happened.
And if I close manually the lightbox and open the login lightbox the try to access to the MemberProfile/Update, it has an error as if the MemberProfileUpdate page doesn’t exist even if I see the new user field in my database. Any idea why ?

[@angelinesirba] The reason is that your wixLocation.to() is called from the .catch(). This is at executed on an error. You need to add a .then() above the catch() and call it there instead! :slight_smile:

Hello guys !

SO ! I picked some pieces code of both yours and mine here and there and after 100000 tests it finally works ! BUT now (another “but” :), I can’t manage to redirect to
wixLocation.to(/MemberProfile/Update/${wixUsers.currentUser.id}) because, as I’m NOT a coder, so I think I put this line at the wrong place. Take a look at those screenshots, none of them worked.

By the way, here is the complete code that is perfectly working (hell yeah !) but WITHOUT REDIRECTION :

import wixUsers from ‘wix-users’;
import wixLocation from ‘wix-location’;
import wixData from ‘wix-data’;
import wixWindow from ‘wix-window’;

$w.onReady( function () {

$w("#registerButton").onClick( (event) => { 

let email = $w(“#email”).value;
let password = $w(“#password”).value;
let first = $w(“#firstName”).value;
let last = $w(“#lastName”).value;

wixUsers.register(email, password, {
contactInfo: {
“firstName”: $w(‘#firstName’).value,
“lastName”: $w(‘#lastName’).value,
}

  } ) 

let userId;
let userEmail;

// prompt the user to log in
wixUsers.promptLogin( {“mode”: “signup”} )
.then( (user) => {

userId = user.id;
return user.getEmail();
} )
.then( (email) => {
// check if there is an item for the user in the collection
userEmail = email;
return wixData.query(“MemberProfile”)
.eq(“_id”, userId)
.find();
} )
.then( (results) => {
// if an item for the user is not found
if (results.items.length === 0) {
// create an item
const toInsert = {
“_id”: userId,
“email”: userEmail,
“prenom”: $w(“#firstName”).value,
“nom”: $w(“#lastName”).value,
};
// add the item to the collection
wixData.insert(“MemberProfile”, toInsert)
. catch ( (err) => {
console.log(err);
} );
}
} )
}
);
});