'Trying to get Gravity forms calculate the highest 3 number fields in the form results
Currently have a personality test for my church that we are trying implement with Gravity forms. All the answers are calculated into key area traits (number fields). We would like to output the highest results. Currently This is what I have written. (I'm no mater of javascript).
add_action( 'gform_pre_submission_1', 'pre_submission_handler');
function pre_submission_handler( $form) {
const gifts = {};
const filter_fields = ['98', '113', '115', '121' , '122', '110', '111', '123', '120', '118', '119', '117', '114', '124', '107', '109', '112', '104', '105', '103', '106', '116', '108', '100' ];
foreach ( $form['fields'] as $field ) {
if filter_fields.includes(title) {
let field_label = $field->title;
let field_value = $field->value;
gifts[field_label] = field_value;
}
}
/* gifts.sort(field_value); */
Object.entries(gifts).sort((a, b) => b[1] - a[1])
let top1 = Object.keys(gifts)[0];
let top2 = Object.keys(gifts)[1];
let top3 = Object.keys(gifts)[2];
$_POST['#####'] = top1;
$_POST['####'] = top2;
}
I would love to have the code output the fields into the email responce
Solution 1:[1]
First of each call to Object.keys|entries|values creates a new instance and sort function in JS manipulates the the array so in the end you are sorting and throwing away the array. The possible solution would be;
const gifts = {
label1: 10,
label2: 12,
label3: 5,
label4: 14,
label5: 1
}
const sortedGifts = Object.entries(gifts) // transform data into an array form
.map(([key, value]) => ({key, value})) // in order to sort and retain key value
.sort((a, b) => b.value - a.value) // sort the value and store in a variable
const topThree = sortedGifts.slice(0, 3) // get top three items from the sorted list
console.log(topThree.map(d => d.key)) // log top three items' labels ["label4", "label2", "label1"]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Hamza Ali TA? |
