Purpose
The wr_form_factory_modify_form_fields filter allows you to dynamically modify or pre-fill form fields during the creation of a form. This is particularly useful for setting default values, applying custom logic, or integrating external data sources like JWT tokens.
Usage
add_filter( "wr_form_factory_modify_form_fields", array( $this, "pre_fill_form" ), 10, 2 );
Parameters
$fields (array)
: An array of form field objects. Each field can be modified individually.$form (Form)
: The form object being constructed.
Use Case
This filter is useful when: • You need to set default values for specific fields dynamically (e.g., based on user data or tokens). • External data (e.g., from a JWT token) needs to prefill specific fields in the form.
Implementation Example
The following example populates the email field in a registration form using an email address extracted from a JWT token:
add_filter( "wr_form_factory_modify_form_fields", array( $this, "pre_fill_form" ), 10, 2 );
/**
* Prefill the email field in the registration form using a JWT token.
*
* @param array $fields
* @param Form $form
* @return array
*/
public function pre_fill_form( array $fields, Form $form ): array {
// Check if the form matches the registration form and a JWT token is provided
if ( $form->get_identifier() === 'form_identifier' && isset( $_POST['GET']["jwt"] ) ) {
// Decode the JWT token to extract user data
$data = ( Token::get_instance() )->decode_jwt( $_POST['GET']["jwt"] );
// Iterate through the form fields and set the email value
foreach ( $fields as $field ) {
if ( $field->get_identifier() === "email" ) {
$field->set_value( $data['email'] ); // Prefill the email field
}
}
}
return $fields; /
}