Dynamic Default Value for the Checkbox Field

A field’s settings can be set dynamically when the form is rendered on the page – this is when the field data is “localized” to the page for use by the form.

Dynamic Field Settings

The checkbox field uses the default_value setting to determine the checked/unchecked state of the checkbox field. This is different than the textbox field, which uses the default_value setting to set the value of the field, where as the checkbox field actually has two different value (a value for the checked state and a value for the unchecked state).

Related Filters

add_filter( ‘ninja_forms_localize_field’, ‘my_callback’ );

add_filter( ‘ninja_forms_localize_field_’ . $field_type, ‘my_callback’ );

Example

<?php
/**
* Change a field's settings when localized to the page.
* ninja_forms_localize_field_{$field_type}
*
* @param array $field [ id, settings => [ type, key, label, etc. ] ]
* @return array $field
*/
add_filter( 'ninja_forms_localize_field_checkbox', function( $field ){
// Change the default_value setting of the checkbox field.
$field[ 'settings' ][ 'default_value' ] = 'checked';
return $field;
});

Full Example

<?php
/**
* Wrap hooks for a specific form.
*
* @param int $form_id
*/
add_action( 'nf_get_form_id', function( $form_id ){
// Check for a specific Form ID.
if( 21 !== $form_id ) return;
/**
* Change a field's settings when localized to the page.
* ninja_forms_localize_field_{$field_type}
*
* @param array $field [ id, settings => [ type, key, label, etc. ] ]
* @return array $field
*/
add_filter( 'ninja_forms_localize_field_checkbox', function( $field ){
if( 'checkbox_1527003278102' == $field[ 'settings' ][ 'key' ] ){
// Change the default_value setting of the checkbox field.
$field[ 'settings' ][ 'default_value' ] = 'checked';
}
return $field;
});
} );