Search code examples
phpwordpressninja-forms

Ninja forms - how to show submitted data to the user on thank you page?


I have a Wordpress website and I am using Ninja Forms plugin for a simple form.

I am looking for a way to have a “thank you” page that will be showing a summary of users submission.

What I have managed so far is to have querystring in the "thank you" page (Ninja Forms redirect action) url with the key of the submitted form (e.g. https://mywebsite.com/thank-you/?key=24).

I know how to display data from the whole form (using form id), but I don't have a clue how to use this key to display data only from that particular submission.


Solution

  • Set the form's Redirect url to http://example.com/thank-you-page/?key={form:id}:{submission:sequence}

    The code extracts the form id and submission sequence. Then it gets the fields for that form, then it loops through the submissions for the form, looking for the passed submission sequence and displays it.

    This is very insecure code as it allows anyone view submissions.

    add_filter( 'the_content', 'dcwd_display_ninja_forms_submission', 11 );
    function dcwd_display_ninja_forms_submission( $content ) {
        if ( !is_page('thank-you-page') ) { return $content; }
    
        if ( array_key_exists( 'key', $_GET ) && preg_match( '/^(\d+):(\d+)/', $_GET['key'], $matches ) ) {
            ob_start();
    
            $form_id = $matches[1];
            $sub_id = $matches[2];
    
            $form_fields = Ninja_Forms()->form( $form_id )->get_fields();
            $key_to_fieldname = array();
            foreach ( $form_fields as $form_field ) {
                $key_to_fieldname[ $form_field->get_setting( 'key' ) ] = $form_field->get_setting( 'label' );
            }
            unset( $key_to_fieldname[ 'submit' ] );  // Do not need 'Submit' info as there won't be any data in it.
            //echo '<h2>Form Fields</h2><pre>', var_export( $key_to_fieldname, true ), '</pre>';
    
            $subs = Ninja_Forms()->form( $form_id )->get_subs();
            foreach ( $subs as $sub ) {
                if ( $sub_id == $sub->get_seq_num() ) {
                    echo '<style>table, th, td { border: 1px solid #ccc; border-collapse: collapse; } th, td { padding: 1em; } th { font-weight: bold; }</style>';
                    echo '<table><tr><th>', implode( '</th><th>', array_values( $key_to_fieldname ) ), '</th></tr>';
                    $values = $sub->get_field_values();
                    echo '<tr>';
                    foreach ( $key_to_fieldname as $key => $name ) {
                        if ( array_key_exists( $key, $values ) ) {
                            echo '<td>', $values[ $key ], '</td>';
                        }
                    }
                    echo '</tr></table>';
                    
                    return $content . ob_get_clean();
                }
            }
        }
    }