Cakephp

Dynamically populate with ajax a chosen.js or select2.js styled multi select drop down

Dynamically populate with ajax a chosen.js or select2.js styled multi select drop down search values in database and display options, show selected options


Dynamically populate with ajax a chosen.js or select2.js styled multi select drop down

Here is how to create a mulit select drop down box in cakephp 3 - or any php driven site for that matter. The box will dynamically search the database for values then return it to the multi select as options, then display the selected ones as buttons.

Step 1 - incluce files

Make sure you have jquery included in your page then also include the select2.js and select2.css files in the header of your page.

Step 2 - incluce drop down multi select and javascript

fields you need to replace is MULTIDROPDOWNSELECTID, THECONTROLLER, THEAJAXACTION

 <?php
     echo $this->Form->input('MULTIDROPDOWNSELECTID', [
         'class' => 'form-control',
          'multiple'=>'multiple'
    ]);
?>
<script>
            $(document).ready(function() {

                $('#MULTIDROPDOWNSELECTID').select2({
                     width: '100%', 
                     dataType: 'json',
                     delay: 150,
                     debug:true,

                     ajax: {
                            url: ServerRootUrl+'THECONTROLLER/THEAJAXACTION/',
                            dataType: 'json',
                            processResults: function (data) {
                              return {results: data.VALUESRETUNEDFROM_CONTROLLER_THEAJAXACTION};
                     }
                    }

                });
            });
            <?php

            foreach ($returnarray as $value){
                echo 'var newOption = new Option("'.$value->name.'", '.$value->id.', true, true);';
                echo "$('#MULTIDROPDOWNSELECTID').append(newOption).trigger('change');";
            }
            ?>
            </script> 

Step 3 - code for the ajax action in the controller


      public function getttps()
    {

      $this->viewBuilder()->layout('ajax');
     
      $search  = $this->request->getQuery('term');

      $VALUESRETUNEDFROM_CONTROLLER_ACTION = $this->TNEMODEL->find('all', [

        'conditions' => ['TNEMODEL.name LIKE' => "%$search%"],

        //$this->log($VALUESRETUNEDFROM_CONTROLLER_ACTION, 'debug'); 
        
        $this->set(compact('VALUESRETUNEDFROM_CONTROLLER_THEAJAXACTION'));

    }

Step 3 - code for the ajax view

<?php
$out = [
    'results'=>$VALUESRETUNEDFROM_CONTROLLER_THEAJAXACTION,    
];
echo json_encode($out);
?>

Step 3 - Massaging the data

select2 expects its ajax input in a really particular format .. {id:x, text:y} So for this reason we are going to create a virtual field in the enties, it is easier than you think. So if your controller/action is something like users/index you need to go to Model/Entity/User.php

    protected $_virtual = ['text'];
    
    //There are often fields you do not want exported in JSON or array formats.
    //remove all the fields you do not want in the json data string, you only want id:x, text:y
    protected $_hidden = ['field1','field2','field3'];
    
   
  protected function _getText(){
        return $this->name;
    }

That's all folks !

Published: 27th March 2019 by Gabriel Kolbe

Adverts