Support

Account

Home Forums General Issues Calculate fields and update the "total field"

Solved

Calculate fields and update the "total field"

  • Hi there,

    My users can on their frontend profile-page (author.php) edit some custom fields via acf_form. All works well and the values in the fields are saved upon “Update” via acf_form.

    But now I’ve created a new field that should act as a “calculated result field” called ‘mojlig_besparing’.

    My goal is for the user to be able to via acf_form (or if you can think of a better solution) edit the numbers in ‘falt_1’, ‘falt_2’, and ‘falt_3’ – Press “Uppdatera” and on this save the new value in field ‘mojlig_besparing’. As you can see in the image, a can show $total frontend. But I want to save this value to ‘mojlig_besparing’.

    <?php 
    $field1 = floatval(get_field('falt_1','user_'. $curauth->ID));
    $field2 = floatval(get_field('falt_2','user_'. $curauth->ID));
    $field3 = floatval(get_field('falt_3','user_'. $curauth->ID));
    $total = floatval(get_field('mojlig_besparing','user_'. $curauth->ID)); //not neccessery, gets calculated.
    
    $total = ($field1 * $field2) * $field3;
    
    echo '<h3>Fält1: '.$field1.'</h3>';
    echo '<h3>Fält2: '.$field2.'</h3>';
    echo '<h3>Fält3: '.$field3.'</h3>';
    echo '<h2>Totalt:' .$total.'</h2>';
    ?>
    
    <?php
    acf_form(
    array(
    'fields' => array('field_57fcd22f0128f','field_57fcd37965a69','field_57fcd37f65a6a'),
    'post_id' => 'user_'.$curauth->ID,
    ));
    
    ?>

    code translates to

  • Hi @dilladakilla

    You should be able to do this by using the update_field() function. It should be something like this:

    <?php 
    $field1 = floatval(get_field('falt_1','user_'. $curauth->ID));
    $field2 = floatval(get_field('falt_2','user_'. $curauth->ID));
    $field3 = floatval(get_field('falt_3','user_'. $curauth->ID));
    $total = ($field1 * $field2) * $field3;
    
    update_field('mojlig_besparing', $total, 'user_'. $curauth->ID);
    
    echo '<h3>Fält1: '.$field1.'</h3>';
    echo '<h3>Fält2: '.$field2.'</h3>';
    echo '<h3>Fält3: '.$field3.'</h3>';
    echo '<h2>Totalt:' .$total.'</h2>';
    ?>

    Please keep in mind that the value will be saved when you open the page. If you want to save it when along with the other fields, kindly use the acf/save_post hook instead.

    I hope this helps 🙂

  • Cool man, that did just what I asked for, thanks!

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

The topic ‘Calculate fields and update the "total field"’ is closed to new replies.