From 96ea490b8140a69aacc11b74c94afc42f887f4e6 Mon Sep 17 00:00:00 2001 From: Scott Kingsley Clark Date: Sat, 23 Mar 2024 09:21:57 -0500 Subject: [PATCH] Add support for setting default values when a field is empty in a form --- classes/PodsField.php | 22 ++++++++++++++++++---- src/Pods/Admin/Config/Field.php | 11 +++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/classes/PodsField.php b/classes/PodsField.php index 3336f0f4a3..471ff74bbd 100644 --- a/classes/PodsField.php +++ b/classes/PodsField.php @@ -456,10 +456,24 @@ public function build_dfv_field_data( $args ) { $attributes = $this->build_dfv_field_attributes( $attributes, $args ); $attributes = array_map( 'esc_attr', $attributes ); - $default_value = ''; + $field_value = isset( $args->value ) ? $args->value : null; - if ( 'multi' === pods_v( $args->type . '_format_type' ) ) { - $default_value = []; + if ( empty( $field_value ) ) { + $default_value = ''; + + $is_multi = 'multi' === pods_v( $args->type . '_format_type', 'single' ); + + if ( $is_multi ) { + $default_value = []; + } + + if ( null === $field_value || 1 === (int) pods_v( 'default_empty_fields', $options, 0 ) ) { + $field_value = PodsForm::default_value( $default_value, $args->type, pods_v( 'name', $options, $args->name ), $options, $args->pod, $args->id ); + + if ( $is_multi ) { + $field_value = explode( ',', $field_value ); + } + } } // Build DFV field data. @@ -474,7 +488,7 @@ public function build_dfv_field_data( $args ) { 'fieldItemData' => $this->build_dfv_field_item_data( $args ), 'fieldConfig' => $this->build_dfv_field_config( $args ), 'fieldEmbed' => true, - 'fieldValue' => isset( $args->value ) ? $args->value : PodsForm::default_value( $default_value, $args->type, pods_v( 'name', $options, $args->name ), $options, $args->pod, $args->id ), + 'fieldValue' => $field_value, ]; /** diff --git a/src/Pods/Admin/Config/Field.php b/src/Pods/Admin/Config/Field.php index d60bb8225e..1c06a2dbf9 100644 --- a/src/Pods/Admin/Config/Field.php +++ b/src/Pods/Admin/Config/Field.php @@ -341,6 +341,17 @@ public function get_fields( \Pods\Whatsit\Pod $pod, array $tabs ) { 'type' => $layout_non_input_field_types, ], ], + 'default_empty_fields' => [ + 'name' => 'default_empty_fields', + 'label' => __( 'Default Empty Fields in Forms', 'pods' ), + 'help' => __( 'On forms where the field value is empty you can enable Default Empty Fields to override the value with your chosen default value.', 'pods' ), + 'type' => 'boolean', + 'default' => '', + 'boolean_yes_label' => __( 'Use the default value when this field is empty', 'pods' ), + 'excludes-on' => [ + 'type' => $layout_non_input_field_types, + ], + ], 'visibility' => [ 'name' => 'visibility', 'label' => __( 'Visibility', 'pods' ),