Reputation: 329
I'm trying to create contact with a custom field, as detailed in the documentation here. So I've tried to use this code, from the documentation:
var contacts = ContactsApp.getContactsByName('John Doe');
var field = contacts[0].getCustomFields()[0];
field.setLabel('Mail application');
field.setValue('Gmail');
When I run the script I get the following error:
TypeError: Cannot read property 'setLabel' of undefined
Any thoughts?
Here's my complete code, to which I'd like to be able to add a custom field named "ID number":
var clientaddress = spreadsheet.getRange('L2').getValue();
var clientcontact = ContactsApp.createContact(clientfirstname, clientlastname, clientemail);
var contactgroup = spreadsheet.getRange('AL2').getValue(); // AL2 has the group name
var group = ContactsApp.getContactGroup(contactgroup);
clientcontact = clientcontact.addToGroup(group);
var address = clientcontact.addAddress(ContactsApp.Field.HOME_ADDRESS,clientaddress);
var phone = clientcontact.addPhone(ContactsApp.Field.MOBILE_PHONE, clientmobile);
var IDnumber = ?
Here's the code I'm trying to run as a test:
function quicktest () {
var contacts = ContactsApp.getContactsByName('XXXX');
var IDnumber = contacts.addCustomField("IDnumber","12345");
}
OK, so now that we know it's an array, I added the [0] to the code but still no joy.I made sure to chose a contact that has no duplicates, so I'll be sure it's editing the right contact.
function quicktest () {
var contacts = ContactsApp.getContactsByName('XXX');
var IDnumber = contacts[0].addCustomField("IDnumber","12345");
}
Here's the screenshot of the contact "more details" page.
Yes, it's working now :) Thanks to everyone! Revised code:
function quicktest () {
var contacts = ContactsApp.createContact("test1", "familytest1", "[email protected]").getId();
ContactsApp.getContactById(contacts).addCustomField("IDnumber","12345");
}
Screenshot from Google ContactS:
Upvotes: 0
Views: 683
Reputation: 50443
field.setLabel('Mail application');
Cannot read property 'setLabel' of undefined
The error says that field
is undefined
and that it cannot read a property called setLabel
in undefined
(because undefined
doesn't have such a method; only customField class does).
field
is undefined
, because the contact "John Doe" doesn't have a custom field associated with it.
Use Contact.addCustomField("fieldName","fieldValue")
to add a custom field to a contact:
clientcontact.addCustomField("IDnumber","12345");
Upvotes: 3