Created
January 18, 2019 22:50
-
-
Save damiencarbery/b0951ee6f7fdd9e7f08833dfb16a1b7d to your computer and use it in GitHub Desktop.
Ninja Forms – Display dynamic drop down selection in Submissions - Dynamically add options to a 'Select' field and ensure that they show when editing a Submission. https://www.damiencarbery.com/2019/01/ninja-forms-display-dynamic-drop-down-selection-in-submissions/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Ninja Forms Select field - display in form and Submissions | |
Plugin URI: https://damiencarbery.com/ | |
Description: Dynamically add options to a 'Select' field and ensure that they show when editing a Submission. | |
Author: Damien Carbery | |
Version: 0.1 | |
*/ | |
// Inspired by: http://developer.ninjaforms.com/codex/dynamic-list-fields/ | |
// And from reading ninja-forms/includes/Abstracts/List.php and noticing that $_GET[ 'post' ] was used. | |
// Update 'Select' options when the form is being rendered. | |
add_filter( 'ninja_forms_render_options', 'dcwd_nf_forms_render_options', 10, 2 ); | |
function dcwd_nf_forms_render_options( $options, $settings ) { | |
if ( 'listselect_1546711953461' == $settings[ 'key' ] ) { | |
$options[] = [ | |
'label' => 'New Seven', | |
'value' => 'new', | |
'calc' => 0, | |
// If you want this value to be selected by default, only do this on the front end | |
// as the selected value in admin (when viewing Submissions) should be the one that | |
// was selected when the form was submitted. | |
// If you don't want it selected on the front end then just set to false. | |
'selected' => is_admin() ? false : true, | |
]; | |
// If viewing a submission get the submitted value in case it is no longer an option in the form. | |
if ( is_admin() && array_key_exists( 'post', $_GET ) ) { | |
$post_id = absint( $_GET[ 'post' ] ); | |
$selected_value = get_post_meta( $post_id, '_field_' . $settings[ 'order' ], true ); | |
// Check whether the selected value is already in $options (either part of the form or added above). | |
$key = array_search( $selected_value, array_column( $options, 'value' ) ); | |
// Only add the selected value if it's not present. | |
if ( false === $key ) { | |
$options[] = [ | |
'label' => $selected_value, // The original display label is not available. | |
'value' => $selected_value, | |
'calc' => 0, | |
'selected' => true, | |
]; | |
} | |
} | |
} | |
return $options; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment