In the last tutorial, we learnt how to enhance the Force.com PHP Toolkit by building a Contact Detail page and doing CRUD operations on the user interface for Contact records. In this post, we’ll look at how to import and export Contact records into a CSV file.
I added a ‘Export to CSV’ option on the Contact listview page as follows.
Clicking this will export all contact records into a CSV file.
There are a couple of ways to do it – A) Fetch data from Salesforce using the SOAP API, store it in memory and dump it a CSV file B) Since we’re already showing the records on the user interface, just read it from there and dump it to a CSV file
For simplicity, I’m demonstrating the approach B) mentioned above.
We read the data from the table and store it each row (delimited by new line) and each column (delimited by ,) as shown above.
We then set the mime type and push all the the data to the CSV file as shown above. For import, the user can chose any CSV file via this file chooser option.
And selecting a file will insert all records into the Salesforce backend and show them in the list view as well. If there are any errors, it will show them in an alert.
We first try to read the file and validate the headers to determine if the file is valid or not.
Once we’ve validated the headers, we read each row and each cell and then try to create a record for it as shown below.
If there’s an error, we shown an alert. If all records are imported successfully, the list view is refreshed to show the newly added records as well.
This wraps up the import/ export capability that we added to the Force.com PHP Toolkit. The updated source code is available here.
I’ll polish up the code hopefully in the next week or so and publish it to my Github repo as well.