Support

Account

Home Forums General Issues update_field in a loop of a list of users Reply To: update_field in a loop of a list of users

  • Hi,

    What I mean by the $_POST['tri'] is that, your form output is looking something like this:

    
    <form action="..." method="POST" class="user-email-settings">
        <div class="user">
            <input type="checkbox" id="1" name="1" class="pref" value="1" checked /> first last
        </div>
        <div class="user">
            <input type="checkbox" id="2" name="2" class="pref" value="1" /> first last
        </div>
        ...
        <input type="submit" value="Update Tri Annual Status" name="status" id="status" class="ai-button" />
    </form>
    

    None of the input contains the name ‘tri’. Therefor your $_POST will only contains:

    
    $_POST = [
        1 => 1,
        'status' => 'Update Tri Annual Status'
    ];
    

    1) the name of the checkbox input is the index in the $_POST variable.
    2) if the checkbox is not check, the $_POST variable will not include them.

    —————————————————————————
    Based on my understanding of your code, i think what you want is something like the following:

    
    if (has_some_permission()):
        $users = do_something_to_get_those_users();
    
        if ($_POST['status']) {
            foreach ($users as $user) {
                update_field('field_598c6559e1b0d', $_POST['tri'][$user->ID], $user);
            }
    
            echo '<p class="success">Status Updated<p>';
        }
    
        echo '<h2 class="group-table-heading">Tri Annual Status</h2>';
        echo '<form action="' . get_the_permalink() . '" method="POST" class="user-email-settings">';
    
        foreach ($users as $user) {
            $f     = get_user_meta($user->ID, 'first_name', true);
            $l     = get_user_meta($user->ID, 'last_name', true);                     
            $field = get_user_meta($user->ID, 'tri', true); 
            // is this an acf field?
            // $field = get_field('field_598c6559e1b0d', $user);
            // $field = get_field('tri', $user);
            
            echo '<div class="user">';
                echo sprintf('<input type="hidden" name="tri[%d]" value="0" />', $user->ID);
                echo sprintf('<input type="checkbox" name="tri[%d]" value="1" %s />', $user->ID, $field? 'checked' : '');
                echo " {$f} {$l}";
            echo '</div>';
        }
    
        echo '<input type="submit" value="Update Tri Annual Status" name="status" id="status" class="ai-button" />';
        echo '</form>';
    }
    

    Notice the checkbox’s name attribute is what will get put into the $_POST variable.
    The $_POST variable after this form is submitted will be something like:

    
    $_POST = [
        'tri' => [
            1 => 1,
            2 => 0,
            3 => 0,
            4 => 0
        ],
        'status' => 'Update Tri Annual Status'
    ];
    

    Cheers