Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpmudev-sls/fd71b5528ed894ebd5b42f5afbcf61e7 to your computer and use it in GitHub Desktop.
Save wpmudev-sls/fd71b5528ed894ebd5b42f5afbcf61e7 to your computer and use it in GitHub Desktop.
[Forminator Pro] - Bulk add options to a Select field
<?php
/**
* Plugin Name: [Forminator Pro] - Bulk add options to a Select field
* Plugin URI: https://premium.wpmudev.org/
* Description: Bulk add options to a Select field (as of 1.12.1.1)
* Author: Alessandro Kaounas @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* Task: 0/11289012348292/1172200210290038
* License: GPLv2 or later
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// No need to do anything if the request is via WP-CLI.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
if ( ! class_exists( 'WPMUDEV_Forminator_Bulk_Select_Options' ) ) {
class WPMUDEV_Forminator_Bulk_Select_Options {
// User defined settings
private $form_id = 26;
private $field_id = 'select-1';
// User defined options
private $options = array(
'value-1' => 'Label 1',
'value-2' => 'Label 2',
'value-3' => 'Label 3',
);
private static $_instance = null;
public static function get_instance() {
if( is_null( self::$_instance ) ){
self::$_instance = new WPMUDEV_Forminator_Bulk_Select_Options();
}
return self::$_instance;
}
private function __construct() {
if ( ! defined( 'FORMINATOR_VERSION' ) || FORMINATOR_VERSION < '1.12' ) {
return;
}
$this->init();
}
public function init(){
add_filter( 'forminator_before_form_render', array( $this, 'wpmudev_forminator_before_form_render' ) );
}
public function wpmudev_forminator_before_form_render( $id ){
if( $this->form_id != $id ){
return;
}
add_filter( 'forminator_field_markup', array( $this, 'wpmudev_forminator_field_markup' ), 10, 2 );
}
public function wpmudev_forminator_field_markup( $html, $field ){
if( $field['element_id'] === $this->field_id ){
$markup = '';
foreach( $this->options as $key => $option ){
$markup .= '<option value="' . $key . '" data-calculation="0">' . $option .'</option>';
}
return str_replace( '</select>', $markup . '</select>', $html );
}
return $html;
}
}
add_action( 'plugins_loaded', function(){
return WPMUDEV_Forminator_Bulk_Select_Options::get_instance();
});
}
@stupidchief
Copy link

In my case I found that if you go to form settings and change value 'Multiple Option Value' to store 'Option Values' then this code stores the values.

@Silnoreki
Copy link

Silnoreki commented Oct 12, 2022

Gr8, that what I was looking for, thx for the code 👍

I made some update if you want to load custom post type posts into select-1 field:

<?php
/**
* Plugin Name: [Forminator Pro] - Bulk add options to a Select field
* Plugin URI: https://premium.wpmudev.org/
* Description: Bulk add options to a Select field (as of 1.12.1.1)
* Author: Alessandro Kaounas @ WPMUDEV
* Author URI: https://premium.wpmudev.org/
* Task: 0/11289012348292/1172200210290038
* License: GPLv2 or later
*/

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// No need to do anything if the request is via WP-CLI.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
	return;
}

 if ( ! class_exists( 'WPMUDEV_Forminator_Posts_In_Select' ) ) {
    
    class WPMUDEV_Forminator_Posts_In_Select {
        
        // User defined settings
        private $form_id    = 3158;
        private $field_id   = 'select-1';
        
        // User defined options
        // *options are switched off
        private $options = array(
            // 'value-1'    => 'Label 1',
            // 'value-2'    => 'Label 2',
            // 'value-3'    => 'Label 3',
        );

        private static $_instance = null;

        public static function get_instance() {

            if( is_null( self::$_instance ) ){
                self::$_instance = new WPMUDEV_Forminator_Posts_In_Select();
            }

            return self::$_instance;
            
        }

        private function __construct() {

            if ( ! defined( 'FORMINATOR_VERSION' ) || FORMINATOR_VERSION < '1.12' ) {
                return;
            }

            $this->init();
        }

        public function init(){
            add_filter( 'forminator_before_form_render', array( $this, 'wpmudev_forminator_before_form_render' ) );
        }

        public function wpmudev_forminator_before_form_render( $id ){
            
			if( $this->form_id != $id ){
				 return;
			}
			
			// Regular WP post query
			$posts  = get_posts(  
				array (  
					'post_type' => 'yours_post_type',
					'post_status' => 'publish',
					'posts_per_page' => -1,
					'orderby' => 'title',
					'order' => 'ASC',
				)  
			);   

			// Pass results to select-1
			// option label = post title
			// option value = post ID
			foreach( $posts as $post ) {
				$this->options[] = array(
					'label' => $post->post_title,
					'value' => $post->ID,
				);
			}
						  
			add_filter( 'forminator_field_markup', array( $this, 'wpmudev_forminator_field_markup' ), 10, 2 );
	  }


        public function wpmudev_forminator_field_markup( $html, $field ){
            if( $field['element_id'] === $this->field_id ){
                $markup = '';
                foreach( $this->options as $key => $option ){
                    $markup .= '<option value="' . $option['value'] . '" data-calculation="0">' . $option['label'] .'</option>';
                }
                return str_replace( '</select>', $markup . '</select>', $html );
            }
            return $html;
        }
		
    }

    add_action( 'plugins_loaded', function(){
        return WPMUDEV_Forminator_Posts_In_Select::get_instance();
    });

} 

