Adding comma separated username autocomplete to a D7 form
Today I needed to add autocomplete to a field that could contain comma separated usernames and obviously the requirements included autocomplete. I thought this problem must be solved already in the ecosystem and sure, Views has it already. So I have added '#autocomplete_path' => 'admin/views/ajax/autocomplete/user', '#element_validate' => array('my_module_usernames_validate')
and then
<span style="color: #000000"><span style="color: #0000BB"><?php<br></span><span style="color: #007700">function </span><span style="color: #0000BB">my_module_usernames_validate</span><span style="color: #007700">(&</span><span style="color: #0000BB">$element</span><span style="color: #007700">) {<br> if (</span><span style="color: #0000BB">$values </span><span style="color: #007700">= </span><span style="color: #0000BB">drupal_explode_tags</span><span style="color: #007700">(</span><span style="color: #0000BB">$element</span><span style="color: #007700">[</span><span style="color: #DD0000">'#value'</span><span style="color: #007700">])) {<br> </span><span style="color: #FF8000">// Good thing Views doesn't use the native constructor.<br> </span><span style="color: #0000BB">$handler </span><span style="color: #007700">= new </span><span style="color: #0000BB">views_handler_filter_user_name</span><span style="color: #007700">();<br> </span><span style="color: #FF8000">// And this function doesn't use the object at all.<br> </span><span style="color: #0000BB">$handler</span><span style="color: #007700">-></span><span style="color: #0000BB">validate_user_strings</span><span style="color: #007700">(</span><span style="color: #0000BB">$element</span><span style="color: #007700">, </span><span style="color: #0000BB">$values</span><span style="color: #007700">);<br> }<br>}<br></span><span style="color: #0000BB">?></span></span>
Ps. This has been confirmed as working (with a plugin instance) in D8 too.