Wix CRM In Wix Code Not Saving In Custom Fields

I have setup a ‘join us’ form on a website and have used the following code below to save the form details into a database and then to create a new contact and add the same custom fields into the new contact details.

The database fields are being filled in and a new contact is created, however the custom fields in the new contact is not being filled in with anything and it doesn’t send out an email in return to the new contact as per the code should do.

The fields used are as listed below as this 'Wix CRM Custom Field Name / Form Input Value:
First Name / firstName
Last Name / lastName
Email / email
Choir Role / choirRole
Read Music / readMusic
Choir Before / choirBefore
Start Now / startNow
Start Date / startDate

import wixCRM from 'wix-crm';
$w.onReady(function () {
$w("#JoinUsForm").onAfterSave( () => {
wixCRM.createContact({
"firstName": $w('#firstName').value,
"lastName": $w('#lastName').value,
"emails": [$w("#email").value],
"Choir Role": $w("#choirRole").value,
"Read Music": $w("#readMusic").value,
"Choir Before": $w("#choirBefore").value,
"Start Now": $w("#startNow").value,
"Start Date": $w("#startDate").value
})
.then((contactId) => {
wixCRM.emailContact(' joiningusform', contactId, {
"variables": {
"firstName": $w('#firstName').value,
 "lastName": $w('#lastName').value,
"emails": [$w("#email").value],
"Choir Role": $w("#choirRole").value
"Read Music": $w("#readMusic").value,
"Choir Before": $w("#choirBefore").value,
"Start Now": $w("#startNow").value,
"Start Date": $w("#startDate").value,
}
})
.then(() => {
// do something after the email was sent
})
.catch((err) => {
// handle the error if the email wasn't sent
} );
}
});
});
export function registerButton_onclick(event) {
$w("#JoinUsForm").save()
}

I have viewed this Wix Code tutorial page and went through both sending a triggered email for new contacts and members wix code and it does not work even with following the guide.
Wix Code Tutorial Link

I have also looked at this Wix Code Forum post about using custom fields in contacts and it states that '- custom fields “keys” should be exactly as written in CRM app (i.e. case sensitive and with whitespaces if required). ’
Forum Post Link

Therefore my custom field in contacts of Choir Role should be Choir Role in the code and not choirRole as I would have assumed before., however after changing it to the code above, it still does not want to save anything in the custom fields.

As the code seems to not work for the sending email, I have setup two Wix Automations that trigger when the form is submitted.

One Automation is an email back to the form filler, whilst the other Automation is an email back to myself informing me that a form has been submitted.

However, on both emails the date field is shown as ‘Tue Jan 29 2019 00:00:00 GMT+0000 (Greenwich Mean Time)’, when I just want it to be displayed as ‘Tue Jan 29 2019’

If I use Wix Forms to make up the exact same form and use the select date picker from there, then the email fields are displayed correctly as ‘Tue Jan 29 2019’. But I’m not using Wix Forms and be limited to only five forms in free option or pay each month just for being able to use Automations with it and have unlimited forms when we can do exactly the same thing in Wix Code for free!

So is there a way that we can change the fields in both email replies to show just the ‘Date Only’ option?

Wix Support have already replied and stated that I can try putting the Date and Time field as text, however when doing this the date picker on the form itself will not let me link the database to that field as it is now not Date and Time!

Only way to alter it so far by their theory is to do it manually and that defeats the object of having the triggered email after the form is filled in!

[@givemeawhisky] Is anything showing up in the CRM?

Have you seen any errors show up in the wix developer console or the browser console?

What is the url of the page you are having the problem with?

Cheers
Steve

Hi Steve and thanks for your reply back.

Firstly here is the webpage link - I have hidden it from my menu again as it doesn’t work.

The ‘JoinUsForm’ dataset is getting filled correctly, however it then does not add any of the other values into the custom fields in the contact list, neither does it send out an email too.

There was a error in the code I have pasted above, it should have had the comma added to one line and taken off another in the emailContact section:

"Choir Role": $w("#choirRole").value, 
"Start Date": $w("#startDate").value

That was my fault as I missed it when I was moving the code lines to match the createContact section.

As for errors I have just had a quick look at it through editor preview and it doesn’t show any errors, although I have now just seen an error in line 36 of the code which shows the red dot error next to it.

The red dot states ‘Parsing Error: Unexpected Token }’ and I have also highlighted the offending symbol as shown in the code too.

   .catch((err) => {
 // handle the error if the email wasn't sent
       } );
    }
  });   It is the } in this line that is marked as the error  
});
export function registerButton_onclick(event) {
  $w("#JoinUsForm").save()
}

