The Community forums are being phased out in favor of a new Slack group.
Add your email address below to get an invitation to join the community slack group

Slack Signup
Newsletter Optin
Help Desk

Randomise quiz questions

Labels

This Discussion is public

Notifications

Hi guys,

I'm trying to randomise the order of my questions in a quiz form and came across this function:
add_filter('frm_get_paged_fields', 'get_extra_form_fields', 10, 3);
function get_extra_form_fields($fields, $form_id, $error=false){
if($form_id == 25){ //change 25 to the id of the form to change
shuffle($fields);
}
return $fields;
}

This works (although my form is a single page, so not sure I should be using the frm_get_paged_fields hook?) but I  have one text field (all other fields are radio buttons) that I don't want shuffled. I'm sure it's a simple single line or two of code to prevent this one field from being shuffled. I'm a PHP noob, so is anyone able to help me with it please?

Also, I found this function for changing the order of the answer options for a radio button field:

add_filter('frm_setup_new_fields_vars', 'frm_reorder_options', 30, 2);
function frm_reorder_options($values, $field){
if ( $field->id == 125 ) {//Replace 125 with the ID of your field
asort($values['options']); // sort the values here
}
return $values;
}

I would like to adapt this function to reorder ALL of my radio button fields - again, my lack of skills prevents me doing it and although I could duplicate the same function for each field I wanted, I know there is a more efficient way, so I'm hoping some kind soul can help me!

Thanks for reading...

Cheers,
Matt

This is not going to be solvable in a line of code or two. It is a somewhat complex problem, but very doable. You said you don't want the text field shuffled. I am assuming you want the text field in a fixed position. At what position in the array do you want the text field? Beginning, end, or middle, and if middle, what position?

Essentially, what you have to do is copy the text field element to a holding array, delete the text field from $fields, shuffle $fields, then merge the text field back into $fields in the desired position. If you want the text field at the end, array_push will do this for you. If you want it at the beginning, use array_merge, and if in the middle, array_splice.

As for the radio buttons, instead of $field->id == 125, you have to create a loop to roll through all of the values['options'] and sort each one.

For an experienced developer, these tasks would take and hour or two,

Discussion closed.