Store a calculated field value

Created by Phil Kurth, Modified on Fri, 18 Nov 2022 at 01:30 PM by Phil Kurth

Calculated fields are designed purely for display purposes but if you find yourself needing to store the calculated value, you may use the af/form/submission hook to call and save the calculated value in an additional ACF field, as per the following example: 


// Calculate the value of our calculated field named `calculated_1`
add_filter( 'af/field/calculate_value/name=calculated_1', function () {
  return af_get_field( 'number_1' ) + af_get_field( 'number_2' );
}, 10, 0 );

// Use a custom submission handler to saved the calculated field value to the database as needed.
add_action( 'af/form/submission', function ( $form, $field, $args ) {

  // If we need to run this only on a specific form, check for the form key.
  if ( $form['key'] !== 'YOUR_FORM_KEY_HERE' ) {
    return $form;
  }
  
  // If the form is creating a post and you need to store the value against the created post ID, you
  // can access the post ID on the submission array and use it as the ACF object ID.
  $acf_object_id = AF()->submission['post'];

  // Alternatively, if the form is creating a user, you can access the ID in a similar fashion to
  // build the necessary ACF object ID.
  //$acf_object_id = 'user_' . AF()->submission['user'];

  // Get the value of the calulated field
  $calculated = af_get_field( 'calculated_1' );

  // Store the value in a desired ACF field
  update_field( 'some_field_name', $calculated, $acf_object_id );

  return $form;
}, 20, 3 );

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select atleast one of the reasons

Feedback sent

We appreciate your effort and will try to fix the article