Home Forums General Issues How to store a repeater row number as a value in another field Reply To: How to store a repeater row number as a value in another field

  • I do something similar to the unique id plugin you found, but I do it manually. What I do is that I create a text field in each row, then I create a filter for this field to make it read only. Then I generate a value for this field, I generally do this in JavaScript but it can be done using an acf/save_post filter. The main issue with doing it based on the number of rows but if I had to… assuming that new fields can be added and fields can be moved.

    add_action('acf/save_post', 'repeater_unique_row_id_on_count');
    function repeater_unique_row_id_on_count($post_id) {
      if (have_rows('your-repeater-field')) }
        // first loop over repeater to get existing IDs
        $existing_ids = array();
        while (have_rows('your-repeater-field')) {
          if (get_sub_field('your-id-field')) {
            // note that this field should be a read only field
            // you could also hide this field using custom admin CSS
            $existing_ids[] = intval(get_sub_field('your-id-field');
        } // when while have_rows
        // you may need to reset rows, I don't know, next line may not be needed
        // second loop to set any missing IDs
        $count = 1;
        while (have_rows('your-repeater-field')) {
          if (!get_sub_field('your-id-field')) {
            // id field is empty
            while (in_array($count, $existing_ids)) {
              // inc count until it does not already exist
              // this will cause count to skip anything that exists
            } // end while
            // record ID and update sub fiele
            $existing_ids[] = $count;
            update_sub_field('your-id-field', $count);
          } // end if empty id
        } // end while have_rows
      } // end if have_rows
    } // end function