phpjqueryajaxcakephppagination

How to set cakephp pagination records limit dynamic


So far, I can load results by setting a static limit. But for my puroposes, I need that limit could be set by a function which generates a number between 2-8 everytime that there is a new call for more results (I've already did that function, but dont know where place it in code)

function random_cols () {
 $min_cols=2;
 $max_cols=8;
 $cols = array();
 $n = rand($min_cols,$max_cols);
 array_push($cols, $n);
 $var = 12 - $n;
 while ($var>0) {
  $n = rand($min_cols,$var);
  if ($var-$n<=1) {
   $n = $var;
  }
 $var = $var - $n;
 array_push($cols, $n);
 }
 return $cols;
}

$mylimit_arr = random_cols ();
$mylimit = count($mylimit_arr);

controller:

public $paginate = array(
        'limit' => $mylimit,
        'order' => array('Post.id' => 'asc' ),      
);

public function index() {

    $posts = $this->paginate('Post');   
        $this->set('posts', $posts);

}

view (using infinitescroll plugin):

<div id="posts-list"> 
 <div class="post-item"></div>
</div>

<script>
  $(function(){
    var $container = $('#posts-list');

    $container.infinitescroll({
      navSelector  : '.next',    // selector for the paged navigation 
      nextSelector : '.next a',  // selector for the NEXT link (to page 2)
      itemSelector : '.post-item',     // selector for all items you'll retrieve
      debug         : true,
      dataType      : 'html',
      loading: {
          finishedMsg: 'No more posts to load. All Hail Star Wars God!',
          img: '<?php echo $this->webroot; ?>img/spinner.gif'
        }
      }
    );
  });

</script>

You may wonder why I need that, but its because of design and the way I display results


Solution

  • $this->paginate = array('limit' => $mylimit);
    

    Does the trick.

    Your controller should look like this:

    public function index() {
      $mylimit_arr = random_cols();
      $mylimit = count($mylimit_arr);
      $this->paginate = array(
        'order' => array('Post.id' => 'asc'),
        'limit' => $mylimit
      );
      $posts = $this->paginate('Post');   
    
      $this->set('posts', $posts);
    }