Support

Account

Home Forums Front-end Issues Dynamically Set A Front-End Form Field

Solved

Dynamically Set A Front-End Form Field

  • Hi guys,

    I really hope you guys can help me out. I have been bashing my head around how to get this right.

    I have a front-end form that I use to receive Candidate Applications.
    I have two custom post types – Vacancies and Candidates.

    On the Candidates custom post type I have created a number of fields (all work on the front-end form) – one of which is a text field called Vacancy Applied For. What I want is for this field to be dynamically populated with the specific vacancy that has been applied for.

    This is the code for registering the Candidate Application Form.

    // Register ACF Forms for Front-End
    // 1. Candidate Application Form
    
        //Defines the fields to display
        $fields = array(
            'field_5db9db36a28bf',	    // candidate first name
            'field_5e05d834dcb14',      // candidate last name
            'field_5db9db5da28c0',	    // candidate email
            'field_5db9dc8ca28c1',	    // candidate contact number
            'field_5dcc08f0a11b5',      // candidate gender
            'field_5dcc092ba11b6',      // candidate race
            'field_5dcc09e2a11b7',      // candidate nationality check
            'field_5dcc0a32a11b8',      // candidate nationality
            'field_5db9dd10a28c2',	    // candidate cv
            'field_5db9ddf5a28c4',      // candidate supporting docs
            'field_5dba152669aaf',      // candidate vacancy applied for
            'field_5dcc0f15030b6'       // candidate disclaimer
    
        );
    
        // Sets the ACF Form
        acf_register_form(
    
        // Defines all the settings associated with the ACF Form 
        array(
    
            /* (string) Unique identifier for the form. Defaults to 'acf-form' */
            'id' => 'acf-candidate-application-form',
    
            /* (int|string) The post ID to load data from and save data to. Defaults to the current post ID. 
            Can also be set to 'new_post' to create a new post on submit */
            'post_id' => new_post,
    
            /* (array) An array of post data used to create a post. See wp_insert_post for available parameters.
            The above 'post_id' setting must contain a value of 'new_post' */
            'new_post' => array(
                'post_type'		=> 'candidates',
                'post_status'	=> 'publish',
            ),
    
            /* (array) An array of field group IDs/keys to override the fields displayed in this form */
            'field_groups' => false,
    
            /* (array) An array of field IDs/keys to override the fields displayed in this form */
            'fields' => $fields,
    
            /* (boolean) Whether or not to show the post title text field. Defaults to false */
            'post_title' => false,
    
            /* (boolean) Whether or not to show the post content editor field. Defaults to false */
            'post_content' => false,
    
            /* (boolean) Whether or not to create a form element. Useful when a adding to an existing form. Defaults to true */
            'form' => true,
    
            /* (array) An array or HTML attributes for the form element */
            'form_attributes' => array(),
    
            /* (string) The URL to be redirected to after the form is submit. Defaults to the current URL with a GET parameter '?updated=true'.
            A special placeholder '%post_url%' will be converted to post's permalink (handy if creating a new post)
            A special placeholder '%post_id%' will be converted to post's ID (handy if creating a new post) */
            'return' => get_home_url('candidate-application-success'),
    
            /* (string) Extra HTML to add before the fields */
            'html_before_fields' => '<input type="text" id="field_5dba152669aaf" name="field_5dba152669aaf" value="test" style="display:none;">',
    
            /* (string) Extra HTML to add after the fields */
            'html_after_fields' => '',
    
            /* (string) The text displayed on the submit button */
            'submit_value' => __("Submit Application", 'acf'),
    
            /* (string) A message displayed above the form after being redirected. Can also be set to false for no message */
            'updated_message' => __("Application successfully submitted", 'acf'),
    
            /* (string) Determines where field labels are places in relation to fields. Defaults to 'top'. 
            Choices of 'top' (Above fields) or 'left' (Beside fields) */
            'label_placement' => 'left',
    
            /* (string) Determines where field instructions are places in relation to fields. Defaults to 'label'. 
            Choices of 'label' (Below labels) or 'field' (Below fields) */
            'instruction_placement' => 'field',
    
            /* (string) Determines element used to wrap a field. Defaults to 'div' 
            Choices of 'div', 'tr', 'td', 'ul', 'ol', 'dl' */
            'field_el' => 'div',
    
            /* (string) Whether to use the WP uploader or a basic input for image and file fields. Defaults to 'wp' 
            Choices of 'wp' or 'basic'. Added in v5.2.4 */
            'uploader' => 'basic',
    
            /* (boolean) Whether to include a hidden input field to capture non human form submission. Defaults to true. Added in v5.3.4 */
            'honeypot' => true,
    
            /* (string) HTML used to render the updated message. Added in v5.5.10 */
            'html_updated_message'	=> '<div id="message" class="updated"><p>%s</p></div>',
    
            /* (string) HTML used to render the submit button. Added in v5.5.10 */
            'html_submit_button'	=> '<input type="submit" class="acf-button button button-primary button-large" value="%s" />',
    
            /* (string) HTML used to render the submit button loading spinner. Added in v5.5.10 */
            'html_submit_spinner'	=> '<span class="acf-spinner"></span>',
    
            /* (boolean) Whether or not to sanitize all $_POST data with the wp_kses_post() function. Defaults to true. Added in v5.6.5 */
            'kses'	=> true
    
        )
    );
    

    This is the code I’m using on the page template where I am using the front-end form.

    <?php
    /**
     * Template Name: Candidate Application Form Page
     * Description: The template for displaying the Candidate Application Page.
     *
     */
    $vacancy = isset( $_GET['vacancy'] ) ? esc_attr( $_GET['vacancy'] ) : '';
    $vacancyurl = isset( $_GET['vacancyurl'] ) ? esc_attr( $_GET['vacancyurl'] ) : '';
    
    function my_pre_save_post( $post_id ) {
    
        // check if this is to be a new post
        if( $post_id != 'new_post' ) {
            return $post_id;
        }
        // Create a new post
        $post = array(
            'post_status'  => 'publish' ,
            'post_type'  => 'Candidates' ,
        );
    
        $post_id = wp_insert_post( $post );
    
        $field_key = "field_5dba152669aaf";
        $value = $vacancy;
        update_field( $field_key, $value, $post_id ); 
        return $post_id;
        echo $value;
    }
    
    add_filter('acf/pre_save_post' , 'my_pre_save_post', 10, 1 );
    
    acf_form_head();
    get_header();
    
    ?>
        
    
    	<div id="primary" class="content-area">
    		<div id="content" class="site-content" role="main">
                <div class="candidateformcontainer">
                
                    <?php /* The loop */ ?>
                    <?php while ( have_posts() ) : the_post(); ?>
                        <div>
                           <h1><?php echo get_the_title(); ?></h1>
                            <p>To proceed with submitting your application for <strong><?php echo $vacancy; ?></strong> complete the application form below.</p>
                        </div>
                        <?php 
    
                        acf_form('acf-candidate-application-form'); 
                            
                        ?>
    
                    <?php endwhile; ?>               
    
                </div>
    
    		</div><!-- #content -->
    	</div><!-- #primary -->
    
    <?php get_footer();
    
    // Omit Closing PHP Tags

    When I echo the $vacancy variable it is being passed to the page (I set it based on the button clicked on the Vacancies page. It just won’t pass into the field and save.

    I have also tried to use the code snippet from the Update Field page. This passes the $vacancy variable into the post when I click submit on my front-end form but I then have two posts that get created. One with all the values from the form (without the Vacancy Applied For field set to the $vacancy variable and a second post with no post data passed to it except the Vacancy Applied For field set to the $vacancy variable.

    This is the code (also placed on the page template)

    $post_data = array(
        'post_type'     => 'candidates',
        'post_status'   => 'publish'
    );
    $post_id = wp_insert_post( $post_data );
    
    // Save a basic text value.
    $field_key = "field_5dba152669aaf";
    $value = $vacancy;
    update_field( $field_key, $value, $post_id );

    Any help would be awesome! I’m stuck and its probably a silly mistake but I can’y figure it out.

  • Your acf/pre_save_post filter does not run before the form is submited, it is run after the form is submitted. Once the form is submitted any value you passed to the original page in $_GET is lost. It cannot be used to pre-populate a field.

    In addition to this, your filter will not even work as expected. Filters like acf/pre_save_post need to be in your functions.php file or in some other file that is always loaded. Your template file will not be loaded during the form submission.

    With that said, if you want to pre-populate a field you need to use an acf/prepare_field filter.

    
    add_fitler('acf/prepare_field/key=field_5dba152669aaf', 'populate_vacancy_applied_for');
    function populate_vacancy_applied_for($field) {
      // only on front end
      if (is_admin()) {
        return $field;
      }
      if (isset($_GET['vacancy'])) {
        $field['value'] = $_GET['vacancy'];
      }
      return $field;
    }
    
  • Adding the above snippet to my functions file just causes an internal server error.

    Any idea why? Nothing in console except error 500.

  • more than likely there’s a php error in it, I don’t test code I post here. I don’t see any errors but that does not mean I didn’t make a mistake. Try turning on wp debugging so you can see the real error https://codex.wordpress.org/WP_DEBUG

    and now that I said that I see the error, I typed ‘add_fitler’ instead of ‘add_filter’, but you should still have debugging on when doing dev work.

  • Done and it works! 🙂

    You are my hero! The error was coz of a typo on filter (typed it as fitler).

    Here is the tweaked code snippet just in case anyone else ever wants to achieve the same thing.

    function populate_vacancy_applied_for($field) {
      // only on front end
      if (is_admin()) {
        return $field;
      }
      if (isset($_GET['vacancy'])) {
        $field['value'] = $_GET['vacancy'];
      }
      return $field;
    }
    
    add_filter('acf/prepare_field/key=field_5dba152669aaf', 'populate_vacancy_applied_for');
Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Dynamically Set A Front-End Form Field’ is closed to new replies.