static function jsAjaxDropdown($name, $field_id, $url, $params = array())
{
global $CFG_GLPI;
if (!isset($params['value'])) {
$value = 0;
} else {
$value = $params['value'];
}
if (!isset($params['value'])) {
$valuename = Dropdown::EMPTY_VALUE;
} else {
$valuename = $params['valuename'];
}
$on_change = '';
if (isset($params["on_change"])) {
$on_change = $params["on_change"];
unset($params["on_change"]);
}
$width = '80%';
if (isset($params["width"])) {
$width = $params["width"];
unset($params["width"]);
}
unset($params['value']);
unset($params['valuename']);
$options = array('value' => $value, 'id' => $field_id);
if (!empty($params['specific_tags'])) {
foreach ($params['specific_tags'] as $tag => $val) {
if (is_array($val)) {
$val = implode(' ', $val);
}
$options[$tag] = $val;
}
}
$output = Html::hidden($name, $options);
$js = "";
$js .= " \$('#{$field_id}').select2({\n width: '{$width}',\n minimumInputLength: 0,\n quietMillis: 100,\n dropdownAutoWidth: true,\n minimumResultsForSearch: " . $CFG_GLPI['ajax_limit_count'] . ",\n closeOnSelect: false,\n ajax: {\n url: '{$url}',\n dataType: 'json',\n type: 'POST',\n data: function (term, page) {\n return { ";
foreach ($params as $key => $val) {
// Specific boolean case
if (is_bool($val)) {
$js .= "{$key}: " . ($val ? 1 : 0) . ",\n";
} else {
$js .= "{$key}: " . json_encode($val) . ",\n";
}
}
$js .= " searchText: term,\n page_limit: " . $CFG_GLPI['dropdown_max'] . ", // page size\n page: page, // page number\n };\n },\n results: function (data, page) {\n// var more = (page * " . $CFG_GLPI['dropdown_max'] . ") < data.total;\n// alert(data.count+' '+" . $CFG_GLPI['dropdown_max'] . ");\n var more = (data.count >= " . $CFG_GLPI['dropdown_max'] . ");\n return {results: data.results, more: more};\n// return {results: data.results};\n }\n },\n initSelection: function (element, callback) {\n var id=\$(element).val();\n var defaultid = '{$value}';\n if (id !== '') {\n // No ajax call for first item\n if (id === defaultid) {\n var data = {id: " . json_encode($value) . ",\n text: " . json_encode($valuename) . "};\n callback(data);\n } else {\n \$.ajax('{$url}', {\n data: {";
foreach ($params as $key => $val) {
$js .= "{$key}: " . json_encode($val) . ",\n";
}
$js .= " _one_id: id},\n dataType: 'json',\n type: 'POST',\n }).done(function(data) { callback(data); });\n }\n }\n\n },\n formatResult: function(result, container, query, escapeMarkup) {\n container.attr('title', result.title);\n var markup=[];\n window.Select2.util.markMatch(result.text, query.term, markup, escapeMarkup);\n if (result.level) {\n var a='';\n var i=result.level;\n while (i>1) {\n a = a+' ';\n i=i-1;\n }\n return a+'»'+markup.join('');\n }\n return markup.join('');\n }\n\n });";
if (!empty($on_change)) {
$js .= " \$('#{$field_id}').on('change', function(e) {" . stripslashes($on_change) . "});";
}
$output .= Html::scriptBlock($js);
return $output;
}