tuupola / jquery_chained

Chained Selects for jQuery and Zepto
https://appelsiini.net/projects/chained/
589 stars 283 forks source link

Adds the trasform callback that create the option from key and value #57

Open fcamp opened 7 years ago

fcamp commented 7 years ago

Can be used to modify the option. By default, the options can have just a value and a label, but in this way data properties can be added or we can apply other transformations.

For example when I change an option, I could load the associated image, or check if that item is a leaf or it has children, without having to launch a request, but using the data from the json response I get on change.

tuupola commented 7 years ago

I kind of like this, but I have hard time figuring out the use case you explained. Do you have an example code snippet how you use it at the moment?

fcamp commented 7 years ago

I have a category tree which is not uniform. Sometimes the leaf (a category with 0 children) are at level 0, sometimes they are at level 1 or 2.

Whenever I find a leaf, I set an hidden field (coming from a symfony form), with the category id.

Without the transform callback, I should request the server just to know if that category is a leaf or not.

In this way we can work with a richer json response, not just the {"key":"value"}

This is the callback applied to each item on the server side

<?php
    ...

    /**
     * @param Category $category
     * @return array
     */
    public function transform(Category $category)
    {
        return [
            $category->getId() => [
                'label' => $category->getTitle(),
                'children' => $category->getChildrenCount(),
            ]
        ];
    }

This is part of the js code

$("#js-category-1").remoteChained({
    parents: "#js-category-0",
    url: "/my/url",
    loading: {'label': 'Loading...'},
    transform: function (key, value) {
        return $('<option/>', {
            'data-has-children': value.children,
            'value': key
        }).append(value.label);
    }
});
fcamp commented 6 years ago

Hi, Is there any chance that this change will be merged?