@gareth94
Copy link

gareth94 commented Nov 12, 2022

Hi @wpmudev-sls @stupidchief and @Silnoreki. I've tried the above code but when I submit the form, I receive the error "Selected value does not exist."? I also changed 'Multiple Option Value' to store 'Option Values' within the form settings but still doesn't work :(

@appsdevpk
Copy link

Hi @wpmudev-sls @stupidchief and @Silnoreki. I've tried the above code but when I submit the form, I receive the error "Selected value does not exist."? I also changed 'Multiple Option Value' to store 'Option Values' within the form settings but still doesn't work :(

I am also facing the same issue

@passingby000
Copy link

same problem for me.

@passingby000
Copy link

Hi @wpmudev-sls @stupidchief and @Silnoreki. I've tried the above code but when I submit the form, I receive the error "Selected value does not exist."? I also changed 'Multiple Option Value' to store 'Option Values' within the form settings but still doesn't work :(

I am also facing the same issue

I found something in this post.

@Silnoreki
Copy link

Silnoreki commented May 18, 2023

@gareth94 @passingby000 @appsdevpk @stupidchief
Sry, I did some updadates a wile ago. I ended up with some code like here. Remember to clear cache etc.

You can check code here: https://gist.github.com/Silnoreki/4de0a35d71651f34c6342064680216e6

@CmendesMS
Copy link

Hi @Silnoreki, could you share your solution to the "Selected value does not exist." problem mentioned above again, please.

thank you in advance.

@Silnoreki
Copy link

Silnoreki commented Sep 26, 2023

You can check this @CmendesMS . The code should look better in VScode.

Replace elements mentioned in the code comments with yours data, clear cache etc. and that should work.

It's working on my live site for about year now 🙊

<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( defined( 'WP_CLI' ) && WP_CLI ) {
	return;
}

/* - - - - - - - - - - - -
    ! Remember to insert form ID in both filters
- - - - - - - - - - - - */
add_filter( 'forminator_cform_render_fields', function( $wrappers, $model_id ) {


	/* - - - - - - - - - - - -
		! Change 9999 to your form ID
	- - - - - - - - - - - - */
	if( $model_id != 9999 ){  return $wrappers; } 

		/* - - - - - - - - - - - -
			! Update the field data
		- - - - - - - - - - - - */
		$select_fields_data = array(
			'select-1' => 'Label 1', 
		);


		foreach ( $wrappers as $wrapper_key => $wrapper ) {
			if ( ! isset( $wrapper[ 'fields' ] ) ) { continue; }

			if ( 
				isset( $select_fields_data[ $wrapper[ 'fields' ][ 0 ][ 'element_id' ] ] ) && 
				! empty( $select_fields_data[ $wrapper[ 'fields' ][ 0 ][ 'element_id' ] ] ) 
			) {

				/* - - - - - - - - - - - -
					! Here you can add your custom post query
				- - - - - - - - - - - - */
                $posts  = get_posts(  
                    array (  
                        'post_type' => 'CUSTOM_POST_TYPE',
                        'post_status' => 'publish',
                        'posts_per_page' => -1,
                        'orderby' => 'title',
                        'order' => 'ASC',
                    )  
                );   
    

				$new_options = [];
				$opt_data = [];

				foreach( $posts as $post ) {
                    $new_options[] = array(
                        'label' => $post->post_title,
                        'value' => $post->ID,
                        'limit' => '-1',
                        'key'   => forminator_unique_key(),
                    );
                    $opt_data['options'] = $new_options;
				}

				$select_field = Forminator_API::get_form_field( $model_id, $wrapper['fields'][0]['element_id'], true );
				if( $select_field ){
					Forminator_API::update_form_field( $model_id, $wrapper['fields'][0]['element_id'], $opt_data );
					$wrappers[ $wrapper_key ][ 'fields' ][ 0 ][ 'options' ] = $new_options;
				}
			}
		}

		return $wrappers;
	},
	10,
	2
);




add_filter(
	'forminator_replace_form_data', 
	function( $content, $data, $fields ) {

		/* - - - - - - - - - - - -
			! Change 9999 to your form ID
		- - - - - - - - - - - - */
		if( $data['form_id'] != 9999 ){
			return $content;
		}

		if ( ! empty( $content ) ) {
			return $content;
		}

		$form_fields = Forminator_API::get_form_fields( $data['form_id'] );
		$data_field = '';
		foreach($data as $key => $value){
	    	if ( strpos( $key, 'select' ) !== false ) {
	    		$values = '';
	    		$field_value = isset( $data[ $key ] ) ? $data[ $key ] : null;

		    	if ( ! is_null( $field_value ) ) {
		    		$fields_slugs  = wp_list_pluck( $form_fields, 'slug' );
					$field_key     = array_search( $key, $fields_slugs, true );
					$field_options = false !== $field_key && ! empty( $form_fields[ $field_key ]->raw['options'] )
							? wp_list_pluck( $form_fields[ $field_key ]->options, 'label', 'value' )
							: array();

					if ( ! isset( $field_options[ $field_value ] ) && isset( $_POST[ $key ] ) ) {
						return sanitize_text_field( $_POST[ $key ] );
					}
				}
			}
		}
	    return $content;
	},
	10,
	3
);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment