Support

Account

Home Forums ACF PRO Change Select Default Value for each Repeater Item

Solving

Change Select Default Value for each Repeater Item

  • Hi people,
    is there a way to have a different default value for the select element for each repeater row?
    For example, let’s imagine there is a repeater field with 2 items in it:

    1. Select Field (Allow Null is off). Select List Items:
    Sun
    Water
    Earth
    Fire

    2. A Wysiwyg field to enter some content.

    Also the minimum and maximum rows has been selected as 4 for the repeater so it will always show 4 rows to start with but you can’t add more rows.

    Now here the problem comes. In the current situation for all the repeater rows the select shows the first item “Sun” as selected value.

    What I was looking for is if there is a way for the select to show the default items in order. So, for the first row the default items is “Sun” for second row “Water, for third row “Earth” and so on….

    Is this actually possible to do? Is there any way to do it?

  • Altering fields on different rows of a repeater is extremely difficult.

    For existing fields, for example if a repeater already has 4 rows then this can be done using an acf/prepare_field filter. The filter needs to keep track of how many rows have been shown and then set a different value or default value based on the counter.

    
    // field_XXXXXXX represents field key of sub field
    add_filter('acf/prepare_field/key=field_XXXXXXX', 'prepare_my_subfield');
    function prepare_my_subfield($field) {
      static $counter = 0
      $values = array_keys($field['choices']);
      if (isset($values[$counter])) {
        $field['default_value'] = $values[$counter];
      }
      $counter++;
      return $field;
    }
    

    For fields that do not already exist, for example when adding a row then you need to use JavaScript https://www.advancedcustomfields.com/resources/adding-custom-javascript-fields/

    You need to add an JS acf append action and set the selected value of the field using the ACF JS API. Sorry, I don’t have code for this, it is more difficult for me to churn that out.

  • In the repeater, I have already set the max and min rows to the same number so there is no extra row to be added by the user. But yes I get it it’s extremely difficult to do and I thought the same. I was just wondering in case there is something which I don’t know.

    Thanks for your reply.

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

You must be logged in to reply to this topic.