phpsortingcakephp

sort by alphabetical field


I need alphabetical order of how the name from a list. What I need to do while I occupied the pager CakePHP but I could not be. I thought in order by the field (in this case the name) so DESC and ASC does not work me in any case.

In Controller :

$conditions = array('active !=' => -1, 'NOT' => array('role_id' => 2));
$users = $this->paginate('User', $conditions);
$this->set(compact('users','filter'));

In View :

<div class="row">
<table class="table table-striped table-hover table-condensed col-lg-12">
<thead>
    <tr>
        <th>#</th>
        <th><?=$this->Paginator->sort('username', h(__('User')));?></th>
        <th><?=$this->Paginator->sort('name');?></th>
        <th><?=$this->Paginator->sort('email');?></th>
        <th><?=$this->Paginator->sort('created', h(__('Registration date')));?></th> 
        <th><?=$this->Paginator->sort('active', h(__('Status')));?></th>
    </tr>
</thead>
<tbody>
    <?php
    $offset = $this->Paginator->counter(array('format' => '{:start}'));
    foreach($users as $user) {
        echo '<tr onclick="window.location.href=\''.$this->Html->url(array('controller'=>'users','action'=>'view',
                $user['User']['id'])).'\'">'.
                '<td>'.($offset++).'</td>'.
                '<td>'.h($user['User']['username']).'</td>'.
                '<td>'.h($user['User']['name'].' '.$user['User']['father_surname'].' '.$user['User']['mother_surname']).'</td>'.
                '<td>'.str_replace('@','[at]',h($user['User']['email'])).'</td>'.
                '<td>'.$this->Time->format('d-m-Y H:i',strtotime($user['User']['created'])).'</td>'.
                '<td>';
                if ($user['User']['active'] == 1)
                    echo '<span class="label label-success">'.h(__('Active')).'</span>';
                else
                    echo '<span class="label label-warning">'.h(__('Blocked')).'</span>';
                echo '</td>'.
            '</tr>';
    }
    ?>
</tbody>
</table>
</div>

Solution

  • Add the following after your conditions

    $this->User->order(
                       array('User.username ASC') //use whatever field you want to sort
                       );