Html::jsAjaxDropdown PHP Method

jsAjaxDropdown() static public method

Create Ajax dropdown to clean JS
static public jsAjaxDropdown ( $name, $field_id, $url, $params = [] ) : String
$name
$field_id string id of the dom element
$url string URL to get datas
$params array of parameters must contains : - 'value' : default value selected - 'valuename' : default name of selected value
return String
    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+'&nbsp;&nbsp;&nbsp;';\n                                 i=i-1;\n                              }\n                              return a+'&raquo;'+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;
    }

Usage Example

ocsinventoryng is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with ocsinventoryng. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------
*/
include '../../../inc/includes.php';
header("Content-Type: text/html; charset=UTF-8");
Html::header_nocache();
Session::checkLoginUser();
// Make a select box
if (isset($_POST["itemtype"])) {
    $table = getTableForItemType($_POST["itemtype"]);
    $rand = mt_rand();
    if (isset($_POST["rand"])) {
        $rand = $_POST["rand"];
    }
    echo "<input type='hidden' name='tolink_itemtype[" . $_POST["id"] . "]' value='" . $_POST["itemtype"] . "'>";
    echo "<br>";
    $field_id = Html::cleanId("dropdown_" . $_POST['myname'] . $rand);
    $p = array('itemtype' => $_POST["itemtype"], 'table' => $table, 'myname' => $_POST["myname"], 'rand' => $_POST["rand"]);
    if (isset($_POST["used"]) && !empty($_POST["used"])) {
        if (isset($_POST["used"][$_POST["itemtype"]])) {
            $p["used"] = $_POST["used"][$_POST["itemtype"]];
        }
    }
    echo Html::jsAjaxDropdown($_POST['myname'], $field_id, $CFG_GLPI['root_doc'] . "/plugins/ocsinventoryng/ajax/getDropdownFindItem.php", $p);
}
All Usage Examples Of Html::jsAjaxDropdown
Html