Otherwise I do not get any errors when testing the form in preview and the same when filling the form in on the published website.

Both forms get sent with successful message coming up and the dataset fields all get filled in correctly, however nothing gets filled into any of the custom contact fields.

So do I have to go back to the Wix Forum post that I linked and do what they suggested on there and put the custom fields as “customField” in the wix-crm API.

As I am doing exactly what the Wix Mod, Tom mentioned on that fourm post to do ‘custom fields “keys” should be exactly as written in CRM app (i.e. case sensitive and with whitespaces if required).’

It seemed to have worked for Steve, the person who put the post up originally and he states ‘Thanks I have tried this and it seems to be working.’

Also, all my custom fields in contact list are text fields apart from the start date which is set as date, although I can only have date and time in the dataset field, so I have to put up with that field being filled in as this ‘Tue Jan 07 2020 00:00:00 GMT+0000 (Greenwich Mean Time)’, instead of just being ‘Tue Jan 07 2020’.

Something I can’t change according to Wix Support unless I do it manually and then send out an email, or I use Wix Forms as the date picker in there does just give me the date itself. If I was displaying info from the dataset on my website then I would be able to shorten the date with code, but I can’t do it in this code, unfortunately.

Thanks for trying to help and if it can be sorted by changing that one symbol in the code, then that would be great, although is anything that easy nowadays!

@givemeawhisky Hey there. I have had a look at your site (Wix Employees have special Admin access). Here is what I found:

  1. Your code was formatted incorrectly (as you mentioned). You need to use the scope lines to try to make sure that the ( ) and {} pairs when nested are matched and you aren’t missing any.

  2. You are using both Ascend forms and triggered emails. The sendEmail you are trying to send looks like is should be joiningusform not the one you have used. This seems also to use different variable names than the ones you are using (it looks like you have cut and pasted the CRM contact information).

  3. Since this is a createContact based email you can only really test this from a published page when not logged in.
    Here is my proposal of the changes you should look at:

$w.onReady(function () {                                         // ( #1  { #1
  $w("#JoinUsForm").onAfterSave( () => {                         // ( #2  { #2
    wixCRM.createContact({                                       // ( #3  { #3 
       "firstName": $w('#firstName').value,
       "lastName": $w('#lastName').value,
       "emails": [$w("#email").value],
       "Choir Role": $w("#choirRole").value,
       "Read Music": $w("#readMusic").value,
       "Choir Before": $w("#choirBefore").value,
       "Start Now": $w("#startNow").value,
       "Start Date": $w("#startDate").value
    })                                                            // } #3 ) #3
    .then((contactId) => {                                        // ( #3  { #3
       // Need to use the triggered email name
       return wixCRM.emailContact('joiningusform', contactId, {   // ( #4  { #4 
         "variables": {                                           // { #5 
         // Need to use the triggered email variable names
             "firstName": $w('#firstName').value,
             "lastName": $w('#lastName').value,
             "emails": [$w("#email").value],
             "choirRole": $w("#choirRole").value,
             "readMusic": $w("#readMusic").value,
             "choirBefore": $w("#choirBefore").value,
             "startNow": $w("#startNow").value,
             "startDate": $w("#startDate").value
          }                                                        // } #5 
      });                                                          // } #4 ) #4 
    })                                                             // } #3 ) #3
    .catch((err) => {                                              // ( #3 { #3
        // handle the error if the email wasn't sent
        console.log(`Error: ${err}`);
    });                                                            // } #3 ) #3
  });                                                              // } #2 ) #2
});                                                                // } #1 ) #1

export function registerButton_onclick(event) {                    // { #1
  $w("#JoinUsForm").save()
}                                                                  // } #1

Hope this helps

Good luck!

Yes sorry I forgot to mention that I was happy for yourself to access my site as I thought the Mods in this forum would have the same access as Wix support and could get in and check it all properly. Too busy with everything else I forgot to mention that!

Anyways, as for your reply which is most appreciated.

The two automated emails through Ascend I had setup as the code was not sending out any email to the person who submitted the form.

It was only supposed to be a temporary stop gap until I could get the ‘joiningusform’ triggered email to work through the code itself.

As for the code, I originally did have it in the emailContact section as you’ve put it in your code above, however for some reason I got it into my head that I had to change the emailContact and the createContact parts and not just the createContact section when doing this originally.

