Support

Account

Home Forums Front-end Issues Dynamically change acf_form checkbox field

Solving

Dynamically change acf_form checkbox field

  • Hi –

    I’m trying to find a way to ajax load new taxonomy based checkboxes into an acf_form() field based on the selection of a select, that is also in the form.

    So far I have tried to render the field and return the html. Something like this sudo code example:

    
    ob_start();
        do_action('acf/render_field/type=taxonomy', 'some_name', 11, 1);
    $field = ob_get_clean();
    

    But that doesn’t work.

    Another way I’ve been thinking is if there is a way to get the JSON value of the taxonomy field and pass it through some acf javascript hooks to rebuild the field. But honestly I’ve not been able to find anything help in the javascript docs to let me know if this is possible.

    Any suggestions welcome. I’d like to code into in a way that works with ACF as opposed to working over it.

  • If you’re looking to dynamically load a field based on another field then I would stick with a basic field type, like a select box, it can be done with radio and checkbox fields, and more than likely something like a taxonomy field, but a taxonomy field is already making AJAX requests and tying into those will be more complicated.

    Here are the basics for setting up a function that will fire when a field changes and make an AJAX request. You would create JavaScript file and enqueue it in the admin. When you enqueue the script set it’s $deps argument to array('acf-input'); which will ensure that that ACF’s acf-input.js file is loaded first.

    The following is for a select field that will trigger the event and change the values of another select field. You’ll need to do some testing to do other things but this is more information than I think is currently available and I think it will give people a place to start. You may also want to localize the script with the action that needs to be called. For more information on ajax and localizing scripts:

    Some of this, I’m not 100% sure of what it does, I’ve commented that below. Some of this was copied from other sources. I hate using stuff without completely understanding it, but, I’ll figure it out eventually. Most of what I’ve been able to learn is by trial and error, as the OP said, there isn’t a lot of information currently available for this type of thing and I’m hoping that others can help me change that. Hope this helps.

    
    jQuery(document).ready(function($){
      if (typeof(acf) == 'undefined') {
        // acf does not exist
        return;
      }
      // create events
      events: {
        // add a change event to the select field with
        // the id acf-field_56f181bf6f8d0
        // that calls the function _my_select_change_function
        'change #acf-field_56f181bf6f8d0': '_my_select_change_function',
        // add another event for the ready event
        // more about this later
        'ready #acf-field_56f181bf6f8d0': '_my_select_change_function',
      }, // end of events
      // the function
      _my_select_change_function: function(e) {
        // if we're already doing a request abort it
        if (this.request) {
          // another ajax request
          this.request.abort();
        }
        // not exactly sure what the next 2 lines do
        var self = this,
            data = this.o;
        // your ajax action
        data.action = 'my_ajax_action';
        // the value of the this field to send in the ajax request
        data.value = e.$el.val();
        // make the ajax request
        this.request = $.ajax({
          url: acf.get('ajaxurl'),
          data: acf.prepare_for_ajax(data),
          type: 'json',
          success: function(json) {
            // this function is called when
            // value is returned from ajax request
            // it returns an object or array
            // that looks like
            /*
              json = array(
                // nested array for each value label pair
                // to use when populating second select field
                array(
                  'value' => 'value of options',
                  'label' => 'label of option'
                )
              );
            */
            // get the other select field we want to populate
            // can probably be done in other ways as well
            $select = $('div[data-key="field-57028ebad20f0"] select');
            // store what's already selected
            var $selected = [];
            // get current options and loop
            var $options = $('.acf-field-57028ebad20f0 option');
            for (i=0; i<options.length; i++) {
              if ($options[i].selected) {
                $selected[$selected.length] = $options[i].value;
              }
            } // end for i
            // clear all current options from the select field
            $select.empty();
            // add null item
            $select.append('<option data-i="" selected="selected" value="">- Select -</option>');
            // loop returned value an populate
            for (i=0; i<json.length; i++) {
              var $item = '<option value="'+$json[i]['value']+'"'
    	  if ($selected.indexOf($taxonomy_terms[i]['value']) > -1) {
                // item was previously selected
                $item += ' selected="selected"';
              }
              $item += '>'+$json[i]['label']+'</option>';
              $select.append($item);
            } // end for i
          } // of success function
        }); // end of ajax request
      }, // end _my_select_change_function function
    
      // this will trigger when the page loads
      // what this will do is cause the select field we 
      // are dynamically populating to be loaded initially
      // using the ready action does not cause ACF to think
      // the field has been changed and means that the
      // "are you sure you want to leave this page"
      // message will not be displayed
      $(#acf-field_56f181bf6f8d0').trigger('ready');
    
    } // end of jquery ready function 
    

    ~JH

  • Thanks John, Thanks for this, I’ll take a look into it.

    To expand on some detail. I have a custom post type called campaigns. Each campaign post has a custom taxonomy associated with that post. (you can do this with some filters of what meta boxes display on the right column of the edit admin screen – so it is kind of faking it since all the taxes are really associated with the post type.). I do this because I need the user to be able to create different categories in the different taxonomies that only show on that specific post admin screen.

    In the front end acf_form() I load the list of campaigns, once the users selects a campaign, I then need to load the taxonomy associated with that campaign. I have ajax that sends the campaign post ID after the user selects. I then need to load or reload the taxonomy checkbox field that is associated with that selected campaign post. On the backend I’m using acf/load_field/ filter to alter which taxonomy loads based on what campaign the user has selected.

    I’m hoping to do that load/reload in an ACF way (either by loading the field HTML on the server and sending it back in the ajax, though I don’t think this will work because it appears that ACF uses a load of javascript to actually create the fields and values, or loading the taxonomy (field options) in a JSON config and then sending that through ACF javascript that loads with the acf_form() and header functions.)

    Thanks,

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

The topic ‘Dynamically change acf_form checkbox field’ is closed to new replies.