Code snippets for symfony 1.x


Refine Tags

Snippets tagged "alphabetical"

Alphabetical index

Suppose you have a list of items (products, contacts, etc) that you want to look up by name. You want them paginated by letter of the alphabet, not by a certain number of items on each page (the default pagination behavior). You will have a navigator that includes every letter of the alphabet, but only the letters that actually have items will be links. The current letter you are looking at will be highlighted. This is similar to a phone book.


The drawback to using this method is that the entire contents of the table have to be loaded for each page in order to build the array of first letters for the navigator. Perhaps there would be a way to query the database for just the DISTINCT first letters of the LNAME field, in effect: SELECT DISTINCT substr(lname,1,1) FROM phonebook. If anyone knows how to go about that, please comment.

First, create your action in action.class.php:

public function executeList()
  $c = new Criteria();
  $entries = PhoneBook::doSelect($c);
  //now we need an array of all the first letters.  
  //At the same time we're looping, we'll put all the 
  //items we need for this page into a separate array
  $pageLetter = strtoupper($this->getRequestParameter('page','A'));
  $arrayOfFirstLetters = array();
  $thisList = array();
  foreach($entries as $entry)
    $firstLetter = strtoupper(substr($entry->getLName(),0,1));
      $thisList[$y++] = $entry;
  $arrayOfFirstLetters = array_unique($arrayOfFirstLetters);
  //make the arrays available to the page template
  $this->page = $pageLetter;
  $this->pageLinks = $arrayOfFirstLetters;
  $this->names = $thisList;

And the template, listSuccess.php:

<?php include_partial('alphaPager',array('letters'=>$pageLinks,'thisPage'=>$page)) ?>
  <?php foreach ($names as $name): ?>
        <?php echo link_to($name->getLName().', '.$name->getFName(), 'phonebook/show?id='.$name->getId()) ?>
  <?php endforeach; ?>

And now the partial template, _alphaPager.php:

<div id="alphapager">
    echo ' | ';
    echo '<font class="alhpaHL">'.$x.'</font>';
      echo link_to($x,'phonebook/list?page='.$x);
      echo $x;
by Eric Heimerman on 2006-06-12, tagged alphabetical  pagination