tetranz / select2entity-bundle

A Symfony2 bundle that integrates Select2 as a drop-in replacement for a standard entity field on a Symfony form.
MIT License
218 stars 110 forks source link

Feature : add custom dynamic parameters to ajax query #151

Closed CPASimUSante closed 4 years ago

CPASimUSante commented 5 years ago

In the documentation, you can pass other field value to change the query, but in my case, i need to add a custom parameter whose values would be dynamically modified.

My select2 element retrieve users (user1, user2, user3, user4) . If i select a date, i have an ajax query that returns users that i shouldn't be able to select (user2, user4). So i would like that the banned users be added in a custom parameter (in a custom data attribute of the select2), so that when i type in the select2 they wouldn't appear in the results : only user1, user3.

I don't see how this would be possible with the current implementation. Thank you

DubbleClick commented 5 years ago

I've actually implemented this already. It's very easy by just extending the $.select2entity() function and adding some code to the select2_widget:

{% block select2_entity_widget %}
{% if extra_parameters %}
        {% set attr = attr|merge({
            'data-extra-parameters': extra_parameters|json_encode
        }) %}
    {% endif %}
    {{ parent() }}
{% endblock %}
$.fn.myselect2entity = function (options) {
    let extraparameters = $s2.data('extra-parameters');
                        if (Array.isArray(extraparameters) ||
                            typeof extraparameters === 'object') {
                            for (var key in extraparameters) {
                                ret[key] = extraparameters[key];
                            }
                        }

Ugh, I should really just do the PR for a 3.0 branch.

DubbleClick commented 5 years ago

I've opened a PR to implement the functionality into the bundle, see PR #152 With this PR you can now change the remote parameters by calling

$('#mySelect').data('query-parameters',
    $.extend({}, { 'paramtochange': 'queryparam' },
        $('#mySelect').data('query-parameters')
);

Thinking of it, would you like to be able to pass jQuery selectors to 'query_parameters' such as

$builder->add('list', Select2Entity::class, [
    // ...
    'query_parameters' => [
        'paramname' => '#form_someChangingElement'
    ]
]);

of which it will then automatically use the value whenever firing off an ajax request? How would error handling happen then, however? I'd expect a fairly high change of failure that wouldn't be as easy to track down.

DubbleClick commented 4 years ago

@CPASimUSante the PR was merged so you can now change the parameters as I stated

CPASimUSante commented 4 years ago

Thank you, it will be very useful.