Passing Data to a Form

Guides Front-End Forms Passing Data to a Form

#Overview

In this guide we’ll learn how to retrieve a parameter from the URL, pass it to the form and use it in the Post Action “Update Target”. The final result will be that the form dynamically update a post based on the URL.

In this example, the form page URL should look like /my-form?profile_id=42.

#Passing Data

First, we retrieve the URL parameter using $_GET. Then, we pass our custom data during the form initialization by simply adding an argument to the acfe_form() settings array. Here, we’ll name it profile_id.

Note that when adding a custom argument you have to make sure it doesn’t already exists in the default parameter list, which can be found here.

// retrieve url parameter
$profile_id = (int) $_GET['profile_id'];

// make sure profile id exists
if($profile_id){
    
    // render form
    acfe_form(array(
        'name'       => 'my-form',
        'profile_id' => $profile_id
    ));

}

If you’re using the [acfe_form] shotcode to display the form, you can use the acfe/form/load_form hook (see documentation) to pass the custom data:

add_filter('acfe/form/load_form/form=my-form', 'my_form_settings');
function my_form_settings($form){

    // retrieve url parameter
    $profile_id = (int) $_GET['profile_id'];
    
    // Add Current User ID
    $form['profile_id'] = $profile_id;
    
    // Return
    return $form;
    
}

#Action Configuration

Now the data is passed to the form, we can use it anywhere in the Form UI using the Template Tag {form:profile_id}. In this example, we’ll use it as the Post Action “Update Target”, so the action will update the Post ID defined in the URL.

Dynamic Form

Add actions on form submission

#Retrieve Data in a Hook

Our custom data can also be retrieve in any Form hook using $form['profile_id']. Here is a usage example within the Post Validation Hook:

add_action('acfe/form/validate_post/form=my-form', 'my_form_validation', 10, 2);
function my_form_validation($form, $action){
    
    // retrieve profile id
    $profile_id = (int) $form['profile_id'];
    
    // add error if the profile id is 50
    if($profile_id === 50){
        acfe_add_validation_error('', 'Updating this profile is disallowed');
    }
    
}