Support

Account

Home Forums Backend Issues (wp-admin) Conditional Field / Different Field Group Reply To: Conditional Field / Different Field Group

  • I ran into a need for this today. This forum post seems to be a top google hit for my search so I’ll put the solution that worked for me here.

    The filter mentioned by John up above wasn’t able to influence field keys that were not a part of the field group of the field I was targeting.

    I ended up needing to use some of the JS API functions for this. https://www.advancedcustomfields.com/resources/javascript-api/

    In the example code below, I had a button group field with two options, and depending on the chosen option I am showing or hiding a field from another field group.

    There are a few ways to get the field keys, I found the easiest way was just to inspect the HTML on the page, but you could also get them from the GUI in the field group builder, or the ACF JSON files if you are using that.

    // Handle show/hide on ready
    acf.addAction( 'ready', function() {
    	buttonField = acf.getField( 'field_6202e1499e575' );
    	conditionalField = acf.getField( 'field_5e98b383fa39f' );
    
    	switch( buttonField.val() ) {
    		case 'traditional':
    			conditionalField.show();
    			break;
    
    		case 'simplified':
    			conditionalField.hide();
    			break;
    	}
    });
    
    // Handle show/hide when value is changed
    $('input[name="acf[field_6202e1499e575]"]').on( 'change', function() {
    	conditionalField = acf.getField( 'field_5e98b383fa39f' );
    
    	switch( $( this ).val() ) {
    		case 'traditional':
    			conditionalField.show();
    			break;
    
    		case 'simplified':
    			conditionalField.hide();
    			break;
    	}
    });
    
    // I didn't need any of either of these callbacks, but I verified they do get called with the above code
    function showFieldCallback( field ) {
    	console.log( 'show callback fired' );
    }
    acf.addAction( 'show_field/key=field_5e98b383fa39f', showFieldCallback );
    
    function hiddenFieldCallback( field ) {
    	console.log( 'hidden callback fired' );
    }
    acf.addAction( 'hide_field/key=field_5e98b383fa39f', hiddenFieldCallback );

    I hope this helps someone else!