Contact Form 7 and FPDF

I use the Contact Form 7 plug-in regularly in advanced ways. I often use the wpcf7_before_send_mail hook to undertake some customised processing of the form data. When I do so, it’s usually in conjunction with the skip_mail: on setting added to the Contact Form additional setting tab if I don’t want Contact Form 7 to send any emails.

Recently I wanted the function servicing the wpcf7_before_send_mail hook to pre-fill a PDF form before an immediate download of it to the user’s web browser. Despite having correct PHP code to do so, my functionality did not work.

Using Chrome developer tools, specifically the console and network tools, I was able to track the issue down to the reliance of Contact Form 7 on JavaScript and AJAX to do what it does. The CF7 client-side event handler was “hijacking” and re-directing my attempt to output a PDF.

The cleanest solution was to revert to server-side CF7 functionality instead of AJAX by implementing the following line of code which causes the CF7 JavaScript, and hence the DOM event handlers, not to be loaded.

add_filter( 'wpcf7_load_js', '__return_false' );

My code (below) then works fine in the wpcf7_before_send_mail hook function.

// $template_filename is the server-side filename of the empty PDF Form file
$pdf = new FPDM( $template_filename );
//  Populate the $fields array here
//  $fields['PDF form control name'] = value;
$pdf->Load( $fields, false );

// Clear headers and output PDF to browser
while ( ob_get_level() ) {
$pdf->Output( 'D', 'Monthly Report.pdf' );

Leave a Reply

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