Support

Account

Home Forums Add-ons Repeater Field load_field – repeater adds empty fields to Field Group Reply To: load_field – repeater adds empty fields to Field Group

  • So, I have a function that pre-loads a repeater field with a specific number of sub fields and adds content to them. I’m doing this with acf/load_value rather than acf/load_field. This will also only create create the sub fields and values it it is a new post.

    Hoping this helps.

    
    <?php 
      
      /*
          the format of the value array needs to be
          
          $value = array(
            // a nested array for each row to be created
            array(
              // an array object for each field_key in the row
              'field_key_1' => 'value',
              'field_key_2' => 'value'
            )
          );
          
          The above would be tedious to create and error prone
          so I did it the other way and then did a loop to make it right
          I suspect you'd need to do it the hard way for nested repeaters
      */
      
      add_filter('acf/load_value/name=FIELD_NAME', 'acf_load_FIELD_NAME_value', 10, 3);
        
      function acf_load_FIELD_NAME_value($value, $post_id, $field) {
        if ($value !== NULL) {
          return $value;
        }
        $subfield_values = array(
          // field_key => array of values
          'field_5601faa3a7737' => array('Test 1', 'Test 2', 'Test 3'),
          'field_5601fbc1a7738' => array('Test 4', 'Test 5', 'Test 6'),
          'field_5601fbd9a7739' => array('Test 7', 'Test 8', 'Test 9'),
        );
        $values = array();
        foreach ($subfield_values as $field_key => $field_values) {
          for ($i=0; $i<count($field_values); $i++) {
            $values[$i][$field_key] = $field_values[$i];
          }
        }
        $value = $values;
        return $value;
      }
      
    ?>
    

    I’m not sure if this will work with nested repeater fields.

    To find out the format of a repeater field with nested repeaters create an acf/load_field filter for an existing repeater that has content in the sub fields and in the nested repeater sub fields and output the value. Here is an example of how to do that. Then you can see how you need to format the value to return to add content with the function above.

    
    <?php 
      
      add_filter('acf/load_value/name=FIELD_NAME', 'acf_load_FIELD_NAME_value', 10, 3);
        
      function acf_load_FIELD_NAME_value($value, $post_id, $field) {
        echo '<pre>'; print_r($value); echo '</pre>';\
        return $value;
      }
      
    ?>