Tag: Submit

Recently a client of ours asked if we could implement a solution to allow a Formidable Forms submission to send data as a CSV file to an external server when a user submits the form. The client wanted the form submissions to be imported into a 3rd party software that could only accept CSV files from a folder on an external server so we looked at building a solution.

This functionality can have several use cases and be used as our client required to export a unique CSV file per form entry or you could amend it to allow a single CSV file to be updated with a new row each time a form is submitted.

You can view the full tutorial, along with a little extra information on connecting to a remote FTP server, HERE.

Part 1: Create the CSV

Firstly, we created a form for users to fill out which will capture essential data we would need to store on the CSV. Our code below assumes the form has the following fields (but you can change these to meet your requirements):

  1. First name
  2. Last name
  3. Email address
  4. Organisation ID
  5. Organisation Name

In our snippet below, we use the frm_after_create_entry hook which runs after the entry has been created in the database. This allows us to use the data once the form has been submitted.

add_action('frm_after_create_entry', 'create_csv', 30, 2);
function create_csv($entry_id, $form_id) {
	if ($form_id == 1234) { //replace 1234 with the id of the form

		// Collect the form data - Add a new row for each field you want to export and give it a unique name
		$firstName = isset($_POST['item_meta'][1537]) ? $_POST['item_meta'][1537] : '';
		$lastName = isset($_POST['item_meta'][1538]) ? $_POST['item_meta'][1538] : '';
		$email = isset($_POST['item_meta'][1540]) ? $_POST['item_meta'][1540] : '';
		$organizationId = isset($_POST['item_meta'][1547]) ? $_POST['item_meta'][1547] : '';
		$organizationName = isset($_POST['item_meta'][1548]) ? $_POST['item_meta'][1548] : '';
		$createdAt = isset($_POST['item_meta'][1555]) ? $_POST['item_meta'][1555] : '';

		// The header row of the CSV - Add a name for each field in the form
		$header = "firstName,lastName,email,organizationId,organizationName,createdAtn";

		// The data of the CSV - Add each of the form fields listed above
		$data = "$firstName,$lastName,$email,$organizationId,$organizationName,$createdAtn";

		/*
		 * The file name of the CSV.
		 * 
		 * NB: To save a single file per entry you will need to make the file name unique 
		 * This can be done using the entry ID or the date & time stamp by including the hour, minutes & seconds. 
		 * E.g at 12:38:43 the file will be named "TestUser-21-02-05-12-38-43-request.csv".
		 * One second later the time (and file name) will be "12:38:44".
		 * Then a new file "TestUser-21-02-05-12-38-44-request.csv" will be created.
		 * How you name the file will determine if you have a new file for each entry, a new file per user or a single file with all entry data.
		 */

		$fileName = dirname(__DIR__, 3) . "/your-project-folder/" . $refUserId . "-" .$createdAt . "-request" . ".csv";

		/*
		 * Create the CSV file.
		 * If file exists, append the data to it. Otherwise create a new file.
		 */
		if (file_exists($fileName)) {
			// Add only data. The header is already added in the existing file.
			file_put_contents($fileName, $data, FILE_APPEND);
		} else {
			// Add CSV header and data.
			file_put_contents($fileName, $header.$data);
		}
	}
}

What the code does

The function, create_csv, will first check to see which form has been submitted. In our case, if the form with an ID of 1234 has a new entry then the rest of our code will trigger.

We’re storing all the data we need to export onto the CSV into PHP variables. This will make it much easier to pass our $data. You’ll need to add rows for each field you want to export giving it a unique variable name. We’re also using the PHP isset function which will handle the scenario of any of the fields being left blank and not containing a value.

$firstName = isset($_POST['item_meta'][202]) ? $_POST['item_meta'][202] : '';
$lastName = isset($_POST['item_meta'][203]) ? $_POST['item_meta'][203] : '';
$email = isset($_POST['item_meta'][204]) ? $_POST['item_meta'][204] : '';
$organizationId = isset($_POST['item_meta'][193]) ? $_POST['item_meta'][193] : '';
$organisationName = isset($_POST['item_meta'][194]) ? $_POST['item_meta'][194] : '';
$refUserId = isset($_POST['item_meta'][197]) ? $_POST['item_meta'][197] : '';
$createdAt = isset($_POST['item_meta'][199]) ? $_POST['item_meta'][199] : '';

If you’re reading this article then you’re most likely familiar with what components make up a valid CSV document. For those of you who aren’t so familiar, CSVs are made up of two main parts: Headers; and Data – separated by commas (or any other valid delimiter).

Simply put, headers are the name of the column whereas the data is the value you’d like to store in that column.

For our function, we need to come up with suitable headers (column names) for our CSV document and store our data in CSV format.

$header = "firstName,lastName,email,organizationId,organisationName,refUserId,createdAtn";

$data = "$firstName,$lastName,$email,$organizationId,$organisationName,$refUserId,$createdAtn";

The next stage is to save the file to our web-server and to do that we need to decide on what we want the file to contain. If we want to create a new file for each form entry (as our client did) then we’ll need to create a unique filename for each file. We do this in our code by adding the date & time stamp to each file name however if you want to have just 1 CSV file add a new row to it for each new form entry you can set the filename as something static.

We also need to set a location to save the file on our local server.

In our clients case we set this fucntion up using the Code Snippets plugin and as the code will be executed from the plugin folder we had to add in (__DIR__, 3) in the file path to look 3 directories above where the code runs to then get the correct to the folder they wanted to store the files locally.

The file path and name are then all set on the same line of code using variable set as seen below.

$fileName = dirname(__DIR__, 3) . "/your-project-folder/" . $refUserId . "-" . $createdAt . "-request" . ".csv";

If you only want to save the CSV file(s) on your own web-server then thats all you need to do. However if you then want to move the files once they have been created to an external server via FTP, you can view the full tutorial HERE which covers stage 2 ina bit more detail.

And thats it. We’ve tried to add as much markup as possible to the code itself to help explain further what each part does so amending this to your own needs should be quite straight forward.

Making the Best WordPress Plugin even better - Together

Take on bigger projects with confidence knowing you have access to an entire community of Formidable Experts and Professionals who have your back when the going gets tough. You got this!
Join the community
crossarrow-right