Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Overriding the direction parameter #188

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,13 +127,16 @@ There is a blade extension for you to use **@sortablelink()**

You can omit 2nd, 3rd and 4th parameter.

By using `['direction'=>'desc']` in 3rd parameter you can override the default toggle behavior.

Possible examples and usages of blade extension:

```blade
@sortablelink('name')
@sortablelink('name', 'Username')
@sortablelink('address', trans('fields.address'), ['filter' => 'active, visible'])
@sortablelink('address', trans('fields.address'), ['filter' => 'active, visible'], ['class' => 'btn btn-block', 'rel' => 'nofollow', 'href' => route('my.custom.route')])
@sortablelink(null, 'Reset') {{!-- back to default --}}
```

If you do not fill **Title** (2nd parameter) column name is used instead.
Expand Down Expand Up @@ -383,3 +386,9 @@ try {
```

>**Note**: I strongly recommend to catch **ColumnSortableException** because there is a user input in question (GET parameter) and any user can modify it in such way that package throws ColumnSortableException with code `0`.

# Session - persisting parameters

Package supports saving the sortable parameters _sort_ and _direction_ into the session. To support this on the application level set the `to_session` configuration parameter to `true`.


46 changes: 45 additions & 1 deletion src/ColumnSortable/Sortable.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
*/
trait Sortable
{

/**
* @param \Illuminate\Database\Query\Builder $query
* @param array|null $defaultParameters
Expand All @@ -25,6 +24,8 @@ trait Sortable
*/
public function scopeSortable($query, $defaultParameters = null)
{
$this->Init();

if (request()->allFilled(['sort', 'direction'])) { // allFilled() is macro
return $this->queryOrderBuilder($query, request()->only(['sort', 'direction']));
}
Expand All @@ -45,6 +46,49 @@ public function scopeSortable($query, $defaultParameters = null)
return $query;
}

private function Init(){
if(request()->allFilled(['sort', 'direction'])){
$this->saveToSession(request()->only(['sort', 'direction']));
}
elseif(request()->has('sort') && request()->input('sort')==config('columnsortable.reset_value')){
$this->removeFromSession();
}
elseif($this->getSessionSort()!==false && !request()->allFilled(['sort', 'direction']) ){
request()->merge($this->getSessionSort());
}
}

private function getSessionSort(){
if(config('columnsortable.to_session')){
$sess_sort = request()->session()->get('sort', []);
if(isset($sess_sort[request()->path()])) {
$sortParams = $sess_sort[request()->path()];
return ['sort' => key($sortParams),
'direction' => reset($sortParams)];
}
}

return false;
}

private function saveToSession($sortParameters){
if(config('columnsortable.to_session')){
list($column, $direction) = $this->parseParameters($sortParameters);
$sort_rec[$column] = $direction;
$sess_sort = request()->session()->get('sort', []);
$sess_sort[request()->path()] = $sort_rec;
session(['sort' => $sess_sort]);
}
}

private function removeFromSession(){
if(config('columnsortable.to_session')){
$sess_sort = request()->session()->get('sort', []);
unset($sess_sort[request()->path()]);
session(['sort' => $sess_sort]);
}
}


/**
* Returns the first element of defined sortable columns from the Model
Expand Down
30 changes: 22 additions & 8 deletions src/ColumnSortable/SortableLink.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public static function render(array $parameters)
request()->merge([$mergeTitleAs => $title]);
}

list($icon, $direction) = self::determineDirection($sortColumn, $sortParameter);
list($icon, $direction) = self::determineDirection($sortColumn, $sortParameter, $queryParameters);

$trailingTag = self::formTrailingTag($icon);

Expand Down Expand Up @@ -125,14 +125,21 @@ private static function applyFormatting($title, $sortColumn)
*
* @return array
*/
private static function determineDirection($sortColumn, $sortParameter)
private static function determineDirection($sortColumn, $sortParameter, $queryParameters)
{
$icon = self::selectIcon($sortColumn);

if (request()->get('sort') == $sortParameter && in_array(request()->get('direction'), ['asc', 'desc'])) {
$icon .= (request()->get('direction') === 'asc' ? config('columnsortable.asc_suffix', '-asc') :
config('columnsortable.desc_suffix', '-desc'));
$direction = request()->get('direction') === 'desc' ? 'asc' : 'desc';
$override_direction = array_key_exists('direction', $queryParameters) && in_array($queryParameters['direction'], ['asc', 'desc']);

if (request()->get('sort') == $sortParameter && in_array(request()->get('direction'), ['asc', 'desc']) || $override_direction) {
$icon .= (request()->get('direction') === 'asc' ? config('columnsortable.asc_suffix', '-asc') : config('columnsortable.desc_suffix', '-desc'));

if($override_direction){
//Override the direction with the query parameter
$direction = $queryParameters['direction'];
}else{
$direction = request()->get('direction') === 'desc' ? 'asc' : 'desc';
}

return [$icon, $direction];
} else {
Expand Down Expand Up @@ -251,8 +258,15 @@ private static function buildQueryString($queryParameters, $sortParameter, $dire
return is_array($element) ? $element : strlen($element);
};

$persistParameters = array_filter(request()->except('sort', 'direction', 'page'), $checkStrlenOrArray);
$queryString = http_build_query(array_merge($queryParameters, $persistParameters, [
$persistParameters = array_filter(request()->except('sort', 'direction', 'page'), $checkStrlenOrArray);

//TODO: Test for one-to-one relations
if(is_null($sortParameter)){
if(config('columnsortable.to_session')) $sortParameter = config('columnsortable.reset_value');
$direction = null;
}

$queryString = http_build_query(array_merge($queryParameters, $persistParameters, [
'sort' => $sortParameter,
'direction' => $direction,
]));
Expand Down
10 changes: 10 additions & 0 deletions src/config/columnsortable.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,16 @@
allow request modification, when default sorting is set but is not in URI (first load)
*/
'allow_request_modification' => true,

/*
Enable storing sorting to session
*/
'to_session' => false,

/*
Value indicating to reset sorting
*/
'reset_value' => '__reset',

/*
default direction for: $user->sortable('id') usage
Expand Down