orchidsoftware / crud

Simplify the process of building CRUD (Create, Read, Update, Delete) functionality in Laravel using the features of Orchid.
https://orchid.software
MIT License
138 stars 34 forks source link

Ability to set default sorting column on List screen #5

Closed pqr closed 3 years ago

pqr commented 3 years ago

I am looking for a method to set default sorting column in CRUD. I need some option or method inside Resource class to define default sort column.

This is how it works in "classic" list screen: https://orchid.software/en/docs/quickstart-sort-filter-table/

/**
 * Query data.
 *
 * @return array
 */
public function query(): array
{
    return [
        'posts' => Post::filters()->defaultSort('id')->paginate()
    ];
}
tabuna commented 3 years ago

How would you like it to look? I'm not sure if we need a default property, but we can add one.

Now this can be done using a filter:

/**
 * @param Builder $builder
 *
 * @return Builder
 */
public function run(Builder $builder): Builder
{
    return $builder->defaultSort('id')
}
tabuna commented 3 years ago

We could add default filters, like the trash filter.

For example:

$builder->defaultSort($builder->getModel()->getKeyName(), 'asc');
// or
$builder->defaultSort($builder->getModel()->getKeyName(), 'desc');

This will automatically match the primary keys and will not be visually displayed in any way.

And adding to the resource will look like this:

/**
 * Get the filters available for the resource.
 *
 * @return array
 */
public function filters(): array
{
    return [
        RoleFilter::class,
        DefaultSortDesc::class
    ];
}

What do you think about this?

pqr commented 3 years ago

I thought about following options:

  1. $defaultSortColmn and $defaultSortOrder properties on Resouce class
  2. public function defaultSortColumn(): string and defaultSortOrder() on Resource class
  3. or even some method on Resource class to manipulate list query Builder $builder - maximum flexibility

For my current situation option 1 (new props) would be enough.

Regarding your proposal about adding filter witch manipulates with $builder - it sounds like "option 3"! The only doubt that I fill "Filter" semantically is something that filters out records, but not sorting them, not changing the order.

tabuna commented 3 years ago

Unfortunately, these modifiers are already named as Filters. Using them will give you a lot more flexibility than simple properties.

I tried my own version, and it may not always fit, since I want to indicate the column, maybe?

    public function filters(): array
    {
        return [
            new DefaultSorted('id', 'asc'),
        ];
    }
pqr commented 3 years ago

I've just used in my project - works as expected! Thanks!