Support

Account

Home Forums Add-ons Repeater Field Nested repeater and programmatically add values

Solved

Nested repeater and programmatically add values

  • Hello all.

    I use ACF Pro and I’ve created a nested repeater field for working hours in a CPT.

    The structure is like that:

    Repeater Field [Field Name: working_hours] (Working Days) (To repeat the week days and working hours of the days)
    Select [Field Name: day] (contains the names of the week days)
    Repeater Field [Field Name: working_hours] (Working Hours repeater to add the working hours per day)
    Time Picker [Field Name: from] (From time)
    Time Picker [Field Name: to] (From time)

    Now, what I need to achieve is to populate the fields with data programmatically.

    What I have try so far is to use the update_field and a structure like this as value:


    $options = [
    "working_hours" => [
    [
    "day" => "Monday",
    "working_hours" => [
    [
    "from" => "09:00",
    "to" => "14:30",
    ],
    [
    "from" => "17:00",
    "to" => "20:30",
    ]
    ]
    ],
    // ... other days here
    ]
    ];

    But this creating only the top level of repeated elements and the child fields are all empty.

    For example, if I have a seven days values (first working_hours contains seven child arrays) in the post I get seven repeated items, all showing Monday and no registered hours.

    Can someone show me how can I achieve this programmatically?

    Thank you in advance !

  • Please note the documentation that you must use field keys when adding values where they do not already exist. When using update_field() it is always safest to use field keys instead of field names.
    Also note that the values you supply must be in the same format that ACF stores in the DB and NOT what you have set for the return format. I do not know what format this is for the time field. You should look in the database and make sure you are matching the value.
    I would also suggest using a different sub field name for your repeater than then parent repeater name. Using the same name could potentially cause issues when using nested have_rows() loops.
    To update a repeater field the value must be:

    
    // you should replace all the field names with field keys
    $value = array(
      // nested array for each row of the repeater
      array(
        // field_key => value pairs for the row
        'day' => 'DAY VALUE',
        'working_hours' => array(
          // this is a nested repeater, it follows the same pattern as the parent repeater
          // nested array for each row
          array(
            // field_key => value pairs for the row
            'from' => 'TIME',
            'to' => 'TIME'
          }
        )
      )
    );
    update_field('working_hours', $value, $post_id);
    
  • Thank you John !! That worked perfectly !! 🙂

    Have a great weekend 🙂

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

You must be logged in to reply to this topic.