Tag: CSV

Recently a question was posed in the forum on how to export information from forms into a .csv file so that that the field name, field ID and field key is displayed.  I have a need for this as well, so I here is what satisfied my particular need for a client and I wanted to share the code snippet with the community encase it would prove helpful to others.

Using the code snippets plugin or by adding to your themes function.php file, put add the following code:

<code>

<?php
/* Export Form Fields to CSV */
function export_form_fields_to_csv() {
// Check if Formidable Forms plugin is installed and activated
if ( ! class_exists( 'FrmFormsController' ) ) {
return 'Formidable Forms plugin is not activated';
}

$forms = FrmForm::getAll(); // Get all Formidable Forms

// Create an array to store the form field data
$fields_data = array();

// Loop through each form
foreach ( $forms as $form ) {
$form_fields = FrmField::get_all_for_form( $form->id );

// Loop through each form field
foreach ( $form_fields as $field ) {
$field_data = array(
'form_name' => $form->name,
'field_name' => $field->name,
'field_type' => $field->type,
'field_id' => $field->id,
'field_key' => $field->field_key,
);

// Add the field data to the array
$fields_data[] = $field_data;
}
}

// Create the CSV file
$csv_file = fopen( 'form_fields.csv', 'w' );

// Add the CSV header
fputcsv( $csv_file, array( 'Form Name', 'Field Name', 'Field Type', 'Field ID', 'Field Key' ) );

// Add the data rows
foreach ( $fields_data as $field_data ) {
fputcsv( $csv_file, $field_data );
}

// Close the CSV file
fclose( $csv_file );

// Return the file path for the download link
return get_site_url() . '/form_fields.csv';
}

// Register the shortcode for the download link
function form_fields_csv_download_link_shortcode() {
$csv_url = export_form_fields_to_csv();

// Check if there was an error during the export process
if ( is_string( $csv_url ) ) {
return $csv_url;
}

// Return the download link markup with inline CSS
$download_link = '<a style="display: inline-block; margin: 10px 0; padding: 8px 16px; font-size: 14px; font-weight: 600; line-height: 1.5; color: #007bff; background-color: transparent; border: 2px solid #007bff; border-radius: 4px; text-align: center; text-decoration: none; transition: background-color 0.2s ease-in-out, color 0.2s ease-in-out; box-shadow: none;" href="' . $csv_url . '" download="form_fields.csv">Download Form Fields</a>';

return $download_link;
}
add_shortcode( 'form_fields_csv_download_link', 'form_fields_csv_download_link_shortcode' );

</code>

This snippet creates a short-code that you can add to a wordpress page or post that will create a link to download a CSV file which contains a list of all of your forms Field Names, Field ID's and Field Keys and Field Type.

The shortcode is:

<code>

[form_fields_csv_download_link]

</code>

Again I hope this is helpful!

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