How to Ajaxify your relationship with Cook
Update field type to Ajax:
<field name="users"
alias="_user_id_name"
label="TEST_FIELD_NAME"
filter="array"
multiple="true"
type="ckajax"
labelKey="_user_id_name"
ajaxContext="test.users.ajax.users"/>
Build an Ajax routine to return the html element:
case 'users':
/* Ajax List : Test
* Called from: view:test, layout:test
*/
// Get only the selected items from the pivot table.
// Remember to create the filter on the pivot model
$model = CkJModel::getInstance('Pivot', 'XxxModel');
$model->setState('filter.group', 'Registered');
$items = $model->getItems();
foreach ($items as $key => $item)
$selected[] = $item->user_id;
// Get all the registered users from the users table
// to populate the dropdown
$model = $this->getModel();
$model->setState('filter.group_title', 'Registered');
$items = $model->getItems();
// Build the selectbox and mark the selected entries
// This will create a standard select on the target form
echo '<input type="hidden" name=jform[users][] value=""/>';
echo '<select id="jform_users" name="jform[users][]" multiple>';
foreach ($items as $key => $item)
echo "<option". (in_array($item->id, $selected) ? " selected " : " ") . "value=\"" . $item->id . "\">" . $item->_user_id_name . "</option>";
echo '</select>';
// Here is the magic, Cook uses "chosen" to transform the
// selectbox. You can pass the jQuery call as below or
// place it in the ajax Complete in a js file or wherever
echo '<script>jQuery("select[id$=\'jform_users\']").chosen({"disable_search_threshold":10,"search_contains":true,"allow_single_deselect":true,"placeholder_text_multiple":"Type or select some options","placeholder_text_single":"Select an option","no_results_text":"No results match"});';
break;
The multi-select relationship now works like the native cook n:m box but loads after the form is built. The model code is missing but is child's play for most cook users.
This idea can be applied to any n:m relation.
Good luck. . . .