Support

Account

Home Forums Backend Issues (wp-admin) Dynamically Loading Values From Adjacent Fields Reply To: Dynamically Loading Values From Adjacent Fields

  • Here is an example of how I’d load values of a field in a row base on other sub fields of a repeater. It’s a little more complicated than a simple function.

    
    <?php 
      
      // use a class so that we can store values rather than 
      // regenerate them for every row of the repeater
      class load_dependency_field {
        
        var $choices = array(); // hold the choices
        
        function __construct() {
          // use the field key when loading a subfield
          add_filter('acf/load_field/key=field_56f0735c7223d', array($this, 'load_choices'));
        } // and function
        
        function load_choices($field) {
          global $post;
          if (get_post_type($post->ID) != 'questionnaire') {
            // only run this when editing the post
            return $field;
          }
          if (!count($this->choices)) {
            // haven't done this before
            $this->get_choices($post->ID);
          }
          $field['choices'] = $this->choices;
          return $field;
        } // end function
        
        function get_choices($post_id) {
          // example of using get_post_meta() instead of get_field for repeater
          // this removes the possiblity of creating infinite loop in ACF
          $repeater = 'questions';
          $subfield = 'question';
          $count = intval(get_post_meta($post_id, $repeater, true));
          for ($i=0; $i<$count; $i++) {
            $question = get_post_meta($post_id, $repeater.'_'.$i.'_'.$subfield);
            $this->choices[$question] = $question;
          }
        } // end function
        
      } // end class
      
      // instantiate the class
      new load_dependency_field();
      
    ?>