Formidable Forms: Export Large Views to One CSV in Batches Without Timing Out

Formidable Forms Batch Export Frontend

Written by

in

I have a client, who is actually a very close friend of mine, running a sales tracker on F. Every branch submits its shift sales through a form, and the team reviews everything in a Formidable View with filters for date, branch and POS type. It works great, until somebody clicks the Export to Excel link at the bottom of the View.

With more than 27,000 entries in the form, the export just spins and then times out. So I wrote a small plugin that exports the same entries in batches and still gives you one CSV file at the end. Here is how it works, and the full code is at the bottom of this post.

Why the default export times out

The View export builds the entire CSV inside a single web request. It loads every matching entry, formats every field, and only then sends the file. With a few hundred entries you never notice. With tens of thousands, that one request runs longer than PHP and the web server allow, and the server kills it before the file is ready.

You can raise max_execution_time and the memory limit, but most hosts also have a hard timeout at the server or proxy level. And even if you get it working today, it breaks again as the data keeps growing.

The fix: many small requests, one file

Instead of one huge request, the plugin splits the export into small jobs that each finish in a second or two:

  1. Start. The browser sends the form ID and filters. The server counts the matching entries, creates a CSV file with the header row, and returns a job ID.
  2. Batches. The browser asks for the next 1,000 entries again and again. Each request reads only those entries, formats them, and appends the rows to the same CSV file on the server. It remembers the last entry ID it wrote, so the next batch picks up exactly where the previous one stopped.
  3. Download. When a batch comes back with fewer than 1,000 rows, the export is done. The browser downloads the finished file, and the server deletes it right after.

So no, you do not end up with 28 separate CSV files. Every batch writes into one file, and you get one download.

What else it handles

  • Progress modal. A popup shows the progress bar, how many entries are done, a percentage, and a Cancel button. Cancel also deletes the half-built file.
  • Retries without duplicates. If a batch request fails, it retries up to three times. Before each batch it trims the file back to the size saved after the last successful batch, so a retry never writes the same rows twice.
  • Excel friendly. The file starts with a UTF-8 BOM so Excel shows accented letters and symbols like ? correctly. Values that start with =, +, - or @ are escaped so Excel will not run them as formulas.
  • Readable values. Dynamic fields export the linked value instead of an entry ID, user ID fields export the display name, and file uploads export the file URL.
  • Locked down. Only logged-in users who can view Formidable entries can use it. Export files are saved with random names in a folder that blocks direct access, and leftover files are deleted after a day.
  • Fast queries. It reads entries and their values straight from the Formidable tables in two queries per batch, instead of loading entries one by one.

Using it from the admin

After you activate the plugin, go to Formidable > Batched Export. Pick a form, and optionally set a field to filter on, a date range (on a date field or on the entry created date), and the batch size. Click Export CSV and keep the tab open until the download starts.

Using it on the same page as your View

The more useful part is the shortcode. Most Formidable Views that have a filter form work through URL parameters. The filter form redirects to something like /tracker/?branch=MAKATI&startdate=11/01/2026, and the View filters use [get param="branch"] to read those values.

The shortcode reads the same URL parameters when you click the button, so the export always matches what the table is showing. Here is the one I use on the sales tracker:

[bryanveloso_batch_export form_id="55" match="1139:pos,1097:branch" match_any="1112:salesdate:date,1113:encodeddate:date" range="1112:startdate:enddate" label="Export to Excel"]

To set it up for your own View, open the View, click Filter entries, and copy each rule into the shortcode:

  • form_id: the form the View pulls entries from.
  • match: rules like “Field equals [get param]”. Write them as fieldID:param, separated by commas. All of them must match. Add :date if the field is a date.
  • match_any: an Or group in your View. At least one of these must match.
  • range: a “greater than or equal” and “less than or equal” pair on one date field, written as fieldID:fromParam:toParam.
  • require (optional): URL parameters that must be set before the export runs, for example require="branch".
  • label: the button text.

A blank URL parameter is skipped, the same way the View ignores a blank [get param]. Dates can come in as m/d/Y (the usual datepicker format) or Y-m-d. The plugin converts them to Y-m-d, which is how Formidable stores date fields.

Limitations

  • Filters only support “equals”, one Or group, and date ranges. Rules like “contains” or “not equal” are not supported yet.
  • It exports every field in the form plus Entry ID, Created and Updated. It does not copy the custom columns of your View.
  • Repeater rows are not included as separate lines.

Installation

  1. Create a folder named bryanveloso-batch-export and save the code below inside it as bryanveloso-batch-export.php.
  2. Zip the folder and upload it in Plugins > Add New > Upload Plugin, or copy the folder to wp-content/plugins/.
  3. Activate it. You need Formidable Forms active, and Formidable Pro if you want to use Views.
  4. Test with a small filtered export first, then try the full one.

The code

