Misc / Using custom_args_js_event with Autocomplete Fields

Fieldmanager_Autocomplete fields have an optional argument¬†custom_args_js_event which allows you to, via JavaScript, pass custom data along with the ajax request. This can be extremely useful when you want to limit the results of the autocomplete search through some other field on the page. An example might be that you have a “Taxonomy” dropdown and a “Term” autocomplete field, and you want the terms returned in the autocomplete field to be limited to the taxonomy selected. Another example might be limiting post results to a selected time period. The data you pass is arbitrary, so use your imagination!

  1. Example 1: Limiting related posts to a given category

    add_action( 'fm_post_post', function() {
    	$fm = new Fieldmanager_Select( array(
    		'name' => 'category',
    		'datasource' => new Fieldmanager_Datasource_Term( array(
    			'taxonomy' => 'category',
    		) ),
    	) );
    	$fm->add_meta_box( 'Select a Category', array( 'post' ) );
    
    	$fm = new Fieldmanager_Autocomplete( array(
    		'name' => 'posts',
    		// This is a JS event that will fire on our field.
    		'custom_args_js_event' => 'fm_demo_custom_args_js_event',
    		'datasource' => new Fieldmanager_Datasource_Post( array(
    			// By default, FM auto-generates the ajax action as a checksum of
    			// the datasource args. Ours change, so we provide a static action.
    			'ajax_action' => 'my_category_posts',
    			'query_args' => array(
    				'post_type' => 'post',
    				// FM passes the custom data that we set in JavaScript in the
    				// "fm_custom_args" POST key.
    				'category' => ( ! empty( $_POST['fm_custom_args'] ) ? intval( $_POST['fm_custom_args'] ) : null ),
    			),
    		) ),
    	) );
    	$fm->add_meta_box( 'Related Posts', array( 'post' ) );
    } );
    
    add_action( 'admin_footer', function() {
    	?>
    	<script type="text/javascript">
    	jQuery( function( $ ) {
    		// We hook into our custom event on the autocomplete field, and return
    		// the selected category from our select dropdown.
    		$( '.fm-posts input.fm-element' ).on( 'fm_demo_custom_args_js_event', function( e ) {
    			return $( '.fm-category option:selected' ).val();
    		} );
    	} );
    	</script>
    	<?php
    } );