Support

Account

Home Forums General Issues Moving a field : update field values Reply To: Moving a field : update field values

  • I try to avoid the need to move a field, but it does happen. It also happens that sometimes the needs expand and I must replace some fields with new fields. In all of these cases what I try to do is to not try to alter the data in the database and it is a multi-step process.

    1. Do not move the field
    2. Create a new field
    3. Alter my template file to look for a value in the new field. If no value is found then look for a value the old field
    4. Create an acf/load_value filter for the new field that loads the value from the old field if it does not already have a value, this is going to be a bit complicated with repeater sub fields.
    5. Create an acf/save_post action that deletes the old field
    6. Create an acf/prepare_field filter removes the old field from the editor

    when new posts are created or old posts are edited the content of the field will be moved while still using the content of the old field where needed on the front of the site. This, IMO, is the best safest way to accomplish this.

    I your case I would probably combine #2 & #3 — See if the new field has a value, if it does not then get the value from the old field and update the row of the repeater.

    
    if (have_rows('repeater')) {
      while (have_rows('repeater')) {
        // little know fact
        // the_row() returns the row in unformatted field key => value pairs
        $the_row = the_row();
        $new_group = get_sub_field('new_group_field_name');
        if (empty($new_group['new_field_name'])) {
          $old_group = get_sub_field('old_group_name');
          // add to $the_row and update
          // field_XXXXXXX = field key of new group field
          // field_YYYYYYY = field key of new sub field in group
          $the_row['field_XXXXXXX']['field_YYYYYYY'] = $old_group['old_field_name'];
          update_row('repeater', get_row_index(), $the_row);
          
          // copy old value to new value
          $new_group['new_field_name'] = $old_group['old_field_name'];
        }
      }
    }
    

    The problem with doing it this way is that this will not delete the old value, but I probably would not care if the old value is deleted or not.