<?php
/**
 * Plugin Name: Bryan Veloso Batched Formidable Export
 * Description: Exports Formidable Forms entries to a single CSV file in batches (default 1,000 entries per request), so very large forms do not time out.
 * Version:     1.2.0
 * Requires PHP: 7.4
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class BRYANVELOSO_Batched_Export {

	const NONCE = 'bryanveloso_bx';
	const DIR   = 'bryanveloso-exports';

	/** Field types that hold no exportable data. */
	const SKIP_TYPES = array( 'break', 'divider', 'end_divider', 'html', 'captcha', 'form', 'summary', 'submit', 'password', 'credit_card' );

	public static function init() {
		add_action( 'admin_menu', array( __CLASS__, 'menu' ), 99 );
		add_shortcode( 'bryanveloso_batch_export', array( __CLASS__, 'shortcode' ) );
		add_action( 'wp_ajax_bryanveloso_bx_start', array( __CLASS__, 'ajax_start' ) );
		add_action( 'wp_ajax_bryanveloso_bx_batch', array( __CLASS__, 'ajax_batch' ) );
		add_action( 'wp_ajax_bryanveloso_bx_cancel', array( __CLASS__, 'ajax_cancel' ) );
		add_action( 'admin_post_bryanveloso_bx_download', array( __CLASS__, 'download' ) );
	}

	/* ------------------------------------------------------------------ *
	 * Permissions and helpers
	 * ------------------------------------------------------------------ */

	private static function can() {
		return current_user_can( 'frm_view_entries' ) || current_user_can( 'manage_options' );
	}

	private static function formidable_ready() {
		return class_exists( 'FrmField' ) && class_exists( 'FrmForm' );
	}

	private static function dir() {
		$up  = wp_upload_dir();
		$dir = trailingslashit( $up['basedir'] ) . self::DIR;
		if ( ! is_dir( $dir ) ) {
			wp_mkdir_p( $dir );
			file_put_contents( $dir . '/index.php', "<?php // Silence.\n" );
			file_put_contents( $dir . '/.htaccess', "Require all denied\nDeny from all\n" );
		}
		return $dir;
	}

	/** Remove export files older than one day. */
	private static function cleanup( $dir ) {
		foreach ( (array) glob( $dir . '/*.csv' ) as $file ) {
			if ( $file && filemtime( $file ) < time() - DAY_IN_SECONDS ) {
				@unlink( $file );
			}
		}
	}

	/** Accepts Y-m-d or m/d/Y (the filter form's format) and returns Y-m-d, or '' if invalid. */
	private static function clean_date( $value ) {
		$value = trim( sanitize_text_field( wp_unslash( (string) $value ) ) );
		if ( '' === $value ) {
			return '';
		}
		if ( preg_match( '/^(\d{4})-(\d{1,2})-(\d{1,2})$/', $value, $m ) ) {
			list( , $y, $mo, $d ) = $m;
		} elseif ( preg_match( '/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/', $value, $m ) ) {
			list( , $mo, $d, $y ) = $m;
		} else {
			return '';
		}
		return checkdate( (int) $mo, (int) $d, (int) $y ) ? sprintf( '%04d-%02d-%02d', $y, $mo, $d ) : '';
	}

	/**
	 * Filter rules:
	 *   eq    => array( array( field_id, value ), ... )        every one must match (AND)
	 *   any   => array( array( field_id, value ), ... )        at least one must match (OR)
	 *   range => array( array( field_id, from, to ), ... )     date range on a field, Y-m-d
	 *   created_from / created_to                              range on the entry created date
	 * Empty values are ignored, like a Formidable View does with a blank [get param].
	 */
	private static function args_from_request() {
		$batch = isset( $_POST['batch_size'] ) ? absint( $_POST['batch_size'] ) : 1000;
		$rules = array( 'eq' => array(), 'any' => array(), 'range' => array(), 'created_from' => '', 'created_to' => '' );

		// Rules sent by the shortcode (read from the page URL).
		$posted = isset( $_POST['rules'] ) ? json_decode( wp_unslash( $_POST['rules'] ), true ) : null;
		if ( is_array( $posted ) ) {
			foreach ( array( 'eq', 'any' ) as $type ) {
				foreach ( (array) ( isset( $posted[ $type ] ) ? $posted[ $type ] : array() ) as $r ) {
					$fid = isset( $r[0] ) ? absint( $r[0] ) : 0;
					$val = isset( $r[1] ) ? trim( sanitize_text_field( (string) $r[1] ) ) : '';
					if ( $fid && '' !== $val ) {
						$rules[ $type ][] = array( $fid, isset( $r[2] ) && 'date' === $r[2] ? self::clean_date( $val ) : $val );
					}
				}
			}
			foreach ( (array) ( isset( $posted['range'] ) ? $posted['range'] : array() ) as $r ) {
				$fid  = isset( $r[0] ) ? absint( $r[0] ) : 0;
				$from = isset( $r[1] ) ? self::clean_date( $r[1] ) : '';
				$to   = isset( $r[2] ) ? self::clean_date( $r[2] ) : '';
				if ( $fid && ( $from || $to ) ) {
					$rules['range'][] = array( $fid, $from, $to );
				}
			}
		}

		// Fields from the admin page.
		$ff = isset( $_POST['filter_field'] ) ? absint( $_POST['filter_field'] ) : 0;
		$fv = isset( $_POST['filter_value'] ) ? trim( sanitize_text_field( wp_unslash( $_POST['filter_value'] ) ) ) : '';
		if ( $ff && '' !== $fv ) {
			$rules['eq'][] = array( $ff, $fv );
		}
		$df   = isset( $_POST['date_field'] ) ? absint( $_POST['date_field'] ) : 0;
		$from = isset( $_POST['date_from'] ) ? self::clean_date( $_POST['date_from'] ) : '';
		$to   = isset( $_POST['date_to'] ) ? self::clean_date( $_POST['date_to'] ) : '';
		if ( $from || $to ) {
			if ( $df ) {
				$rules['range'][] = array( $df, $from, $to );
			} else {
				$rules['created_from'] = $from;
				$rules['created_to']   = $to;
			}
		}

		// Drop eq/any rules whose date value failed to parse.
		foreach ( array( 'eq', 'any' ) as $type ) {
			$rules[ $type ] = array_values( array_filter( $rules[ $type ], function ( $r ) { return '' !== $r[1]; } ) );
		}

		return array(
			'form_id'    => isset( $_POST['form_id'] ) ? absint( $_POST['form_id'] ) : 0,
			'batch_size' => max( 100, min( 5000, $batch ? $batch : 1000 ) ),
			'rules'      => $rules,
		);
	}

	/* ------------------------------------------------------------------ *
	 * Queries
	 * ------------------------------------------------------------------ */

	/** Returns array( $join_sql, $where_sql ) for the entry filters. */
	private static function sql_parts( $a ) {
		global $wpdb;
		$metas = $wpdb->prefix . 'frm_item_metas';
		$r     = $a['rules'];
		$where = $wpdb->prepare( 'it.form_id = %d AND it.is_draft = 0', $a['form_id'] );
		$has   = "EXISTS (SELECT 1 FROM {$metas} m WHERE m.item_id = it.id AND m.field_id = %d AND ";

		foreach ( $r['eq'] as $rule ) {
			$where .= ' AND ' . $wpdb->prepare( $has . 'm.meta_value = %s)', $rule[0], $rule[1] ); // phpcs:ignore
		}

		if ( $r['any'] ) {
			$or = array();
			foreach ( $r['any'] as $rule ) {
				$or[] = $wpdb->prepare( $has . 'm.meta_value = %s)', $rule[0], $rule[1] ); // phpcs:ignore
			}
			$where .= ' AND (' . implode( ' OR ', $or ) . ')';
		}

		// Formidable stores date fields as Y-m-d, so string comparison works.
		foreach ( $r['range'] as $rule ) {
			list( $fid, $from, $to ) = $rule;
			$cond = array();
			if ( $from ) {
				$cond[] = $wpdb->prepare( 'm.meta_value >= %s', $from );
			}
			if ( $to ) {
				$cond[] = $wpdb->prepare( 'm.meta_value <= %s', $to );
			}
			$where .= ' AND ' . $wpdb->prepare( $has, $fid ) . implode( ' AND ', $cond ) . ')'; // phpcs:ignore
		}

		// Entry created date, stored in GMT.
		if ( $r['created_from'] ) {
			$where .= $wpdb->prepare( ' AND it.created_at >= %s', get_gmt_from_date( $r['created_from'] . ' 00:00:00' ) );
		}
		if ( $r['created_to'] ) {
			$where .= $wpdb->prepare( ' AND it.created_at <= %s', get_gmt_from_date( $r['created_to'] . ' 23:59:59' ) );
		}

		return array( '', $where );
	}

	private static function count_entries( $a ) {
		global $wpdb;
		list( $join, $where ) = self::sql_parts( $a );
		return (int) $wpdb->get_var( "SELECT COUNT(DISTINCT it.id) FROM {$wpdb->prefix}frm_items it {$join} WHERE {$where}" ); // phpcs:ignore
	}

	private static function fields( $form_id ) {
		$out = array();
		foreach ( (array) FrmField::get_all_for_form( $form_id ) as $field ) {
			if ( ! in_array( $field->type, self::SKIP_TYPES, true ) ) {
				$out[] = $field;
			}
		}
		return $out;
	}

	/* ------------------------------------------------------------------ *
	 * Value formatting
	 * ------------------------------------------------------------------ */

	private static function flatten( $value ) {
		if ( ! is_array( $value ) ) {
			return (string) $value;
		}
		$parts = array();
		array_walk_recursive(
			$value,
			function ( $v ) use ( &$parts ) {
				if ( '' !== (string) $v ) {
					$parts[] = (string) $v;
				}
			}
		);
		return implode( ', ', $parts );
	}

	private static function format_value( $raw, $field ) {
		static $cache = array();
		$value = maybe_unserialize( $raw );

		switch ( $field->type ) {
			case 'user_id':
				$user  = is_numeric( $value ) ? get_userdata( (int) $value ) : false;
				$value = $user ? $user->display_name : $value;
				break;

			case 'file':
				$urls = array();
				foreach ( (array) $value as $id ) {
					$url    = is_numeric( $id ) ? wp_get_attachment_url( (int) $id ) : '';
					$urls[] = $url ? $url : $id;
				}
				$value = $urls;
				break;

			case 'data': // Dynamic field: stored value is the linked entry ID.
				$key = $field->id . '|' . ( is_array( $value ) ? wp_json_encode( $value ) : $value );
				if ( ! isset( $cache[ $key ] ) ) {
					$cache[ $key ] = $value;
					if ( class_exists( 'FrmEntriesHelper' ) ) {
						try {
							$cache[ $key ] = wp_strip_all_tags(
								FrmEntriesHelper::display_value(
									$value,
									$field,
									array( 'type' => 'data', 'show_icon' => false, 'truncate' => false, 'sep' => ', ' )
								)
							);
						} catch ( Throwable $e ) {
							$cache[ $key ] = $value;
						}
					}
				}
				$value = $cache[ $key ];
				break;
		}

		$value = self::flatten( $value );

		// Stop Excel from running cell contents as formulas.
		if ( '' !== $value && in_array( $value[0], array( '=', '+', '-', '@' ), true ) && ! is_numeric( $value ) ) {
			$value = "'" . $value;
		}
		return $value;
	}

	/* ------------------------------------------------------------------ *
	 * AJAX: start, batch, download
	 * ------------------------------------------------------------------ */

	public static function ajax_start() {
		check_ajax_referer( self::NONCE );
		if ( ! self::can() ) {
			wp_send_json_error( 'You are not allowed to export entries.', 403 );
		}
		if ( ! self::formidable_ready() ) {
			wp_send_json_error( 'Formidable Forms is not active.' );
		}

		$args = self::args_from_request();
		if ( ! $args['form_id'] || ! FrmForm::getOne( $args['form_id'] ) ) {
			wp_send_json_error( 'Pick a valid form.' );
		}

		$dir = self::dir();
		self::cleanup( $dir );

		$job    = strtolower( wp_generate_password( 24, false, false ) );
		$file   = $dir . '/' . $job . '.csv';
		$fields = self::fields( $args['form_id'] );

		$header = array( 'Entry ID', 'Created', 'Updated' );
		foreach ( $fields as $field ) {
			$header[] = $field->name;
		}

		$fh = fopen( $file, 'w' );
		if ( ! $fh ) {
			wp_send_json_error( 'Could not create the export file.' );
		}
		fwrite( $fh, "\xEF\xBB\xBF" ); // UTF-8 BOM so Excel reads accents and symbols correctly.
		fputcsv( $fh, $header );
		fclose( $fh );
		clearstatcache( true, $file );

		$total = self::count_entries( $args );

		set_transient(
			'bryanveloso_bx_' . $job,
			array(
				'args'    => $args,
				'user'    => get_current_user_id(),
				'file'    => $file,
				'last_id' => 0,
				'done'    => 0,
				'total'   => $total,
				'bytes'   => filesize( $file ),
			),
			DAY_IN_SECONDS
		);

		wp_send_json_success( array( 'job' => $job, 'total' => $total ) );
	}

	private static function get_job( $job ) {
		$job   = preg_replace( '/[^a-z0-9]/', '', strtolower( (string) $job ) );
		$state = $job ? get_transient( 'bryanveloso_bx_' . $job ) : false;
		if ( ! $state || (int) $state['user'] !== get_current_user_id() ) {
			return array( $job, false );
		}
		return array( $job, $state );
	}

	public static function ajax_batch() {
		global $wpdb;
		check_ajax_referer( self::NONCE );
		if ( ! self::can() ) {
			wp_send_json_error( 'You are not allowed to export entries.', 403 );
		}

		list( $job, $state ) = self::get_job( isset( $_POST['job'] ) ? sanitize_text_field( wp_unslash( $_POST['job'] ) ) : '' );
		if ( ! $state || ! file_exists( $state['file'] ) ) {
			wp_send_json_error( 'Export job not found or expired. Start again.' );
		}

		$a = $state['args'];
		list( $join, $where ) = self::sql_parts( $a );
		$where .= $wpdb->prepare( ' AND it.id > %d', $state['last_id'] );

		$ids = array_map(
			'intval',
			$wpdb->get_col( "SELECT DISTINCT it.id FROM {$wpdb->prefix}frm_items it {$join} WHERE {$where} ORDER BY it.id ASC LIMIT " . (int) $a['batch_size'] ) // phpcs:ignore
		);

		// If an earlier attempt of this batch wrote rows but the response was lost, drop those rows before retrying.
		clearstatcache( true, $state['file'] );
		$fh = fopen( $state['file'], 'r+' );
		if ( ! $fh ) {
			wp_send_json_error( 'Could not open the export file.' );
		}
		if ( filesize( $state['file'] ) > $state['bytes'] ) {
			ftruncate( $fh, $state['bytes'] );
		}
		fseek( $fh, 0, SEEK_END );

		if ( $ids ) {
			$in    = implode( ',', $ids );
			$items = $wpdb->get_results( "SELECT id, created_at, updated_at FROM {$wpdb->prefix}frm_items WHERE id IN ({$in}) ORDER BY id ASC" ); // phpcs:ignore
			$rows  = $wpdb->get_results( "SELECT item_id, field_id, meta_value FROM {$wpdb->prefix}frm_item_metas WHERE item_id IN ({$in})" ); // phpcs:ignore

			$metas = array();
			foreach ( $rows as $row ) {
				$metas[ $row->item_id ][ $row->field_id ] = $row->meta_value;
			}
			unset( $rows );

			$fields = self::fields( $a['form_id'] );

			foreach ( $items as $item ) {
				$line = array(
					$item->id,
					get_date_from_gmt( $item->created_at, 'Y-m-d H:i:s' ),
					get_date_from_gmt( $item->updated_at, 'Y-m-d H:i:s' ),
				);
				foreach ( $fields as $field ) {
					$raw    = isset( $metas[ $item->id ][ $field->id ] ) ? $metas[ $item->id ][ $field->id ] : '';
					$line[] = '' === $raw ? '' : self::format_value( $raw, $field );
				}
				fputcsv( $fh, $line );
			}

			$state['last_id'] = end( $ids );
			$state['done']   += count( $ids );
		}

		fflush( $fh );
		fclose( $fh );
		clearstatcache( true, $state['file'] );
		$state['bytes'] = filesize( $state['file'] );
		set_transient( 'bryanveloso_bx_' . $job, $state, DAY_IN_SECONDS );

		$finished = count( $ids ) < (int) $a['batch_size'];
		$response = array(
			'done'     => $state['done'],
			'total'    => $state['total'],
			'finished' => $finished,
		);
		if ( $finished ) {
			$response['url'] = add_query_arg(
				array(
					'action'   => 'bryanveloso_bx_download',
					'job'      => $job,
					'_wpnonce' => wp_create_nonce( 'bryanveloso_bx_dl_' . $job ),
				),
				admin_url( 'admin-post.php' )
			);
		}
		wp_send_json_success( $response );
	}

	/** Cancel a running export: remove its partial file and job record. */
	public static function ajax_cancel() {
		check_ajax_referer( self::NONCE );
		if ( ! self::can() ) {
			wp_send_json_error( 'You are not allowed to export entries.', 403 );
		}
		list( $job, $state ) = self::get_job( isset( $_POST['job'] ) ? sanitize_text_field( wp_unslash( $_POST['job'] ) ) : '' );
		if ( $state ) {
			if ( file_exists( $state['file'] ) ) {
				@unlink( $state['file'] );
			}
			delete_transient( 'bryanveloso_bx_' . $job );
		}
		wp_send_json_success();
	}

	public static function download() {
		$job = isset( $_GET['job'] ) ? sanitize_text_field( wp_unslash( $_GET['job'] ) ) : '';
		check_admin_referer( 'bryanveloso_bx_dl_' . $job );
		if ( ! self::can() ) {
			wp_die( 'You are not allowed to export entries.', 403 );
		}

		list( $job, $state ) = self::get_job( $job );
		if ( ! $state || ! file_exists( $state['file'] ) ) {
			wp_die( 'Export file not found or expired.' );
		}

		$form  = FrmForm::getOne( $state['args']['form_id'] );
		$name  = sanitize_file_name( ( $form ? $form->name : 'entries' ) . '-' . wp_date( 'Y-m-d-His' ) . '.csv' );
		$bytes = filesize( $state['file'] );

		nocache_headers();
		header( 'Content-Type: text/csv; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename="' . $name . '"' );
		header( 'Content-Length: ' . $bytes );
		while ( ob_get_level() ) {
			ob_end_clean();
		}
		readfile( $state['file'] );

		@unlink( $state['file'] );
		delete_transient( 'bryanveloso_bx_' . $job );
		exit;
	}

	/* ------------------------------------------------------------------ *
	 * UI: admin page and shortcode
	 * ------------------------------------------------------------------ */

	public static function menu() {
		if ( self::formidable_ready() ) {
			add_submenu_page( 'formidable', 'Batched Export', 'Batched Export', 'frm_view_entries', 'bryanveloso-batch-export', array( __CLASS__, 'admin_page' ) );
		} else {
			add_management_page( 'Batched Export', 'Batched Export', 'manage_options', 'bryanveloso-batch-export', array( __CLASS__, 'admin_page' ) );
		}
	}

	public static function admin_page() {
		echo '<div class="wrap"><h1>Batched Formidable Export</h1>';
		if ( ! self::formidable_ready() ) {
			echo '<p>Formidable Forms is not active.</p></div>';
			return;
		}
		echo '<p>Exports entries to one CSV file, a batch at a time, so large forms do not time out. Keep this tab open until the download starts.</p>';
		echo self::render( array() ); // phpcs:ignore
		echo '</div>';
	}

	/**
	 * Shortcode that exports with the same URL parameters a Formidable View filters on.
	 *
	 * Example:
	 * [bryanveloso_batch_export form_id="55" match="1139:pos,1097:branch" match_any="1112:salesdate:date,1113:encodeddate:date" range="1112:startdate:enddate" label="Export to Excel"]
	 *
	 * form_id    Form to export.
	 * match      field_id:url_param pairs that must ALL match. Add :date if the value is a date.
	 * match_any  field_id:url_param pairs where at least ONE must match (an Or group in the View).
	 * range      field_id:from_param:to_param date ranges (inclusive).
	 * require    Optional comma list of URL params that must be set before exporting, e.g. "branch".
	 * label      Button text.
	 *
	 * Blank URL params are ignored, the same way the View ignores a blank [get param].
	 */
	public static function shortcode( $atts ) {
		if ( ! is_user_logged_in() || ! self::can() || ! self::formidable_ready() ) {
			return '';
		}
		$atts = shortcode_atts(
			array(
				'form_id'   => 0,
				'match'     => '',
				'match_any' => '',
				'range'     => '',
				'require'   => '',
				'label'     => 'Export to Excel',
			),
			$atts,
			'bryanveloso_batch_export'
		);
		return self::render( $atts );
	}

	/** "1139:pos,1112:salesdate:date" into array( array( 1139, 'pos', '' ), array( 1112, 'salesdate', 'date' ) ). */
	private static function parse_spec( $spec, $parts ) {
		$out = array();
		foreach ( array_filter( array_map( 'trim', explode( ',', (string) $spec ) ) ) as $item ) {
			$bits = array_map( 'trim', explode( ':', $item ) );
			$fid  = absint( $bits[0] );
			if ( ! $fid || count( $bits ) < $parts ) {
				continue;
			}
			$row = array( $fid );
			for ( $i = 1; $i < 3; $i++ ) {
				$row[] = isset( $bits[ $i ] ) ? sanitize_key( $bits[ $i ] ) : '';
			}
			$out[] = $row;
		}
		return $out;
	}

	private static function render( $atts ) {
		$atts = wp_parse_args(
			$atts,
			array(
				'form_id'   => 0,
				'match'     => '',
				'match_any' => '',
				'range'     => '',
				'require'   => '',
				'label'     => 'Export CSV',
			)
		);

		$form_id     = absint( $atts['form_id'] );
		$is_admin_ui = is_admin() && ! $form_id;
		$spec        = array(
			'eq'    => self::parse_spec( $atts['match'], 2 ),
			'any'   => self::parse_spec( $atts['match_any'], 2 ),
			'range' => self::parse_spec( $atts['range'], 3 ),
		);
		$require     = implode( ',', array_filter( array_map( 'sanitize_key', explode( ',', (string) $atts['require'] ) ) ) );

		ob_start();
		?>
		<div class="bryanveloso-bx"
			data-ajax="<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>"
			data-nonce="<?php echo esc_attr( wp_create_nonce( self::NONCE ) ); ?>"
			data-spec="<?php echo esc_attr( wp_json_encode( $spec ) ); ?>"
			data-require="<?php echo esc_attr( $require ); ?>">

			<?php if ( $form_id ) : ?>
				<input type="hidden" data-arg="form_id" value="<?php echo esc_attr( $form_id ); ?>">
			<?php else : ?>
				<p><label>Form<br>
					<select data-arg="form_id">
						<option value="">Select a form</option>
						<?php foreach ( (array) FrmForm::getAll( array( 'is_template' => 0, 'status' => 'published' ), 'name' ) as $form ) : ?>
							<option value="<?php echo esc_attr( $form->id ); ?>"><?php echo esc_html( $form->name . ' (ID ' . $form->id . ')' ); ?></option>
						<?php endforeach; ?>
					</select></label></p>
			<?php endif; ?>

			<?php if ( $is_admin_ui ) : ?>
				<p><label>Filter field ID (optional)<br><input type="number" min="0" data-arg="filter_field"></label></p>
				<p><label>Filter value<br><input type="text" data-arg="filter_value"></label></p>
				<p><label>Date field ID (blank = entry created date)<br><input type="number" min="0" data-arg="date_field"></label></p>
				<p><label>From<br><input type="date" data-arg="date_from"></label>
				<label>To<br><input type="date" data-arg="date_to"></label></p>
				<p><label>Batch size<br><input type="number" min="100" max="5000" step="100" value="1000" data-arg="batch_size"></label></p>
			<?php endif; ?>

			<p>
				<button type="button" class="button button-primary bryanveloso-bx-go"><?php echo esc_html( $atts['label'] ); ?></button>
				<span class="bryanveloso-bx-status"></span>
			</p>
		</div>
		<?php
		self::print_script();
		return ob_get_clean();
	}

	private static function print_script() {
		static $printed = false;
		if ( $printed ) {
			return;
		}
		$printed = true;
		?>
		<style>
		.bryanveloso-bx-go.bryanveloso-bx-go {
			background: #dd3333; border: 1px solid #dd3333; color: #fff; border-radius: 4px;
			padding: 10px 20px; font-size: 15px; line-height: 1.2; height: auto; cursor: pointer;
			text-shadow: none; box-shadow: none; transition: background .15s ease;
		}
		.bryanveloso-bx-go.bryanveloso-bx-go:hover, .bryanveloso-bx-go.bryanveloso-bx-go:focus { background: #b82222; border-color: #b82222; color: #fff; }
		.bryanveloso-bx-go.bryanveloso-bx-go:disabled { opacity: .6; cursor: default; }
		.bryanveloso-bx-status { margin-left: 10px; font-weight: 600; color: #dd3333; }

		.bryanveloso-bx-overlay {
			position: fixed; inset: 0; z-index: 100000; background: rgba(0, 0, 0, .6);
			display: flex; align-items: center; justify-content: center; padding: 20px;
			opacity: 0; transition: opacity .2s ease;
			font-family: roboto, -apple-system, "Segoe UI", Arial, sans-serif;
		}
		.bryanveloso-bx-overlay.is-open { opacity: 1; }
		.bryanveloso-bx-modal {
			background: #fff; color: #222; width: 100%; max-width: 460px; border-radius: 6px; overflow: hidden;
			box-shadow: 0 20px 50px rgba(0, 0, 0, .35); transform: translateY(10px); transition: transform .2s ease;
		}
		.bryanveloso-bx-overlay.is-open .bryanveloso-bx-modal { transform: none; }
		.bryanveloso-bx-modal__head {
			background: #000; color: #fff; padding: 14px 20px; border-bottom: 3px solid #dd3333;
			font-family: "news cycle", "arial narrow bold", roboto, sans-serif; font-weight: 700; font-size: 18px;
			letter-spacing: .3px; margin: 0;
		}
		.bryanveloso-bx-modal__body { padding: 22px 20px 8px; }
		.bryanveloso-bx-modal__msg { margin: 0 0 14px; font-size: 15px; line-height: 1.45; }
		.bryanveloso-bx-track { height: 14px; background: #eee; border-radius: 7px; overflow: hidden; }
		.bryanveloso-bx-fill {
			height: 100%; width: 0; background: #dd3333; border-radius: 7px; transition: width .35s ease;
			background-image: linear-gradient(45deg, rgba(255,255,255,.18) 25%, transparent 25%, transparent 50%, rgba(255,255,255,.18) 50%, rgba(255,255,255,.18) 75%, transparent 75%, transparent);
			background-size: 20px 20px; animation: bryanveloso-bx-stripes 1s linear infinite;
		}
		.bryanveloso-bx-overlay.is-done .bryanveloso-bx-fill, .bryanveloso-bx-overlay.is-error .bryanveloso-bx-fill { animation: none; background-image: none; }
		.bryanveloso-bx-overlay.is-error .bryanveloso-bx-fill { background: #222; }
		@keyframes bryanveloso-bx-stripes { from { background-position: 0 0; } to { background-position: 20px 0; } }
		.bryanveloso-bx-meta { display: flex; justify-content: space-between; margin-top: 8px; font-size: 13px; color: #555; }
		.bryanveloso-bx-pct { font-weight: 700; color: #000; }
		.bryanveloso-bx-note { margin: 14px 0 0; font-size: 13px; color: #777; }
		.bryanveloso-bx-modal__foot { padding: 16px 20px 20px; text-align: right; }
		.bryanveloso-bx-btn {
			font: inherit; font-size: 15px; padding: 9px 20px; border-radius: 4px; cursor: pointer;
			border: 1px solid #dd3333; transition: background .15s ease, color .15s ease;
		}
		.bryanveloso-bx-btn--ghost { background: #fff; color: #dd3333; }
		.bryanveloso-bx-btn--ghost:hover { background: #dd3333; color: #fff; }
		.bryanveloso-bx-btn--solid { background: #dd3333; color: #fff; }
		.bryanveloso-bx-btn--solid:hover { background: #b82222; border-color: #b82222; }
		.bryanveloso-bx-btn:disabled { opacity: .6; cursor: default; }
		</style>
		<script>
		(function () {
			function ready(fn) { document.readyState !== 'loading' ? fn() : document.addEventListener('DOMContentLoaded', fn); }
			function fmt(n) { return Number(n || 0).toLocaleString(); }

			/* ---------- Modal ---------- */
			function Modal() {
				var o = document.createElement('div');
				o.className = 'bryanveloso-bx-overlay';
				o.setAttribute('role', 'dialog');
				o.setAttribute('aria-modal', 'true');
				o.setAttribute('aria-labelledby', 'bryanveloso-bx-title');
				o.innerHTML =
					'<div class="bryanveloso-bx-modal">' +
						'<h2 class="bryanveloso-bx-modal__head" id="bryanveloso-bx-title">Exporting to Excel</h2>' +
						'<div class="bryanveloso-bx-modal__body">' +
							'<p class="bryanveloso-bx-modal__msg" aria-live="polite">Counting entries...</p>' +
							'<div class="bryanveloso-bx-track"><div class="bryanveloso-bx-fill"></div></div>' +
							'<div class="bryanveloso-bx-meta"><span class="bryanveloso-bx-count"></span><span class="bryanveloso-bx-pct"></span></div>' +
							'<p class="bryanveloso-bx-note">Keep this tab open until the download starts.</p>' +
						'</div>' +
						'<div class="bryanveloso-bx-modal__foot"><button type="button" class="bryanveloso-bx-btn bryanveloso-bx-btn--ghost">Cancel</button></div>' +
					'</div>';
				document.body.appendChild(o);
				requestAnimationFrame(function () { o.classList.add('is-open'); });

				var self = this;
				this.el = o;
				this.title = o.querySelector('.bryanveloso-bx-modal__head');
				this.msg = o.querySelector('.bryanveloso-bx-modal__msg');
				this.fill = o.querySelector('.bryanveloso-bx-fill');
				this.count = o.querySelector('.bryanveloso-bx-count');
				this.pct = o.querySelector('.bryanveloso-bx-pct');
				this.note = o.querySelector('.bryanveloso-bx-note');
				this.btn = o.querySelector('.bryanveloso-bx-btn');
				this.onCancel = null;
				this.btn.addEventListener('click', function () {
					if (self.state === 'running' && self.onCancel) { self.onCancel(); } else { self.close(); }
				});
				this.state = 'running';
				this.btn.focus();
			}
			Modal.prototype.progress = function (done, total) {
				var p = total ? Math.min(100, Math.round(done / total * 100)) : 0;
				this.fill.style.width = p + '%';
				this.pct.textContent = p + '%';
				this.count.textContent = fmt(done) + ' of ' + fmt(total) + ' entries';
				this.msg.textContent = 'Exporting entries in batches...';
			};
			Modal.prototype.finish = function (title, text, kind) {
				this.state = 'finished';
				this.el.classList.add(kind === 'error' ? 'is-error' : 'is-done');
				this.title.textContent = title;
				this.msg.textContent = text;
				this.note.style.display = 'none';
				if (kind !== 'error') { this.fill.style.width = '100%'; this.pct.textContent = '100%'; }
				this.btn.textContent = 'Close';
				this.btn.disabled = false;
				this.btn.className = 'bryanveloso-bx-btn bryanveloso-bx-btn--solid';
				this.btn.focus();
			};
			Modal.prototype.close = function () {
				var o = this.el;
				o.classList.remove('is-open');
				setTimeout(function () { if (o.parentNode) o.parentNode.removeChild(o); }, 200);
			};

			/* ---------- Export flow ---------- */
			ready(function () {
				document.querySelectorAll('.bryanveloso-bx').forEach(function (box) {
					if (box.dataset.bound) return;
					box.dataset.bound = '1';

					var btn = box.querySelector('.bryanveloso-bx-go');
					var status = box.querySelector('.bryanveloso-bx-status');

					function post(data) {
						var fd = new FormData();
						fd.append('_ajax_nonce', box.dataset.nonce);
						Object.keys(data).forEach(function (k) { fd.append(k, data[k]); });
						return fetch(box.dataset.ajax, { method: 'POST', body: fd, credentials: 'same-origin' })
							.then(function (r) { return r.json(); })
							.then(function (j) {
								if (!j || !j.success) throw new Error((j && j.data) || 'Request failed');
								return j.data;
							});
					}

					btn.addEventListener('click', function () {
						var data = { action: 'bryanveloso_bx_start' };
						box.querySelectorAll('[data-arg]').forEach(function (el) { data[el.dataset.arg] = el.value; });
						status.textContent = '';

						if (!data.form_id) { status.textContent = 'Select a form first.'; return; }

						// Read the same URL parameters the View filters on.
						var q = new URLSearchParams(window.location.search);
						function p(name) { return (q.get(name) || '').trim(); }
						var missing = (box.dataset.require || '').split(',').filter(function (n) { return n && !p(n); });
						if (missing.length) {
							status.textContent = 'Set the ' + missing.join(', ') + ' filter first, click Search, then export.';
							return;
						}
						var spec = {};
						try { spec = JSON.parse(box.dataset.spec || '{}'); } catch (e) {}
						var rules = { eq: [], any: [], range: [] };
						(spec.eq || []).forEach(function (r) { if (p(r[1])) rules.eq.push([r[0], p(r[1]), r[2]]); });
						(spec.any || []).forEach(function (r) { if (p(r[1])) rules.any.push([r[0], p(r[1]), r[2]]); });
						(spec.range || []).forEach(function (r) { if (p(r[1]) || p(r[2])) rules.range.push([r[0], p(r[1]), p(r[2])]); });
						data.rules = JSON.stringify(rules);

						var modal = new Modal();
						var job = null, cancelled = false;

						function leaveWarning(e) { e.preventDefault(); e.returnValue = ''; }
						function stopGuard() { window.removeEventListener('beforeunload', leaveWarning); btn.disabled = false; }
						window.addEventListener('beforeunload', leaveWarning);
						btn.disabled = true;

						modal.onCancel = function () {
							cancelled = true;
							modal.btn.disabled = true;
							modal.msg.textContent = 'Cancelling...';
							(job ? post({ action: 'bryanveloso_bx_cancel', job: job }) : Promise.resolve()).catch(function () {}).then(function () {
								stopGuard();
								modal.finish('Export cancelled', 'Nothing was downloaded.', 'error');
							});
						};

						function batch(total, tries) {
							if (cancelled) return;
							return post({ action: 'bryanveloso_bx_batch', job: job }).then(function (r) {
								if (cancelled) return;
								modal.progress(r.done, total);
								if (r.finished) {
									stopGuard();
									modal.finish('Export complete', fmt(r.done) + ' entries exported. Your download is starting.', 'done');
									window.location.href = r.url;
									return;
								}
								return batch(total, 0);
							}, function (err) {
								if (cancelled) return;
								if (tries < 3) {
									modal.msg.textContent = 'Connection hiccup. Retrying batch (' + (tries + 1) + ' of 3)...';
									return new Promise(function (res) { setTimeout(res, 2000); }).then(function () { return batch(total, tries + 1); });
								}
								throw err;
							});
						}

						post(data).then(function (s) {
							if (cancelled) return;
							job = s.job;
							if (!s.total) {
								stopGuard();
								post({ action: 'bryanveloso_bx_cancel', job: job }).catch(function () {});
								modal.finish('Nothing to export', 'No entries match these filters.', 'error');
								return;
							}
							modal.progress(0, s.total);
							return batch(s.total, 0);
						}).catch(function (err) {
							if (cancelled) return;
							stopGuard();
							modal.finish('Export failed', err.message, 'error');
						});
					});
				});
			});
		})();
		</script>
		<?php
	}
}

BRYANVELOSO_Batched_Export::init();

If you run into a field type that does not export nicely, let me know in the comments.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.