Support

Account

Home Forums Backend Issues (wp-admin) Fill fields after change value in another field

Solving

Fill fields after change value in another field

  • Hi,
    I have 3 acf. The first one is a select field.
    I want to get the value of the select field every time the user make a choice. So every time the field value is changed I want to trigger a function so I can get this value and based on this value to fill the next two fields with a simple update_field.

    I have tried to use save_post or wp_insert_post hook, but they both trigger my function when we create the new post so the field is still empty.

    Is is possible?

  • This can be done by :

    – 1st : pusching the selected data to the ajax request. For this you should use
    select2_ajax_data javascript filter and add a new element in the ajaxData array using the ACF JS API.
    Let say ajaxData.myparameter = getField(yourselectbox)

    – 2nd : Once this is ok, use the acf/field/post_object/query on php side.
    This filter is used to retrieve information and add them to the query.

    For this get $_POST[myparameter] ?? get_field(yourselectbox).

    $_POST : used to get ajax value from JS.
    get_field() : used when you update the page to used the current saved value for yourselectbox.

    Then you update the query to get the value for the other fields.

  • I am kind of trouble in the first step.
    Can you explain me a bit more how can I pass the selected value to ajax?

  • Here is a more complete example .

    UC : you want to change the content of some fields based on the selection of a combo box.

    Here the JS part :

    jQuery(document).ready(($) => {
        acf.addFilter('select2_ajax_data',(data, args, $input, field, instance) => {
                
                // Get the combo field instance
    
                let your_combo = acf.getFields({
                    name: 'your_combo_field_name'
                })[0];
    
                if (your_combo !== undefined && (data.field_key === field.get('key')) {
                        data.your_value = your_combo.val();  // Here is the magic ;)
                    }
                }
            });
    })

    And on PHP side, for all the fields depending on the combo selected value

    foreach (['field1','field2','field3',] as $name) {
    	add_filter( 'acf/fields/post_object/query/name=' . $name, function ( $args, $field, $post_id ) {
    
    		// get the value from AJAX or from the field value
    		$list = $_POST['your_value'] ) ?? get_field( 'your_combo_field_name', $post_id );
    		}
    
    		// change the query according to your model
    		if ( null !== $list ) {
    			// $args['tax_query']
    			// $args['meta_query'] 
    		}
    		return $args;
    	}, 1, 3 );
    }
    

    Hope this helps. Do not hesitate to comment if you find any problem in the code (wrote online from a live example)

  • In my functions.php:

    
    function fill_data($post_id){
    	foreach (['sub_title'] as $name) {
    
    	add_filter( 'acf/fields/post_object/query/name=' . $name, function ( $args, $field, $post_id ) {
    
    		$list = $_POST['your_value']  ?? get_field( 'sub_title', $post_id );
    		
    
    		// change the query according to your model
    		if ( null !== $list ) {
    			// $args['tax_query']
    			// $args['meta_query'] 
    		}
    
    		return $args;
    	}, 1, 3 );
    }
    	
    }
    
    function my_scripts_method() {
        wp_enqueue_script(
            'script',
            get_stylesheet_directory_uri() . 'script.js', #your JS file
            array( 'jquery' ) #dependencies
        );
    }
    
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
    	
    add_action('init', 'fill_data', 10, 1);

    In my script.js (in the same folder with functions.php):

    jQuery(document).ready(($) => {
        acf.addFilter('select2_ajax_data',(data, args, $input, field, instance) => {
                
                // Get the combo field instance
    
                let your_combo = acf.getFields({
                    name: 'sub_title'
                })[0];
    
                if (your_combo !== undefined && (data.field_key === field.get('key')) {
                        data.your_value = your_combo.val();  // Here is the magic ;)
                    }
                }
            });
    })

    It doesn;t seem to work. I am not sure if I haven’t included correctly the script.js file. Also shouldn’t the php function to be triggered every time I change my choice in my select drop down field? Thank you

  • You did not use the right hook to enqueue your script in the admin part.
    The best way to do this when you are using ACF is to use the dedicated action.

    Heres an example to enqueue a my.js file from <MY PLUGIN>/js

    add_action( 'acf/input/admin_enqueue_scripts', function () {
    	wp_register_script( 'my-js', esc_url( plugins_url( '/js/my.js', __FILE__ ) ), false, false, true );
    	wp_enqueue_script( 'my-js' );
    
    } );
  • I will try this.But with what action should I trigger the php function?
    With do_action(‘init’)?

  • On PHP there’s no action to trigger 🙂 but a filter. Do not encapsulate the filter hook in any action but use it as is in your functions.php.

  • I have used the filter inside a public function so that I can have it on my plugin folder. Should I use it without any function?

  • Sure.
    Add it into your plugin main PHP file.

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.