Skip to content

Instantly share code, notes, and snippets.

@damiencarbery
Created January 18, 2019 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save damiencarbery/b0951ee6f7fdd9e7f08833dfb16a1b7d to your computer and use it in GitHub Desktop.
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/
<?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