boxfrommars / rutorika-sortable Goto Github PK
View Code? Open in Web Editor NEWAdds sortable behavior to Laravel Eloquent models
License: MIT License
Adds sortable behavior to Laravel Eloquent models
License: MIT License
scopeSorted should order by sortableGroupField
as well as sortableField
. Otherwise, $this->hasMany()->sorted() returns mis-ordered result (especially noticeable when with composite sort group).
E.g.
class Post extends Model {
use SortableTrait;
// Sortable model config
protected static $sortableField = 'order';
protected static $sortableGroupField = ['some_unrelated_id', 'date'];
}
class Author extends Model {
public function posts(..) {
return $this->hasMany('\App\Post')->sorted();
}
}
scopeSorted should probably look like this:
public function scopeSorted($query)
{
$sortableField = static::getSortableField();
return static::applySortableGroup($query, $this)->orderBy($sortableField);
}
i have already two entities and when i am adding third entities in config/sortable.php file after than raised error in third entities
first two entities working properly but third is not working and that error raised.
I want multiple rows drag and drop, is it possible in rutorika-sortable??
plz give me solution
Currently this plugin doesn't work on Laravel 7.
Any fix available?
Hello!
First off, this is fantastic plugin! It works really well. Thanks for building it!
I was trying to do the inverse of what you had in your example. http://sortable5.boxfrommars.ru/posts
Rather than sorting tags within a post. Is it possible to sort posts within a tag? I couldn't figure out if that was possible.
Thanks again!
-Tim
Hello!
I got error
Array to string conversion
when use morphedBySortedMany
On 5.4 this code work fine.
Sdantard works module, all new items have order number last item + 1. Is it possible when a new item will be first (has position 1) and other items will be reordered automatically?
Will this work in Laravel 5 and if not will there be an update?
Using Laravel 5.3.31, I ran composer require rutorika/sortable:3.4.1
, continued through the steps in README, and when I got to
Add \Rutorika\Sortable\SortableTrait to your Eloquent model.
I add use \Rutorika\Sortable\SortableTrait;
to my model and get an error "Trait 'Rutorika\Sortable\SortableTrait' not found".
I'm lost after this.
I keep getting these errors when trying to sort:
Here is my config:
'entities' => [
'sections' => [
'entity' => '\App\Models\Section',
'relation' => 'assessments' // relation name (method name which returns $this->belongsToSortedMany)
]
],
I have definitely got the naming of the class right. Is it something I am missing in my view file?
<table class="table table-striped table-hover">
<tbody class="sortable" data-entityname="sections">
@foreach ($assessment->sections as $section)
<tr data-itemId="{{ $section->id }}">
<td class="sortable-handle"><span class="glyphicon glyphicon-sort"></span></td>
<td class="id-column">{{ $section->id }}</td>
<td>{{ $section->name }}</td>
</tr>
@endforeach
</tbody>
</table>
The jQuery:
$(document).ready(function(){
var $sortableTable = $('.sortable');
if ($sortableTable.length > 0) {
$sortableTable.sortable({
handle: '.sortable-handle',
axis: 'y',
update: function(a, b){
var entityName = $(this).data('entityname');
var $sorted = b.item;
var $previous = $sorted.prev();
var $next = $sorted.next();
console.log( $sorted.data('itemid'));
if ($previous.length > 0) {
changePosition({
parentId: $sorted.data('parentid'),
type: 'moveAfter',
entityName: entityName,
id: $sorted.data('itemid'),
positionEntityId: $previous.data('itemid'),
"_token": "{{ csrf_token() }}",
});
} else if ($next.length > 0) {
changePosition({
parentId: $sorted.data('parentid'),
type: 'moveBefore',
entityName: entityName,
id: $sorted.data('itemid'),
positionEntityId: $next.data('itemid'),
"_token": "{{ csrf_token() }}",
});
} else {
console.error('Something wrong!');
}
},
cursor: "move"
});
}
});
I've got everything set up exactly as in the info on this repo. But when I try to sort, I get this:
Object {entityName: Array(1), entityClass: Array(1)}entityClass: Array(1)0: "The entity class field is required."length: 1__proto__: Array(0)entityName: Array(1)0: "The selected entity name is invalid."length: 1__proto__: Array(0)__proto__: Object
success @ 1238:133
j @ jquery.js:3099
fireWith @ jquery.js:3211
x @ jquery.js:8264
(anonymous) @ jquery.js:8605
What am I doing wrong?
Hi,
I have some requirement where I can leave some empty rows in between.
Need to store the position of empty row also.
In order to display in particular position.
Please let me know How can I achieve this.
Is it possible in rutorika sortable package?
If the sortable model is using a specific database connection, its base table cannot be found since the connection name is not considered at the moment.
The validator fails with the following PDOException during calling the sort function of the SortableController:
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'xxx' doesn't exist
StackTrace points to
Rutorika\Sortable\SortableController.php(21): Illuminate\Validation\Validator->passes()
The reason why the table cannot be found is the missing name of the database connection prepended to the table name in the "exists" validation rules.
Also the creation of a new sortable model fails by the same PDOException if no position is set manually.
I have found the corresponding code lines and will provide a fix for this issue in the next days.
I keep getting this error whenever I try to save a new sortable record.
General error: 1364 Field 'position' doesn't have a default value
My config:sortable
:
'entities' => [
// 'articles' => '\Article' for simple sorting (entityName => entityModel) or
// 'posts' => ['entity' => '\Post', 'relation' => 'tags'] for many to many or many to many polymorphic relation sorting
'sections' => [
'entity' => '\App\Models\Section',
'relation' => 'assessments' // relation name (method name which returns $this->belongsToSortedMany)
]
],
];
Model:
class Section extends Model
{
use BelongsToSortedManyTrait, SortableTrait;
public $table = "sections";
public $primaryKey = "id";
public $timestamps = true;
/*public $sortable = [
'order_column_name' => 'order',
'sort_when_creating' => true,
];*/
public $fillable = [
'id',
'name',
'description',
'parent',
'position'
];
public static $rules = [
// create rules
'name' => 'required'
];
public function assessments() {
return $this->belongsToSortedMany('App\Models\Assessment');
}
public function questionGroups() {
return $this->hasMany(\App\Models\QuestionGroup::class);
}
}
I am using Laravel 5.5 and "rutorika/sortable": "^4.2",
. Any ideas?
Hey - would it be possible to extend this package for sorting relationships through pivot tables?
I have a many-to-many relation through pivot, and need sorting to be there...
Call to a member function beginTransaction() on null
Is there any way to make the extension working in mobile ? Pls help thank you.
I'm using Laravel 5 and have updated plugin to version 3.4.0. Everything seems to work as expected during the seeding - records are created using attach()
method and position
column on the pivot table is populated correctly. However, during the edit, when sending to controller reordered list of child records and using sync()
to update parent record, no changes to position
column take place.
Any suggestions?
I would like to implement a sortable behavior with plank/laravel-mediable, but can't figure out how and where to set the sortableGroupField ?
Any help would be welcome ?
After a composer update I did today, the previous() and next() queries look like they are being limited to 0 records.
I'm trying to track down exactly which update caused it, but i've so far narrowed it down to one of the following (see below). I'm thinking laravel core is the most likely contender. Any ideas?
Removing paragonie/random_compat (1.0.10)
Installing paragonie/random_compat (1.1.0)
Removing ckeditor/ckeditor (4.5.4)
Installing ckeditor/ckeditor (4.5.5)
Removing symfony/var-dumper (v2.7.6)
Installing symfony/var-dumper (v2.7.7)
Removing symfony/translation (v2.7.6)
Installing symfony/translation (v2.7.7)
Removing symfony/routing (v2.7.6)
Installing symfony/routing (v2.7.7)
Removing symfony/process (v2.7.6)
Installing symfony/process (v2.7.7)
Removing symfony/http-foundation (v2.7.6)
Installing symfony/http-foundation (v2.7.7)
Removing symfony/event-dispatcher (v2.7.6)
Installing symfony/event-dispatcher (v2.7.7)
Removing symfony/debug (v2.7.6)
Installing symfony/debug (v2.7.7)
Removing symfony/http-kernel (v2.7.6)
Installing symfony/http-kernel (v2.7.7)
Removing symfony/finder (v2.7.6)
Installing symfony/finder (v2.7.7)
Removing symfony/dom-crawler (v2.7.6)
Installing symfony/dom-crawler (v2.7.7)
Removing symfony/css-selector (v2.7.6)
Installing symfony/css-selector (v2.7.7)
Removing symfony/console (v2.7.6)
Installing symfony/console (v2.7.7)
Removing nesbot/carbon (1.20.0)
Installing nesbot/carbon (1.21.0)
Removing doctrine/inflector (v1.0.1)
Installing doctrine/inflector (v1.1.0)
Removing psy/psysh (v0.5.2)
Installing psy/psysh (v0.6.1)
Removing classpreloader/classpreloader (2.0.0)
Installing classpreloader/classpreloader (3.0.0)
Removing laravel/framework (v5.1.22)
Installing laravel/framework (v5.1.24)
Removing frozennode/administrator (v5.0.6)
Installing frozennode/administrator (v5.0.8)
Removing symfony/yaml (v2.7.6)
Installing symfony/yaml (v2.7.7)
Removing phpunit/phpunit (4.8.16)
Installing phpunit/phpunit (4.8.18)
Removing symfony/class-loader (v2.7.6)
Installing symfony/class-loader (v2.7.7)
first of all, thanks for this nice package
The issue:
when I try to sort the second item in the list to the first item, I got the error
" positionEntityId is required "
then I made a review for jQUery code and I found you check if previous or next is greater than zero
if( $previous.length > 0 )
// do
else if( $next.length > 0 )
// do
but when i make console.log for [ $previous.length ] and [ $next.length ]
i noticed that both of them is greater than 0, so each time the code in $previous.length will execute every time
so I made a simple solution to the code
instead of check the length greater than zero or not
I checked [ itemid ] for both previous and next whether defined or not
like:
if ($previous.data('itemid') !== undefined)
// do
else if ($next.data('itemid') !== undefined)
// do
this solution is worked for me in all cases
thanks
Hi,
I would like to use your sortable trait, but i have a issue. I'm have a single model which uses a where clause to list it's items.
For example, i have a eloquent model "FoodItems" which has a category slug (i.e. cheese and bread)
I would like to sort these items in that slug.
I could not find this in the documentation or the source code if this was possible, and if so, how. Could you let me know how to do this?
Thanks,
Michel
Hi! I haven't had the chance to really dig into this issue but I noticed that using syncWithoutDetaching
on a belongsToSortedMany
relation will simply act as a normal sync
.
I wasn't sure if the library simply doesn't support syncWithoutDetaching
or if this is a bug. I can try to investigate further when I have some time but just pointing it out in case anyone had any feedback.
I am passing data like this
type:moveAfter
entityName:leadgen_parameters
id:1
positionEntityId:2
response : {"success":true}
But there is problem in saving the position, failed the steps in readme file
New to laravel
is it compatible with laravel 5.7 now?
I set protected static $sortableGroupField = ['fieldName1','fieldName2'];
as in documentation and it throwed an array to string conversion exception in SortableTrait.php on line 255. I managed to solve this problem by adding an else after the if with is_array condition and it worked. Here is the code:
public function checkSortableGroupField($sortableGroupField, $entity)
{
if ($sortableGroupField === null) {
return;
}
if (is_array($sortableGroupField)) {
foreach ($sortableGroupField as $field) {
if ($this->$field !== $entity->$field) {
throw new SortableException($this->$field, $entity->$field);
}
}
} else
if ($this->$sortableGroupField !== $entity->$sortableGroupField) {
throw new SortableException($this->$sortableGroupField, $entity->$sortableGroupField);
}
}
Thank you for this package. Is there any working example?
Also will it work on laravel 5.6?
Is there any way to receive an sorted array of ids and use that to update the position on each row?
Class App\Model contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (App\Model ::getBelongsToManyCaller)
Is it posible in rutorika sortable package??
How to show record actual number not position?
In DB position may start from 59, 60, 61 and I need to show it actual number 1,2,3...
I'm using belongsToSortedMany
in the immediate model in Playlist
.
public function tracks()
{
return $this
->belongsToSortedMany(Track::class, 'position')
->withTimestamps();
}
What happen is when I perform moveBefore
or moveAfter
the position of the tracks
are all the same.
move
operationplaylist_track
playlist_id | track_id | position |
---|---|---|
1 | 1 | 2 |
1 | 1 | 2 |
tracks
id | name |
---|---|
1 | Foo |
2 | Bar |
playlists
id | name |
---|---|
1 | Sample Playlist |
Hi,
I'm using the "Sortable many to many" and everything works as expected.
My database structure is like the one you gave in the readme. But I am sorting the posts and not the categories (tags).
When I display all the posts for one tag, everything works. Sorting works. Added post gets the correct position. etc.
What I want to do next is when I display one post, I to want to display within that page a link to the previous and next post. But the next() or previous() function gives me the following exception:
Call to undefined method Illuminate\Database\Query\Builder::siblingssiblings()
when I try $post->next(); (Controller or view)
and
Illegal operator and value combination.
/vendor/rutorika/sortable/src/Rutorika/Sortable/SortableTrait.php
* @return QueryBuilder
*/
public function siblings($isNext, $limit = 0)
{
$sortableField = static::getSortableField();
$query = static::applySortableGroup($this->newQuery(), $this);
$query->where($sortableField, $isNext ? '>' : '<', $this->getAttribute($sortableField));
$query->orderBy($sortableField, $isNext ? 'asc' : 'desc');
if ($limit !== 0) {
when I try $post->previous();
Here are my models:
Post model
class Faq_post extends Model
{
use \Rutorika\Sortable\SortableTrait;
use \Rutorika\Sortable\SortableTrait;
public function categories()
{
return $this->belongsToSortedMany('App\Faq_category', 'position','faq_posts_faq_categories');
}
Categories mode:
class Faq_category extends Node
{
use BelongsToSortedManyTrait;
public function posts() {
return $this->belongsToSortedMany('\App\Faq_post', 'position', 'faq_posts_faq_categories');
}
Am I missing something? Thank you
Hi! I have the problem with belongsToSortedMany relationship.
In my project, I have a revision system for some models.
I use PivotEventTrait he has pivotAttached, pivotDetached methods and etc.
With standard relationship belongsToMany everything is good, but when I use belongsToSortedMany, it does not work
The library pivot - https://github.com/fico7489/laravel-pivot
Laravel version 7.21.0
When I use soft delete to remove record, position was recalculated. But when $model->restore() nothing happened and I got two records with the same position.
Any solution?
The comparison should read if ($entity1->$field != $entity2->$field)
(single equals sign).
In my model, in Laravel 5.7, date
field is part of the sort group. If date is being cast (protected $casts = ['date' => 'datetime:Y-m-d']
, checkFieldEquals
fails to correctly compare two such dates.
A patch for this is in a prior PR #61
It's not a issue, but a question about your package. I'm thinking to use that, but I like to know some details.
Imagine that I have position range(0, 1000000), all persisted on database. What should happen when I move to position 500000? I will have two objects on this position, or it'll move 500000 to 1000000 subsequents to next position?
Thanks and sorry for open an issue for that.
Is it something I am missing, or does the trait not re-sort the remaining entries in the database after I delete one or multiple entries by Eloquent ->delete() ?
Hey,
I was wondering, how hard it would be to implement sorting by multiple group fields? Suppose it shouldn't be hard:
if ($sortableGroupField)
{
$query = static::newInstance();
\Illuminate\Support\Collection::make($sortableGroupField)->each(
function($field) use ($query, $model)
{
$query = $query->where($field, $model->$field);
}
);
$maxPosition = $query->max('position');
}
Similar adjustment can be made for _applySortableGroup
.
Collection::make() can be moved to getSortableGroupField
function.
I'm using Laravel 4 package by the way.
Hello,
are there any plans to make it customizable?
how to change primary key from id to article_id
This is my error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select count(*) as aggregate from articles
where id
= 2)
Thank you
There don't have any error and i can get the entity and the position id as well. But I'm not sure why it can't save the position in the database. Pls help me , thank you.
In my application, I'm always creating byPosition
scope to fetch data by the position. Is there any similar functionality already written? Or may I make one?
any plan to support laravel 5.6?
best regards~
I get this error after drag and drop. The entity name is what I gave in config/sortable.php
return [
'entities' => [
'pages' => '\App\Pages'
]
Is there some other config needed. I don't see this error message in the source code so I can debug.
If in target model the key field is UUID (or other non numeric type) then validator fails.
Hello,
first of all, thank you for your package, it's really great and I've been using it for a really long time now.
Recently I upgraded my CMS to Laravel framework version 6.0 and your package is not working anymore, looks like it does not support this version of the Laravel framework.
The problem is that since Laravel version 6.0 the helper method array_get() doesn't exists, it was changed to Arr:get().
The execution breaks in the SortableController on line 108, can you fix this to support newer versions of Laravel framework?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.