Skip to content

Instantly share code, notes, and snippets.

@agustinprosperi
Created August 1, 2022 14:35
Show Gist options
  • Save agustinprosperi/f91132829dcb9718c8a43f857c331be9 to your computer and use it in GitHub Desktop.
Save agustinprosperi/f91132829dcb9718c8a43f857c331be9 to your computer and use it in GitHub Desktop.
Snippets para cmb2
<?php
/**
* Limitar maximo de items de un group field con la opcion rows_limit
* @param array $cmb_id The current box ID.
* @param int $object_id The ID of the current object.
* @param string $object_type The type of object you are working with.
* @param array $cmb This CMB2 object.
*/
add_action('cmb2_after_form', 'js_limit_group_repeat', 10, 4);
function js_limit_group_repeat($cmb_id, $object_id, $object_type, $cmb) {
// Encontrar un group field con rows_limit
$groupFields = array();
foreach ($cmb->meta_box['fields'] as $field) {
if ($field['type'] == 'group' && !empty($field['options']['rows_limit'])) {
$groupFields[] = array('id' => $field['id'], 'limite' => absint($field['options']['rows_limit']));
}
}
if (empty($groupFields)) {
return;
}
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var groupFields = <?php echo json_encode($groupFields) ?>;
$.each(groupFields, function(index, item) {
item.objeto = $('#' + item.id + '_repeat');
item.countRows = function() {
return this.objeto.find('> .cmb-row.cmb-repeatable-grouping').length;
};
item.disableAdder = function() {
this.objeto.find('.cmb-add-group-row').prop('disabled', true);
};
item.enableAdder = function() {
this.objeto.find('.cmb-add-group-row').prop('disabled', false);
};
item.cuenta = $('<span class="cmb2-metabox-description" style="padding: 0; line-height: 2.2; margin-left: 10px;"></span>');
item.objeto.find('.cmb-add-group-row').after(item.cuenta);
item.actualizarCuenta = function() {
this.cuenta.html(this.countRows() + ' - ' + this.limite + '.');
};
item.actualizarCuenta();
if (item.countRows() >= item.limite) {
item.disableAdder();
}
item.objeto.on('cmb2_add_row', function() {
item.actualizarCuenta();
if (item.countRows() >= item.limite) {
item.disableAdder();
}
})
.on('cmb2_remove_row', function() {
item.actualizarCuenta();
if (item.countRows() < item.limite) {
item.enableAdder();
}
});
});
});
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment