Home › Forums › General Issues › 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,
));
?>


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 🙂
The topic ‘Calculate fields and update the "total field"’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.