Note the upgraded forum! If you are experiencing issues logging in, you may need to reset your password which should send an email. If the email doesn't arrive, be sure to check your spam folder just in case.

Ajax for a Select2 with a long list of elements

Hi!
I have a select2 field with loads a huge list of data (13000+ items). This makes the page load very slow and it's very annoying.
I've already set the "minimumInputLength" setting to 3 but the page load is still loading all the data at the beginning.
Is there anyway to set an Ajax source for the select2 field? Or pagination? Or any other idea to speed up the page loading?

Thank you!
Jaime

Comments

  • You can, but it will require a little bit of javascript code. Also, if the options values for the field are automatically being added by FUEL because of a relationship (e.g. foreign_key), you can prevent that overhead by removing the relationship before rendering the form_fields().

    public function form_fields($values = array(), $related = array())
    {
        unset($this->foreign_keys['my_foriegn_key']);
        $fields = parent::form_fields($values, $related);
        return $fields;
    }
    

    To add the javascript fo the page, there is some information on how to do that (there are various ways). There is also a section about ajaxing in option results which it sounds like you'll want:
    https://docs.getfuelcms.com/general/javascript

  • edited May 28

    Ok. It's working now.
    I needed to update the select2 plugin to the new version.
    I removed the field from the foreign_keys array. Then I assign the "select" type (not the "select2" type) to it.
    Then I added the following code to the form_fields method:

    $fields['id_pop']['js'] = "
        <script>
            $(document).ready(function() {                  
                $('#id_pop').select2({
                    language: 'es',
                    placeholder: 'Escriba un título',   
                    minimumInputLength: 3,                  
                    ajax: {
                        url: 'http://ivac.local/admin/p.php',
                        dataType: 'json',
                        data: function (params) {
                            var query = {
                                term: params.term
                            }                           
                        return query;
                        }
                    },                                              
                });
            });
        </script>
    ";
    

    In the case that the select2 library is not loaded, I have to load it.
    I needed to add an option to the "select" field with the previous values when it has one.

    Now a would like to change the p.php testing script by a method in the POP model.

    Thanks for your help!
    Jaime

Sign In or Register to comment.