The email was not sent out then, so I thought I had made an error and must have got myself mixed up and easily confused and changed the emailContact section too.

I think to be honest that I probably did have the ‘Parsing Error: Unexpected Token }’ as I mentioned in previous post when I first did the emailContact section the same as yourself, before I changed it to exactly like the CRM fields and the createContact section.

However I think that I must have been too transfixed with the createContact and emailContact sections that I must have kept overlooking that error and not fixing it, instead getting too caught up in other errors. I definitely needed to step back and look at it with fresh eyes!

I have looked at your code and seen where I’ve gone wrong with it, I am still learning so better to make mistakes and learn from them now. Thank you very much for your help with the code.

Having used your new code and republished the website I have tested it again using a temporary email address through Temp Mail and this time both the fields in the dataset and the custom fields in the new contact details get filled in correctly. (I do not get any errors anywhere.)

I also turned off those two Ascend automations to test if the triggered email got sent too, however this triggered email still does not want to be sent, so for some reason it is still not working with the email sending.

I sent a test email from my own email account to the temporary email to test it and it received it all fine, so it wasn’t an issue with the temporary email that was being used.

If I turn the Ascend automations back on then I still do get those two emails sent out automatically and I have turned them back on for now as they do work, although they shouldn’t really be needed!

However, I would prefer the triggered email to work with the code on the page itself, although as the custom contact fields are now being filled in correctly too, then I could leave the Ascend automations on for the foreseeable future if the not sending the email problem can not be sorted out, as it seems to be a working and viable temp fix for it.

Apologies if this is a bit of a long winded answer for a reply, however your help and support with it all is very much appreciated and without it I would still be pulling my hair out or having sort of cheated and just gone back to using Wix Forms and taking the easy way out!

Thanks again.

P.S. Thinking about it then I could always setup that temp fix of Ascend automation to be sent back to the form submitter an hour later. That way I would have time to manually change the date in the dataset to the correct starting time and then it would be correct on the email sent back to them. Long winded way of working around the problem to get a solution!

Also, if this doesn’t get fixed then I might try using this tutorial for sending an email on form submissions and see if I can get that to work instead.

I have updated the page and swapped out the code and replaced it with sending an email on form submisson using SendGrid through the backend.

I have also setup authentication with my domain through DNS using CNAME, so instead of getting the sent via SendGrid attached to all my emails after my own sender details, I now just get my own sender details on it only.

It works all fine for me, however I would still prefer to have the branded triggered email by using the original code that I had and you helped with.

So I have republished the website with the working send emails via backend as the main join us page and the existing join us page is now hidden from menu and search engines. Although I will keep it for the time being and see if I can get it to work still.

So, if you know of any way to solve the email not working issue so that I can go back to using the triggered email instead of backend, then I would be must grateful, thanks.

@givemeawhisky Thank you for the update. I will take another look later today or tomorrow and see if I have any ideas.

Cheers

@givemeawhisky
OK I have managed to sort your problem out. There were a number of problems related to using datasets with this page.

  1. After a dataset save the field values linked to the data set are cleared. When the onAfterSave handler fires all values are available because the handler is called before the dataset operations have completed. The problem comes with the wixCRM create call. This is an asynchronous function call. So it doesn’t happen immediately it is queued to run when the dataset function completes. This means that the create call works fine BUT the subsequent email trigger fails because all of the form values are empty :-).
  2. Additionally you were passing an Array and a Date object to the triggered email variables list. Since the email is sending text only you need to make sure these values are text.
  3. You were using the wrong name for the email variable email - not emails :slight_smile:
  4. You were calling save() twice. The dataset binding to the button (green disk icon) calls save(), then you also have a registerButton_onclick(event) function that repeats this which generated an error.

I have checked this out and it now works :slight_smile:

Here are the code changes.

import wixCRM from 'wix-crm';

