-
Notifications
You must be signed in to change notification settings - Fork 21
Group fields
Travis van der F edited this page Sep 11, 2018
·
8 revisions
Now you can setup rows and columns even on group fields too. First Create your cmb2 metabox with group fields like you are used to:
$prefix = '_yourprefix_group_';
$cmb_group = new_cmb2_box(array
(
'id' => $prefix . 'metabox',
'title' => __('Repeating Field Group', 'cmb2'),
'object_types' => array('page',),
));
$field1 = $cmb_group->add_field(array
(
'name' => __('Test Text', 'cmb2'),
'desc' => __('field description (optional)', 'cmb2'),
'id' => $prefix . 'text',
'type' => 'text',
));
$field2 = $cmb_group->add_field(array
(
'name' => __('Test Text Small', 'cmb2'),
'desc' => __('field description (optional)', 'cmb2'),
'id' => $prefix . 'textsmall',
'type' => 'text',
));
// $group_field_id is the field id string, so in this case: $prefix . 'demo'
$group_field_id = $cmb_group->add_field(array
(
'id' => $prefix . 'demo',
'type' => 'group',
'options' => array
(
'group_title' => __('Entry {#}', 'cmb2'), // {#} gets replaced by row number
'add_button' => __('Add Another Entry', 'cmb2'),
'remove_button' => __('Remove Entry', 'cmb2'),
'sortable' => true,
),
));
$gField1 = $cmb_group->add_group_field($group_field_id, array
(
'name' => __('Entry Title', 'cmb2'),
'id' => 'title',
'type' => 'text',
));
$gField2 = $cmb_group->add_group_field($group_field_id, array
(
'name' => __('Description', 'cmb2'),
'description' => __('Write a short description for this entry', 'cmb2'),
'id' => 'description',
'type' => 'textarea_small',
));
Now pay attention to the addCmb2GroupGrid() method
if (!is_admin())
{
return;
}
// Create a default grid
$cmb2Grid = new \Cmb2Grid\Grid\Cmb2Grid($cmb_group);
// Create now a Grid of group fields
$cmb2GroupGrid = $cmb2Grid->addCmb2GroupGrid($group_field_id);
$row = $cmb2GroupGrid->addRow();
$row->addColumns(array($gField1, $gField2));
// Now setup your columns like you generally do, even with group fields
$row = $cmb2Grid->addRow();
$row->addColumns(array($field1, $field2));
$row = $cmb2Grid->addRow();
$row->addColumns(array($cmb2GroupGrid)); // Can be $group_field_id also