2

I can create a new Google contact on submission of a Form. I need to add a label to these contacts but I couldn't find any method to do that. Is it possible to add a label? Here is a snippet of my code for finding/creating a contact:

var contact = ContactsApp.getContact(email);
if(!contact){
  contact = ContactsApp.createContact(firstName, lastName, email);
}
TheMaster
  • 45,448
  • 6
  • 62
  • 85
  • Thank you for replying. I'm glad your issue was resolved. From your replying, I could understand that my answer was not useful for your situation. This is due to my poor skill I deeply apologize for this. I would like to delete my answer because I don't want to confuse other users. So can you post your answer as an answer? By this, it will be useful for other users who have the same issue. I deeply apologize for my poor skill again. – Tanaike Aug 09 '20 at 00:51
  • Btw, small tip: `var contact = ContactsApp.getContact(email) || ContactsApp.createContact(firstName, lastName, email);` – Oleg Valter is with Ukraine Aug 09 '20 at 04:37
  • 1
    Thanks for the tip. To be honest, it was your code that made me realize that "Labels" are actually called "ContactGroups" in the API. I will post my solution as an answer. :) – Aaryan Gupta Aug 10 '20 at 00:09
  • @AaryanGupta - I assume you mean Tanaike's code? Btw, good to know, I do not work with Contacts usually, so that's good to know :) – Oleg Valter is with Ukraine Aug 10 '20 at 01:48

1 Answers1

1

To add label to a contact, add Contact to a ContactGroup. Here is a sample code:

  let labelName = 'myLabel';
  let firstName = 'John';
  let lastName = 'Doe';
  let email = 'john.doe@gmail.com';

  //find or create the Contact
  let contact = ContactsApp.getContact(email) || ContactsApp.createContact(firstName, lastName, email);
  }

  //find the Label
  let group = ContactsApp.getContactGroup(labelName);

  //add label to the contact
  group.addContact(contact);