$w.onReady(function () {
  $w("#JoinUsForm").onAfterSave(() => {
  
  // Preserve our values as dataset will reset these after "onAfterSave"
  // create Contact is async (returns a promise) so these will be preserved
  // whereas the form values will be cleared by the dataset save.
 let startDate = $w("#startDate").value;
 let firstName = $w('#firstName').value;
 let lastName = $w('#lastName').value;
 let email =  $w("#email").value;
 let choirRole = $w("#choirRole").value;
 let readMusic = $w("#readMusic").value;
 let choirBefore = $w("#choirBefore").value;
 let startNow = $w("#startNow").value;
 
    wixCRM.createContact({ 
 "firstName": firstName,
 "lastName": lastName,
 "emails": [email],
 "Choir Role": choirRole,
 "Read Music": readMusic,
 "Choir Before": choirBefore,
 "Start Now": startNow,
 "Start Date": startDate
      }) 
      .then((contactId) => { 
 // Need to use the triggered email name
 return wixCRM.emailContact('joiningusform', contactId, { 
 "variables": { 
 // Need to use the triggered email variable names
 "firstName": firstName,
 //"lastName": $w('#lastName').value,  << - not defined in the triggered email
 //"emails": [$w("#email").value],   << - cannot have array here
 "email": email, // << - correct variable is email not emails
 "choirRole": choirRole,
 "readMusic": readMusic,
 "choirBefore": choirBefore,
 "startNow": startNow,
 "startDate": startDate.toString()
          } 
        });  
      }) 
      .catch((err) => { 
 // handle the error if the email wasn't sent
        console.log(`Error: ${err}`);
      }); 
  }); 
}); 

/* Remove this as the Submit button is already calling this function so 
   you end up calling it twice which is an error
export function registerButton_onclick(event) { 
  $w("#JoinUsForm").save()
} */

Cheers
Steve

@stevendc

Thanks for your help with this and it all works fine now with the triggered email. Just one small issue is left now!

I have now deleted all other ‘Join Us’ pages apart from the one shown on the website and the existing ‘Join Us Original Triggered Email’ page that you worked on.

I have also deleted all the backend files for the triggered email through third party (SendGrid) pages too, however I have kept all the code stored just in case I want to use it somewhere else and don’t have to redo it all.

I have though left a data.js hook in backend as it is setup on two datasets - ‘JoinUsForm’ and ‘Members’ - so that the first letter of each name is in capital letters. I might add my other datasets too later on.

Anyways, back now to the small issue… we are nearly there!

The small issue I still have with it is that the date is still shown on the triggered email as date and time and not just the date only with it left as .toString().

With your line of:

"startDate": startDate.toString()

If I modify it to either of these options:

 "startDate": startDate.toLocaleDateString('en-GB')
 "startDate": startDate.toDateString() 

Then it does show the date only as 29/01/2019 or Tue Jan 29 2019, which is ideal.

However, in the Contacts List it then lists the same contact as two seperate contacts as this:

For some reason it is creating a new contact with the triggered email details and yet no custom fields are filled in, then also listing a seperate but same contact which shows the last visit and this time with the custom fields filled in.

Obviously this is not want I wanted, so is there an easy way that I can stop this from happening by modifying the code already setup.

Or add something like this in the code somewhere?:

let item = $w("#JoinUsForm").getCurrentItem();
let startDate = item.startDate;
startDate = startDate.toDateString();
// That gets only the date string of the value

Although if I try to put exactly that above into my code then it will keep reporting it as an error as ‘startDate’ is already defined in the code.

Can I add a hook in the dataset for it so that it takes the input from date and time - something like a beforeInsert like I’ve already done for the cap letters at start? - so that the date and time is formatted to just the date and then it returns this date input back into the dataset field before it carries on with that last startDate put back to startDate.toString()?

I will have a go at it myself to see if I can get something to work for it, however if you know of a simple answer for it then that would solve my last little issue.

Would be great if we all had the option of being able to choose how we display the date and time in the dataset field itself, or in the variable on a triggered email or on the page itself without having to resort to coding it.

I know that the date can be shown as date only if you are displaying it on a page by using code or you can just put the date picker on your page as read only and it will just show the date only.

However, you would think that it would be that easy to do it on the dataset field or a triggered email with code too, or am I expecting too much!

Finally, thank you very much for all your help and it is very much appreciated.

Hi there,

I have the same problem,
“The database fields are being filled in and a new contact is created, however the custom fields in the new contact is not being filled in with anything and it doesn’t send out an email in return to the new contact as per the code should do.”
and also when I do the test in preview if it creates the custom field but not in publish

Hey man! Sorry for bothering, but have you found any solution for this? I’m currently having the same issue as you… the only thing I can think of is it’s a Wix bug of some sort, 'cause I can save custom fields just fine to the sandbox non-live site version. However, the moment I try it in the live published website, my assigned custom field remains empty…
I tried doing it with onReady() and both with onAfterSave() or onBeforeAfterSave(), and even without any of them, just using the onClick event for the submit button… every single one led to empty custom fields. This is driving me nuts already…

@polifinance As this is an old (and solved!) post, please create a new post for your question and include your code formatted in a code block. Thanks!