Skip to content

Instantly share code, notes, and snippets.

@templeman
Last active February 11, 2021 23:48
Show Gist options
  • Save templeman/b60d4d3f536c96520fdabc4c08164433 to your computer and use it in GitHub Desktop.
Save templeman/b60d4d3f536c96520fdabc4c08164433 to your computer and use it in GitHub Desktop.
CMB2 metabox with custom after_group_row callback
/**
* CMB2 Metabox Registration: Product Rooms
*/
function register_product_room_metabox()
{
$prefix = 'product_';
for ($idx = 0; $idx < 14; $idx++) {
$product_rooms_box = new_cmb2_box([
'id' => $prefix . 'rooms_box_'.$idx,
'title' => rooms_box_title($idx, 'Rooms'),
'object_types' => ['product'],
'context' => 'normal',
'priority' => 'high',
'classes' => 'cmb2-product-rooms',
'iterator' => $idx, // used by variations_box_show_on_cb function
'show_on_cb' => 'variations_box_show_on_cb',
]);
// rooms, repeatable group
$product_rooms_lines = $product_rooms_box->add_field([
'id' => $prefix . 'rooms_'.$idx,
'type' => 'group',
'description' => product_rooms_description(),
'repeatable' => true,
'options' => [
'group_title' => __('Room {#}', 'moad'),
'add_button' => __('Add Another Entry', 'moad'),
'remove_button' => __('Remove Entry', 'moad'),
'sortable' => true,
'closed' => true, // true to have the groups closed by default
],
# This is our custom callback function for outputting dynamic HTML
'after_group_row' => 'rooms_after_group_row',
]);
$product_room_id = $product_rooms_box->add_group_field($product_rooms_lines, [
'id' => $prefix . 'room_id',
'name' => __('Room ID', 'moad'),
'desc' => esc_html__('eg, &quot;room5&quot;', 'moad'),
'type' => 'text_small',
]);
$product_room_supplement = $product_rooms_box->add_group_field($product_rooms_lines, [
'id' => $prefix . 'room_supplement',
'name' => __('Room Supplement', 'moad'),
'desc' => esc_html__('$ Per Room', 'moad'),
'type' => 'text_money',
])
}
}
/**
* CMB2 Custom display callback
*/
function rooms_after_group_row($field_args, $field)
{
/**
* The 'unset_param_callback_cache()' function, taken from the CMB2.php plugin definition, does nothing here.
* Probably needs to be invoked earlier, but where?
*/
$field->unset_param_callback_cache('after_group_row');
if (!empty($field->value[$field->index])) {
echo '<div class="cmb-row">';
echo '<div class="product-rooms-summary col-md-12">';
if (!empty($field->value[$field->index]['product_room_supplement'])) {
# Here we want to output the fresh value - getting cached value instead
echo " <b>Room Supplement:</b> $".intval(preg_replace("/[^\-.0-9]/","",$field->value[$field->index]['product_room_supplement']));
}
if (!empty($field->value[$field->index]['product_room_id'])) {
# Here we want to output the fresh value - getting the cached value instead
echo " <b>Room ID:</b> ".($field->value[$field->index]['product_room_id']);
}
echo "</div>\n";
echo "</div>\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment