-
Notifications
You must be signed in to change notification settings - Fork 566
Open
Labels
Description
We lean on CMB2 to create quizzes. These quizzes have questions (repeatable groups). Within each question, the admin can create answers (repeatable text field). Here's an example of one of the repeatable groups structure.
When the data is saved, it removes all but one of the questions. To replicate:
- First group field - add 3 repeating text fields
- click "add group" - add 3 repeating text fields
- do this two more times to make a total of 5 repeating field groups, with each group having 3 repeating text fields
- publish the post
When you refresh the page:
- repeating group fields 2,3,4 now only have 2 repeating text fields (it removed the last)
- it added a 6th group with two random answers
Here's the sample code:
// instantiate metabox
$cmb = new_cmb2_box( array(
'id' => '_quiz_metabox',
'title' => 'Quiz Questions',
'object_types' => array( 'cgc_quiz' )
) );
$cmb->add_field( array(
'name' => 'Public Quiz',
'id' => '_is_public',
'type' => 'checkbox'
) );
$cmb->add_field( array(
'name' => 'XP Worth',
'id' => '_question_xp',
'type' => 'text_small'
) );
$cmb->add_field( array(
'name' => 'Questions to Display',
'desc' => 'Image URL',
'id' => '_total_questions',
'type' => 'select',
'default' => '4',
'options' => array(
'4' => '4',
'6' => '6',
'8' => '8'
),
) );
// $group_field_id is the field id string, so in this case: $prefix . 'demo'
$group_id = $cmb->add_field( array(
'id' => '_quiz_questions',
'type' => 'group',
'description' => 'A Question with Answers',
'options' => array(
'group_title' => 'Question {#}',
'add_button' => 'Add Another Question',
'remove_button' => 'Remove Question',
'sortable' => true
)
) );
$cmb->add_group_field( $group_id, array(
'id' => 'question',
'name' => __('Question', 'cgc-quiz'),
'type' => 'textarea',
'desc' => 'Type the question here.'
) );
$cmb->add_group_field( $group_id, array(
'id' => 'image',
'name' => __('Image', 'cgc-quiz'),
'type' => 'file',
'desc' => 'Optional image.'
) );
$cmb->add_group_field( $group_id, array(
'id' => 'answers',
'name' => __('Answers', 'cgc-quiz'),
'type' => 'text',
'sortable' => true,
'repeatable' => true,
'repeatable_max' => 10
) );
$cmb->add_group_field( $group_id, array(
'id' => 'correct',
'name' => __('Correct Answer', 'cgc-quiz'),
'type' => 'text'
) );