Separate custom markup for results and final value
See original GitHub issueI have a Python autocomplete view returning custom markup. (I need to disambiguate possibly duplicate names using email addresses so I need the name and the email in the search results.)
class MyAutocompleteView(autocomplete.Select2QuerySetView):
def get_result_label(self, item):
return f"""
<div class="modelchoice-search-result">
<div class="modelchoice-search-name">{item.name}</div>
<div class="modelchoice-search-email">{item.email}</div>
</div>
"""
This ultimately generates the html below inside <span class="select2 select2-container>
(I’ve omitted a few containers/levels for clarity).
<span class="select2-selection__rendered" id="select2-id_form-13-child-container" title="
<div class="modelchoice-search-result">
<div class="modelchoice-search-name">Firstname Lastname</div>
<div class="modelchoice-search-email">email@example.com</div>
</div>
"><span class="select2-selection__clear">×</span><span>
<div class="modelchoice-search-result">
<div class="modelchoice-search-name">Firstname Lastname</div>
<div class="modelchoice-search-email">email@example.com</div>
</div>
</span></span>
So, it looks like the markup template is used for both the display of the results and also as the value that is added to the widget upon selection. That’s fine, I guess that makes sense as much as not. But is there any way I can separate out the display of the results from the final value that is added to the field? In this case, for example, I want to omit the email and be left just with the name.
I’ve tried just deleting that DOM node and other hacks, I’ve tried those by attaching to both the change
event and also select2’s select2:close
event, etc. But there seems to be some DOM manipulation happening that I’m not able to override and so I’m always ultimately left with the full template being added to the box. Any suggestions would be much appreciated, I’d prefer not to have to fork and hack the template logic in autocomplete_light/select2.js
.
Issue Analytics
- State:
- Created 6 years ago
- Comments:7 (4 by maintainers)
@jhrr you can do it with Select2 but unfortunately you’ll have to hack
autocomplete_light/select2.js
. Select2 initalization has two parameter functions:templateResult
andtemplateSelection
, one for rendering choices in the dropdown and one to render the selected choice. Unfortunately DAL currently does not allow to use different templating functions fortemplateResult
andtemplateSelection
Ah great 😃