questions

Prefill form data from external api

Rate this post

I am using acf_form to manage the user profile.

Now I would like to understand if it is possible to populate the fields by taking them from an external api, this is the code developed so far:

<?php
    $response = wp_remote_get('http://connector.it/prendiutentedaid?idutente=' . $current_user->id_ext_pro);

    if (isset($response['body'])) {
        $data = json_decode($response['body'], true);

        $options = [
            'post_id' => 'user_' . $current_user->ID,
            'field_groups' => [552977, 589701],
            'form' => true,
            'return' => add_query_arg('updated', 'true', get_permalink()),
            'html_before_fields' => '',
            'html_after_fields' => '',
            'submit_value' => 'update',
        ];
        acf_form($options);
    }
        // show error

    ?>

 

✔️Solution:

Hi You Can Update Form Fields Before Show The Form

Use : update_field();

<?php
$response = wp_remote_get('http://connector.it/prendiutentedaid?idutente=' . $current_user->id_ext_pro);

if (isset($response['body'])) {
    $data = json_decode($response['body'], true);

    if ($data){
        // Fields  should Be Array  key and Value 
        //  $data = [
        //   'field_name'=>'value_form_api',
        //  'field_name2'=>'value_form_api2',
        //]; 
        foreach ($data as $key=>$value){
            update_field($key,$value,'user_'.$current_user->ID);
        }
    }
    $options = [
        'post_id' => 'user_' . $current_user->ID,
        'field_groups' => [552977, 589701],
        'form' => true,
        'return' => add_query_arg('updated', 'true', get_permalink()),
        'html_before_fields' => '',
        'html_after_fields' => '',
        'submit_value' => 'update',
    ];
    acf_form($options);
}
// show error

?>

Leave a Reply

Your email address will not be published.

Back to top button