1.13. Creating a New Contact in the Address Book

Problem

You want to allow your application to create and save a new contact or edit an existing contact in the device’s address book.

Solution

The PhoneGap API exposes a function called contacts.create that accepts a structure with the information about the contact. It creates a new Contact object that contains a save function to add the contact to the address book. When the Contact.id already exists, the information is updated instead of creating a new contact. By creating a new form that allows the user to enter information about the contact, when the user submits the data, it will be saved in the address book.

Discussion

The first thing that you need to do is create a new form. Inside of your assets/www directory, create a new file called form.html. This contains a basic form that will be used to collect the contact’s information.

<!DOCTYPE HTML> <html> <head> <title>PhoneGap</title> </head> <body> <div data-role="page" id="form-page"> <div data-role="header" data-position="inline"> <a href="contacts.html" data-icon="delete"> Cancel</a> <h1>Add Contact</h1> <a onClick="return saveContact()" href="#" data-icon="check" data-theme="b">Save</a> </div> <form action="form.html" method="post"> <input type="hidden" name="id" value="0" /> <table> <tr> <td>Display Name</td> <td><input type="text" name="displayName" value="" /></td> </tr> <tr> <td>First Name</td> <td><input type="text" name="firstName" value="" /></td> </tr> <tr> <td>Last Name</td> ...

Get 20 Recipes for Programming PhoneGap now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.