This is a howto guide on manually integrating RSForm Pro with the MailChimp API using the scripting feature. None of this requires the separate MailChimp plugin that is available. You'll need some understanding of PHP or the willingness to Google the bits you don't understand in order to learn.
How would you like to send out an email to your subscribers that contained a link to your RSform and when the subscriber clicked on it, the form was pre-filled with their data from MailChimp? Or would you like to selectively pick information off an RSForm and use it to subscribe people to a MailChimp list? Once you understand the MailChimp api, you can make use of it with RSForm in any way that you want.
First thing's first. Head over to MailChimp and
create an api key and then
download the php api wrapper files. The latter contains
MCAPI.class.php and
config.inc.php. These two files will need to go in a directory on the web server with 755 permissions. Essentially, you put a copy of your API key into
config.inc.php. I comment out most of the other defaults. The PHP wrapper lets you use the api with
just some simple commands.
We're also going to be manipulating the output of the form. So to make that easier, you'll need a
copy of the Simple HTML DOM Parser. It allows you to find tags and change attributes in the form HTML without doing string searches. Place
simple_html_dom.php in the same directory as the MailChimp files.
Step 1
Create a simple form. Make sure that the
Name of your textboxes in RSForm matches the
mergetag name (excluding the *| |*) that you used for the same field in Mailchimp.
Go to the
Scripts tab and the
Scripts Called On Form Display. Your first bit of code should reference the files so that you can make use of them. I put the files in a folder called mailchimp.
require_once 'mailchimp/MCAPI.class.php'; // mailchimp functions
require_once 'mailchimp/config.inc.php'; //contains mailchimp apikey
require_once 'mailchimp/simple_html_dom.php'; //simple html parser to modify rsform output
Step 2
The key to getting your form to display data from MailChimp is to embed the unique list id and contact id into the URL in your email.
Within your MailChimp email, create a new link to your RSForm page. You need to add two new parameters called Listid and Contactid. Populate them with the merge tags *|LIST:UID|* and *|UNIQID|*.
http://www.example.com/index.php?option=com_content&view=article&id=3&Itemid=21&listid=*|LIST:UID|*&contactid=*|UNIQID|*
Your URL is now individually tailored to each email subscriber.
Step 3
Now you have to tell RSForm Pro to grab those ID's. So back to your script and insert:
// Find contactid parameter in URL and get value
$contactId = JRequest::getVar('contactid');
// Find listid parameter in URL and get value
$listId = JRequest::getVar('listid');
So now you can reference the variables $contactid and $listid in your PHP script to get the data.
Step 4
I normally put all my code into an if statement like this one.
if (isset($contactId, $listId)) { your code }
Only if your URL string contained the listid and contactid data, will the script execute. If you load the page normally, nothing will happen.
Step 5
In the IF statement code area, you need a few more lines to set things up properly.
// New instance of mailchimp api
$api = new MCAPI($apikey);
// Create a new instance of DOM object
$html = new simple_html_dom();
//Set the key name that holds the merge data in the mailchimp array
$mergekey = "merges";
$api creates a new connection to the Mailchimp api using the functions in MCAPI.class.php and the api key in config.inc.php.
$html creates a new instance of the Simple HTML DOM that you can place the form html code into so that it can be manipulated.
$mergekey defines the key name in the array that comes back from Mailchimp that holds an array of all your data. Hopefully it will be documented if MailChimp change this key name.
Step 6
Now comes the fun part. Let's go get some data from MailChimp.
// send the listid and contactid to mailchimp to retrieve contact info
$chimparray = $api->listMemberInfo( $listId, array($contactId) );
$chimparray is going to contain the array of data that we get back. We're going to use the api connection to get some info about a member of our list. You can see that we're passing it the listid and the contact id that we extracted earlier. The array will contain everything that Mailchimp knows about this member.
The trouble is that what we've got back is an array of arrays. All the data we want is in a single array. So we need to extract that data into just a single array to make it easier to work with.
// break the multidimensional mailchimp array into a single array of merge field data
$mergedata = get_keyval($chimparray, $mergekey);
$mergedata will contain our single array of data. We're passing our array of arrays and the key name of the array we want into a function.
Here's a copy of that function.
/**
Within a multidimensional array, search for a key name that marks the start of another array and save it
as a single array on its own
**/
function get_keyval($arr,$mykey) //input the array and search key
{
foreach($arr as $key => $value){ //loop through array elements
if((gettype($key) == gettype($mykey)) && ($key == $mykey)) { // check that key and mykey are same data type and see if they match
return $value; // output result
}
if(is_array($value)){ //check if result contains an array
return get_keyval($value,$mykey); // if it does, run through function again - recursion
}
}
return None; // if no matches, return nothing
}
Step 7
Now we have our data, let's do something with it.
First thing we have to do is to get the existing html code for our form. RSForm pro lets us do that using the variable $formlayout. So let's put that into our HTML DOM.
// load the form html - $formLayout - into an object
$html->load($formLayout);
Now we can manipulate the form output as we please. Using this function...
// run valreplace function to update html form with new default values
valreplace ($mergedata,$html);
...we will find all textbox names in our form that match mergefield tags in our Mailchimp array. Then for each textbox, we will replace the default value with the data from the Mailchimp array. Here's a copy of the function.
/**
Loop through an array comparing array keys to <input> element attribute ids in a HTML object. For each match,
replace the element attribute called value with the corresponding key value from the array
**/
function valreplace ($arr, $html) // input single array and html object
{
foreach ($arr as $key => $value) { // loop through array elements
// setup the search string that finds an input element with the id attribute equal to the key
$findstring = "input[id=".$key."]";
// find and return the first object that matches the search
$e = $html->find($findstring, 0);
// find the value attribute within the same element and insert the new value
$e->value = $value;
}
// output the updated html object
return $html->save();
}
Step 8
The final step is to save our modifications to the form html and pass the modified layout back to RSForm.
// overwrite existing $formLayout with modified $html
$formLayout = $html;
// make rsform load new modified form
return $formLayout;
That's it! You have just populated a form with data from MailChimp.
Advanced Functions
What if you have checkboxes on your form and you want them to be checked based on data that Mailchimp is holding?
In the RSForm
Items area for a checkbox, I had a number of items written like this:
Field Value|Checkbox Display Value
For my purposes I was importing data into MailChimp rather than using their checkboxes. So I had a MailChimp text field with a merge tag called
CHECKED. In this field, I would put the
Field Value from my RSForm that I wanted to be ticked. I could specify more than one by separating them with the |.
I then called my makechecked function.
// run makechecked function to make checkbox values selected. Uses | as seperator
makechecked ($mergedata,$html);
This is what the function looks like.
/**
Loop through an array comparing array values to <input> element attribute values in an HTML object. For each match,
create the element attribute called checked, with a value of checked
**/
function makechecked ($arr, $html) // input single array and html object
{
// only execute function if array contains CHECKED key
if (array_key_exists("CHECKED",$arr))
{
// Get the string value for the array key CHECKED and put it in a variable
$checkarr = $arr["CHECKED"];
// Use | as a seperator and create a new array called SELECTION that contains each unique part
$selection = explode('|', $checkarr);
foreach ($selection as $key => $value) { // loop through array elements of SELECTION array
// setup the search string that finds an input element with the value attribute that starts with the array value
$findstring = "input[value^=".$value."]";
// find and return the first object that matches the search
$e = $html->find($findstring, 0);
// create the checked attribute with the value checked
$e->checked = "checked";
}
// output the updated html object
return $html->save();
} // close IF statement
else
{
return None; //if CHECKED doesn't exist, do nothing
}
}
If you do use MailChimp check boxes, that may give you some ideas as to how to read them and manipulate the RSForm.
Uploading Values
You can upload data to Mailchimp too. If you're not getting a listid in the URL, you'll need to make sure that you specify a $listid variable manually and populate it with the Mailchimp List ID where subscriptions will go. This script needs to go in the
Scripts On Form Process area.
Step 1
For clarity of code and ease of updates, I extract the data from the form and put it in some new variables. The
Name of the form field is the one right at the end of each line.
$user_email = $_POST['form']['email'];
$form_fname = $_POST['form']['fname'];
$form_lname = $_POST['form']['lname'];
$form_company = $_POST['form']['company'];
Then you need to match up the variables with data from your form to the mergetags that Mailchimp is expecting (except the field that contains the email address) and create an array.
//Match up Mailchimp merge fields to the form variables collected
$merge_vars = array('FNAME'=>$form_fname, 'LNAME'=>$form_lname, 'COMPANY'=>$form_company);
Step 2
You'll need to make sure that you've already initiated a connection to the api as I showed earlier.
Then it's just a matter of using the list subscribe function.
// For list subscribe config, see http://apidocs.mailchimp.com/rtfm/listsubscribe.func.php
$api->listSubscribe( $listId, $user_email, $merge_vars, 'html',false,true,true,false);
That's it. I hope that this tutorial has been useful and given you an insight into how you can manually script interactions between RSForm and MailChimp. Take the time to read the MailChimp api documentation - it's very good.