DEV Community

Sahil kashyap
Sahil kashyap

Posted on

Pagination in selectbox/dropdown, Optimal way to show large data in selectbox using select2

Select2 requires a response like this for pagination to work

{
  "results": [
    {
      "id": 1,
      "text": "Option 1"
    },
    {
      "id": 2,
      "text": "Option 2"
    }
  ],
  "pagination": {
    "more": true
  }
}
Enter fullscreen mode Exit fullscreen mode

we can generate this response by modifying the pagination in laravel

<?php

namespace App\Http\Controllers;

class SomeController extends Controller
{
   public function getdataforselect2(Request $request){

        if ($request->ajax()) {

            $term = trim($request->term);
            $posts = DB::table('channels')->select('id','name as text')
                ->where('name', 'LIKE',  '%' . $term. '%')
                ->orderBy('name', 'asc')->simplePaginate(10);

            $morePages=true;
           $pagination_obj= json_encode($posts);
           if (empty($posts->nextPageUrl())){
            $morePages=false;
           }
            $results = array(
              "results" => $posts->items(),
              "pagination" => array(
                "more" => $morePages
              )
            );

            return \Response::json($results);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode
//api.php

Route::get('/tags', function() {
    return view('Somefolder.index');
});
Route::get('dataforselect2', 'SomeController@getdataforselect2')->name('dataforselect2');
Enter fullscreen mode Exit fullscreen mode
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
    <link rel="stylesheet" href="style.css" />
  </head>
  <body>
  <div class="container">
  <div class="page-header">
    <h1>select2 with pagination</h1>
    </div>
    <select id='channel_id' style='width: 200px;'>
        <option value='0'>- Search Channel -</option>
     </select>
    </div>
    <script type="text/javascript" src='//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
    <!--<![endif]-->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script> <script >

(function() {

  $("#channel_id").select2({
    placeholder: 'Channel...',
    // width: '350px',
    allowClear: true,
    ajax: {
        url: '/dataforselect2',
        dataType: 'json',
        delay: 250,
        data: function(params) {
            return {
                term: params.term || '',
                page: params.page || 1
            }
        },
        cache: true
    }
});
})();

    </script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

gist of all the code

Top comments (0)