[Resolved] get the sum of custom fields after submit a form using submit api
This thread is resolved. Here is a description of the problem and solution.
Problem:
A form includes several numerical fields. The total should be calculated when the form is submitted and stored in another field.
Solution:
You will need to use the Forms API hook cred_save_data and write a snippet of custom code that retrieves the field values, performs the calculation, and stores the result.
This support ticket is created 5 years, 11 months ago. There's a good chance that you are reading advice that it now obsolete.
This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.
Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.
No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.
i wonder if thats possible with the submit api.
i have 4 fields and i want to calculate all fields together to get a sum and than save that sum in another custom field of this posttype.
field1+field2+field3+field4= save the total of all 4 fields in another custom field.
But i am no coder so it is very difficult for me to get this running.
<?php
/**
* New custom code snippet.
*/
toolset_snippet_security_check() or die( 'Direct access is not allowed' );
/**
* Custom form action to sum field values
*/
add_action( 'cred_save_data', 'tssupp_form_submit', 10, 3 );
function tssupp_form_submit( $post_id, $form_data ){
if ( in_array( $form_data['id'], array( 985 ) ) ) { // Edit form ID
$slugs = array( 'wpcf-skala-job-schwerpunkt-1', 'wpcf-skala-job-schwerpunkt-2', 'wpcf-skala-job-schwerpunkt-3', 'wpcf-skala-job-schwerpunkt-4' ); // Edit slugs of fields to SUM
$result_slug = 'wpcf-skillswert-speichern'; // Edit for slug of field to store result
$values = [];
foreach ($slugs as $key => $slug) {
$values[$key] = get_post_meta( $post_id, 'wpcf-' . $slug, true ); // What shell i add here: wpcf-
}
$sum = array_sum( $values );
add_post_meta( $post_id, 'wpcf-' . $result_slug, $sum ); // What shell i add here: wpcf-
}
}
Another question is where does the calculating is going on because the sum of all fields needs ((sum *100)/40) to get the percentage of the sum. but i can´t see math anywhere?