Tiamo Idzenga
Tiamo Idzenga

Reputation: 1186

How to add a default ordering of ListEntries table in Backpack for Laravel?

When a user first visits the page, the ListEntries table is ordered ascending by id and none of the ordering icons in the table header are active.

I would like to have the ListEntries table ordered by a column of my choosing, including having the icon next to this column active (either ascending or descending).

Is there a way to have the ListEntries table ordered by a column of my choosing when a user visits the page?

Upvotes: 4

Views: 3928

Answers (3)

Ayman Elshehawy
Ayman Elshehawy

Reputation: 2964

Use this key orderable it is a boolean

 this->crud->addColumn([
   'label'      => 'Category',
   'type'       => 'select',
   'name'       => 'category_id', // the db column for the foreign key
   'entity'     => 'category', // the method that defines the relationship in your Model
   'attribute'  => 'name', // foreign key attribute that is shown to user
   'orderable'  => true,
   'orderLogic' => function ($query, $column, $columnDirection) {
        return $query->leftJoin('categories', 'categories.id', '=', 'articles.select')
            ->orderBy('categories.name', $columnDirection)->select('articles.*');
    }
]);

Reference

Upvotes: 2

tjarrett
tjarrett

Reputation: 126

This can be done by manipulating the request object, which may be frowned upon in some circles.

This solution will also update the order icon on the appropriate column.

There are a number of ways to accomplish this, but one way would be to add the following to the setupListOperation() method of your Controller.

/** @var \Illuminate\Http\Request $request */
$request = $this->crud->getRequest();
if (!$request->has('order')) {
    $request->merge(['order' => [
        [
            'column' => 'column-index-here',
            'dir' => 'asc'
        ]
    ]]);
}

Upvotes: 4

tabacitu
tabacitu

Reputation: 6223

In your Controller's setup() method you can use:

$this->crud->orderBy('name', 'DESC');

Anything you pass to the orderBy() statement will be used on the Eloquent query.

By default, columns for real attributes (that have a correspondent column in the database) should be orderable. But you can also manually specify 'orderable' => true for columns, or define your own order logic. Note that relationship columns (1-n, n-n), model_function or model_function columns are NOT orderable by default, but you can make them orderable with orderLogic.

Hope it helps.

Upvotes: 5

Related Questions