Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // INSTRUCTIONS
- // ensure you have two hidden fields labeled 'quiz' and 'correct', they can be placed anywhere in the form
- // in each quiz question check 'enable values' and set the value of the correct answer to 1, others set to 0. don't use other point systems
- // processes a quiz and total up the correct answers
- function sb_quiz_process($form){
- if ( ! sb_is_quiz( $form ) ) return;
- $total_value = 0; $questions_num = 0;
- foreach($form['fields'] as $field){
- //if ( strtolower($field['label']) == 'quiz') $is_quiz = true;
- if ( strtolower($field['label']) == 'correct') $total_field_id = $field['id'];
- $value = $_POST['input_' . $field['id']];
- if ( $value === '1' || $value === '0' ) {
- $total_value = $total_value + $value;
- $questions_num++;
- }
- }
- if ( $total_field_id && $questions_num ) {
- $percent_correct = $total_value / $questions_num; // assuming each correct value is 1 and not more!
- $_POST['input_' . $total_field_id] = sprintf("%.2f", $percent_correct );
- }
- }
- add_action("gform_pre_submission", "sb_quiz_process");
- //create our own confirmation
- function sb_quiz_submission( $lead, $form ) {
- if ( ! sb_is_quiz( $form ) ) return;
- echo '<div id="gforms_confirmation_message">';
- echo '<p>Thanks for taking the quiz! Your results are stored and you can always check your status to see what quizzes you have finished and which still need to be done.</p>';
- foreach($form["fields"] as $field){
- $field_label = esc_html(GFCommon::get_label($field));
- if ( strtolower($field['label']) == 'quiz') continue;
- $field_value = RGFormsModel::get_lead_field_value($lead, $field);
- $field_value_display = GFCommon::get_lead_field_display($field, $field_value, false, true);
- if ( strtolower($field['label']) == 'correct' ) {
- echo "<p class='sb_quiz_total'><strong>Your Score: ". $field_value * 100 ."%</strong>";
- unset($_POST['input_'.$field['id']]);
- } elseif ( is_numeric($field_value) ) {
- echo "<p class='sb_quiz_result' style='text-align:left;margin-left: 20px; '><strong>$field_label</strong><br>";
- if ( $field_value === '1' ){
- echo "<span style='color:green'>CORRECT - $field_value_display</span>";
- } else {
- echo "<span style='color:red'>INCORRECT - try again</span>";
- unset($_POST['input_'.$field['id']]);
- }
- echo "</p>";
- }
- }
- echo '</div>';
- }
- add_action( 'gform_post_submission', 'sb_quiz_submission', 10, 2 );
- //disable default confirmation
- function sb_quiz_confirmation( $confirmation, $form, $lead, $ajax ) {
- if ( sb_is_quiz( $form ) )
- return '';
- else
- return $confirmation;
- }
- add_filter( 'gform_confirmation', 'sb_quiz_confirmation', 10, 4 );
- // is this form a quiz?
- function sb_is_quiz( $form ) {
- foreach($form['fields'] as $field){
- if ( strtolower($field['label'] ) == 'quiz' )
- $is_quiz = true;
- }
- return $is_quiz;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement