Support

Account

Home Forums Add-ons Repeater Field ACF 5.0+ Dynamically Populating Repeater Reply To: ACF 5.0+ Dynamically Populating Repeater

  • @mcnab It looks like this:

    /**
     * Load value from custom table
     * 
     * @param Mixed $value
     * @param Integer $post_id
     * @param Array $field
     * 
     * @return $value
     */
    function populate_custom_table_data( $value, $post_id, $field ) {
    
    	if( ! empty( $value ) ) {
    		return $value;
    	}
    
    	$has_parent_field	= false;
    	$field_name 		= $field['name'];
    
    	/**
    	 * Grab parent field and get value by the parent field name
    	 * Use conditional below to populate the actual fields.
    	 */
    	if( ! empty( $field['parent'] ) && false !== strpos( $field['parent'], 'field_' ) ) {
    
    		// false, false is important to prevent infinite recursive loop.
    		$parent_field 	  = get_field_object( $field['parent'], $post_id, false, false );
    		$has_parent_field = ( ! empty( $parent_field ) );
    		$field_name 	  = ( $has_parent_field ) ? $parent_field['name'] : $field_name;
    
    	}
    	
    	// Grab data from custom table
    	$db_data   	= $this->data_util->get_data( $post_id, $field_name );
    	$value		= $db_data;
    
    	// Return early if value is empty
    	if( empty( $value ) ) {
    		return $value;
    	}
    
    	// We're in a subfield
    	if( $has_parent_field ) {
    
    		$field_concat_name = $field['name'];
    		$field_concat_name = str_replace( sprintf( '%1$s_', $field_name ), '', $field_concat_name );
    		preg_match( '(\d{1,})', $field_concat_name, $possible_keys );
    
    		if( ! empty( $possible_keys ) ) {
    
    			$arr_index 			= $possible_keys[0];
    			$field_concat_name 	= str_replace( sprintf( '%1$d_', $arr_index ), '', $field_concat_name );
    
    			// Now we know what index in our subarray
    			$subfield_arr		= $db_data[ $arr_index ];
    
    			// Overwrite $value to actual subfield value
    			// Now that we know the name we can grab it from our named index array
    			$value = ( ! empty( $subfield_arr[ $field_concat_name ] ) ) ? $subfield_arr[ $field_concat_name ] : '';
    		}
    		
    
    	} else if( 'repeater' == $field['type'] ) {	// Return repeater count
    
    		$value = count( $db_data );
    
    	}
    
    	return $value;
    
    }
    add_filter( 'acf/load_value', 'populate_custom_table_data', 20, 3 );