Reputation: 103
I need to get back the contact id after it is saved in order to save it to my online database. However the cordova contact.save() method does not return an id after execution.
Here is my logic:
if ($scope.contact.id === undefined) {
contact.save();
console.log("Contact ID is:", savedContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}
This does not work.
Is there any way to retrieve the id for the contact without having to search the phones contact list using a phone number like this:
if ($scope.contact.id === undefined) {
contact.save();
var savedContact = navigator.contacts.find({ "phoneNumbers[0]": phoneNumbers[0].value });
console.log("Contact ID is:", savedContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}
The above seems like way too much overhead. Not to mention it may not even return the correct contact as a phone number may not be unique.(If someone saves the contact twice with different information)
Upvotes: 0
Views: 438
Reputation: 1049
contact.save()
can take two callbacks, success and failure. The success callback should return your newly saved contact (which would include the id.)
if ($scope.contact.id === undefined) {
contact.save(contactSuccess, contactFailure);
}
function contactSuccess(newContact) {
console.log("Contact ID is:", newContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}
function contactError(err) {
//bb10 fires multiple error callbacks with empty errors
if (err) {
console.log(err);
}
}
Since it looks like you are using Angular, check out the ngCordova project. It provides some nice wrappers around some plugins that make everything a bit more readable. Here is the relevant excerpt from their contacts docs:
$cordovaContacts.save($scope.contactForm).then(function(savedContact) {
console.log("Contact ID is:", newContact.id);
table.insert({ id: contact.id.value, firstname: name.givenName, lastname: name.familyName, homephone: phoneNumbers[0].value, mobilephone: phoneNumbers[1].value, email: emails[0].value });
}, function(err) {
if (err) {
console.log(err);
}
});
Upvotes: 2