Support

Account

Home Forums General Issues acf.registerConditionType not working

Solved

acf.registerConditionType not working

  • I am trying to use the ACF 5.7 js API to register a new condition type so that I can show/hide fields based on whether a taxonomy field has a particular value.

    I’ve got the condition to show in the field configuration, but can’t get a field using that condition to show. For example:

    (function( $ ) {
    	'use strict';
    	$(function() {
    		var HasTerm = acf.Condition.extend({
    			type: 'hasTerm',
    			operator: '==hasTerm',
    			label: 'Has term',
    			//label: __('Has term'), //__ is not defined error
    			fieldTypes: [ 'taxonomy' ],
    			match: function( rule, field ){
    				console.log('matching...'); //never runs
    				return true; //field should always show
    			},
    			choices: function( fieldObject ){
    				return '<input type="text" />';
    			}
    		});
    		acf.registerConditionType( HasTerm );
    	});
    
    }( jQuery ));

    This is loaded in admin at the admin_enqueue_scripts hook, and on the front end at the wp_enqueue_scripts hook with jquery, acf-input and acf-field-group as dependencies.

    When I try this on the form, I have two issues:

    1. The __() function generates an error – __ is not defined
    2. The match function never runs and the field doesn’t show (which it always should in this test code since it returns true)

    What am I missing? Is there some other dependency or should I be loading this at some particular js or php action?

  • With big thanks to Elliot for helping me figure this out, and for the benefit of anyone else who finds this, the main problem was wrapping acf.Condition in jQuery on ready.

    For testing purposes, this code works and can be added to a theme’s functions.php:

    add_action( 'acf/admin_footer', 'my_admin_footer' );
    function my_admin_footer() {
    ?>
    <script>
    (function( $ ) {
    	'use strict';
    	var HasTerm = acf.Condition.extend({
    		type: 'hasTerm',
    		operator: '==hasTerm',
    		label: acf.__('Has term'),
    		fieldTypes: [ 'taxonomy' ],
    		match: function( rule, field ){
    			return rule.value === field.val();
    		},
    		choices: function( fieldObject ){
    			return '<input type="text" />';
    		}
    	});
    	acf.registerConditionType( HasTerm );
    
    }( jQuery ));
    </script>
    <?php
    }
Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘acf.registerConditionType not working’ is closed to new replies.