Is It Possible To Use `switch_user` Through A Search Field?
Solution 1:
That is an associated array in PHP:
var searchnames = [
"Smith, John" => "jsmith",
"Doe, Jane" => "jdoe1990",
];
In JavaScript, you only have normal arrays and objects. An object can be used for key/value pairs.
The source option can take an array of objects. Each object has a value
and label
property.
[{"label":"Smith, John","value":"jsmith"},{"label":"Doe, Jane","value":"jdoe1990"}]
If you have a fixed set of users, you can simply add them to your JavaScript function and that's that.
However the users are probably come from a database. You can create an object of all users in the system, pass them to the (Twig) view and output them using the json_encode
filter. However this is bad practice as it bloats the HTML and increases security risk. (o.a. All the users are still in the browser cache, even when you log out.)
Instead you probably want to use AJAX. You can set the source
option to a URL, which is handled by your user controller. (See the jQuery UI remote example.)
$("#search-names).autocomplete({
source: "/users/search"
});
The search action query the database and create an array with associated arrays each having a value
and label
key. Than output it as JSON.
Last you want to do to load the page when an option is selected. This can be done in JavaScript by setting window.location
.
$("#search-names").autocomplete({
source: "/users/search",
change: function() {
var username = $(this).val();
if (!username) return;
window.location = window.location + '?_switch_user=' + username;
}
});
The code is untested an may require some modifications to make it actually work.
Post a Comment for "Is It Possible To Use `switch_user` Through A Search Field?"