Recently, I had the need to have a dropdown field in a CRUD add/edit form where the choices would be listed, but also provide the User the ability to add a value not in the list. After some searching, I discovered Koen Punt's fork of Harvest's Chosen jQuery plugin. He has implemented this feature and as integrated it into the latest version of chosen.
github => https://github.com/koenpunt/chosen
Discussion of around original request of feature => https://github.com/harvesthq/chosen/pull/166
What I did was extend Grocery_crud.php with a 2 new field_types "multiselectadd", "dropdownadd"
in get_field_input(...)
- added these 2 new types to $types_array
- and included the extra case(s) (with add) after the original
Copied the function definition of get_dropdown_input() => get_dropdownadd_input() modifying class='chosen-select-add'
Also, the similar copy, modification for get_multiselect_input() => get_multiselectadd_input() modifying class='chosen-multiple-select-add'
then modify assets/grocery_crud/js/jquery_plugins/config/jquery.chosen.config.js
to include the following:
$(".chosen-select-add,.chosen-multiple-select-add").chosen({allow_single_deselect:true, create_option: function(term){ var chosen = this; chosen.append_option({ value: term, text: term }); } });
Now, using $crud->field_type('my_field', 'dropdownadd', /* function array of id => value */ ); results in a pop-up which shows the choices for that field, and also allows the User to enter a new value for that field.
You will need to write a $crud->callback_insert() and $crud->callback_update() to handle the special case where "my_field" is the new string value, rather than the integer index value.
$my_field = $post['my_field']; if( $my_field != '' ){ if( preg_match("/^\d+$/", $my_field) ){ /* Yes, this is an index */ } else { /* New value entered */ } }