Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cakephp 3.x Sorting of another model is not working

I have two models Users & Roles

Here "Roles hasMany Users" and "Users belongsTo Roles"

When the user saved we're also asking user's role & record saved.

Problem : I have list of users with column firstname, lastname,roles. Each & Every column has sorting but on roles sorting is not working.

Role Table contains "name" field for Role name. I have referred below link but it doesn't working for me. Pagination Sort in Cakephp 3.x

UsersController:

public function index() {
     $this->paginate = [
                'contain' => ['Roles'],
                'conditions' => [
                    'Users.user_type <>' => 1
                ]
            ];

            $this->set('users', $this->paginate($this->Users));
            $this->set('_serialize', ['users']);
}

index.ctp

 <tr>
                <th><?php echo $this->Paginator->sort('firstname',__('First Name')) ?></th>
                <th><?php echo $this->Paginator->sort('lastname',__('Last Name')) ?></th>
                <th><?php echo $this->Paginator->sort('email',__('Email Address')) ?></th>
                <th><?php echo $this->Paginator->sort('Roles.name',__('Role Associated')) ?></th>
                <th><?php echo $this->Paginator->sort('status',__('status')) ?></th>
                <th class="actions"><?php echo __('action') ?></th>
            </tr>

Let me know any solution you have.

like image 637
Pratik Patel Avatar asked Apr 27 '15 10:04

Pratik Patel


Video Answer


2 Answers

You just have to use this:

$this->paginate = [
    'sortWhitelist'=>['Roles.name']
];
like image 194
Sainesh Mamgain Avatar answered Jan 04 '23 21:01

Sainesh Mamgain


UsersController.php

 $this->paginate = [
            'contain' => ['Roles'],
            'conditions' => [
                'Users.user_type <>' => 1
            ],
            'order' => ['Users.role_id' => 'ASC']
        ];

Use 'order' => ['Models.field' => 'ASC/DESC']

like image 45
Justin Atack Avatar answered Jan 04 '23 20:01

Justin Atack