Autocomplete doesn't work if field id starts not from underscore symbol
Closed this issue · 2 comments
$cmb->add_field( array(
'name' => __( 'Author', 'bt-task' ),
'id' => '_author', // DO WORK
//'id' => 'author', DOESN'T WORK
'type' => 'autocomplete',
'options' => array(
array('value' => 1, 'name' => 'Admin'),
array('value' => 2, 'name' => 'Oleg'),
array('value' => 3, 'name' => 'Grisha')
)
) );
Took me way too much time trying to debug this one to realize why it's not working.
The key part is from here:
// Set up the autocomplete field. Replace the '_' with '-' to not interfere with the ID from CMB2.
$id = str_replace('_', '-', $field_object->args['id']);
Without the prefix in the field type ID used, the $id
variable ends up not having anything replaced from the str_replace()
function. Along with this, the markup is getting two inputs with the same ID. The first one is a hidden field and the one referenced in "Replace the '_' with '-' to not interfere with the ID from CMB2.". Because it's the one found by the js, there's no visible UI to attach the autocomplete to.
When there is a prefix, the $id
ends up being -someID
and thus not matching as a duplicate.
I am going to push up a change to the sample code that looks as such:
// Set up the autocomplete field. Replace the '_' with '-' to not interfere with the ID from CMB2.
$id = str_replace( '_', '-', $field_object->args['id'] );
if ( '_' !== substr( $field_object->args['id'], 0, 1 ) ) {
$id = '-' . $field_object->args['id'];
}
It will check if the ID is lacking a prefixed underscore already, and if so, prefix with the dash.