Code Monkey home page Code Monkey logo

rutorika-sortable's Introduction

Build Status Scrutinizer Code Quality Latest Stable Version Total Downloads Latest Unstable Version License

Laravel 5 - Demo

https://github.com/boxfrommars/rutorika-sortable-demo5

Install

Install package through Composer

composer require rutorika/sortable

Version Compatibility

Laravel Rutorika Sortable
4 1.2.x (branch laravel4)
<=5.3 3.2.x
5.4 3.4.x
5.5 4.2.x
5.7 4.7.x
6.0 6.0.x
7.x, 8.x 8.x.x
9.x, 10.x, 11.x 9.x.x

Sortable Trait

Adds sortable behavior to Eloquent (Laravel) models

Usage

Add position field to your model (see below how to change this name):

// schema builder example
public function up()
{
    Schema::create('articles', function (Blueprint $table) {
        // ... other fields ...
        $table->integer('position'); // Your model must have position field:
    });
}

Add \Rutorika\Sortable\SortableTrait to your Eloquent model.

class Article extends Model
{
    use \Rutorika\Sortable\SortableTrait;
}

if you want to use custom column name for position, set $sortableField:

class Article extends Model
{
    use \Rutorika\Sortable\SortableTrait;

    protected static $sortableField = 'somefield';
}

Now you can move your entities with methods moveBefore($entity) and moveAfter($entity) (you dont need to save model after that, it has saved already):

$entity = Article::find(1);

$positionEntity = Article::find(10)

$entity->moveAfter($positionEntity);

// if $positionEntity->position is 14, then $entity->position is 15 now

Also this trait automatically defines entity position on the create event, so you do not need to add position manually, just create entities as usual:

$article = new Article();
$article->title = $faker->sentence(2);
$article->description = $faker->paragraph();
$article->save();

This entity will be at position entitiesMaximumPosition + 1

To get ordered entities use the sorted scope:

$articles = Article::sorted()->get();

** Note **: Resorting does not take place after a record is deleted. Gaps in positional values do not affect the ordering of your lists. However, if you prefer to prevent gaps you can reposition your models using the deleting event. Something like:

// YourAppServiceProvider

YourModel::deleting(function ($model) {
    $model->next()->decrement('position');
});

You need rutorika-sortable >=2.3 to use ->next()

Sortable groups

if you want group entity ordering by field, add to your model

protected static $sortableGroupField = 'fieldName';

now moving and ordering will be encapsulated by this field.

If you want group entity ordering by many fields, use as an array:

protected static $sortableGroupField = ['fieldName1','fieldName2'];

Sortable many to many

Let's assume your database structure is

posts
    id
    title

tags
    id
    title

post_tag
    post_id
    tag_id

and you want to order tags for each post

Add position column to the pivot table (you can use any name you want, but position is used by default)

post_tag
    post_id
    tag_id
    position

Add \Rutorika\Sortable\BelongsToSortedManyTrait to your Post model and define belongsToSortedMany relation provided by this trait:

class Post extends Model {

    use BelongsToSortedManyTrait;

    public function tags()
    {
        return $this->belongsToSortedMany('\App\Tag');
    }
}

Note: $this->belongsToSortedMany has different signature then $this->belongsToMany -- the second argument for this method is $orderColumn ('position' by default), next arguments are the same

Attaching tags to post with save/sync/attach methods will set proper position

    $post->tags()->save($tag) // or
    $post->tags()->attach($tag->id) // or
    $post->tags()->sync([$tagId1, $tagId2, /* ...tagIds */])

Getting related model is sorted by position

$post->tags; // ordered by position by default

You can reorder tags for given post

    $post->tags()->moveBefore($entityToMove, $whereToMoveEntity); // or
    $post->tags()->moveAfter($entityToMove, $whereToMoveEntity);

Many to many demo: http://sortable5.boxfrommars.ru/posts (code)

You can also use polymorphic many to many relation with sortable behavour by using the MorphsToSortedManyTrait trait and returning $this->morphToSortedMany() from relation method.

By following the Laravel polymorphic many to many table relation your tables should look like

posts
    id
    title

tags
    id
    title

taggables
    tag_id
    position
    taggable_id
    taggable_type

And your model like

class Post extends Model {

    use MorphToSortedManyTrait;

    public function tags()
    {
        return $this->morphToSortedMany('\App\Tag', 'taggable');
    }
}

Sortable Controller

Also this package provides \Rutorika\Sortable\SortableController, which handle requests to sort entities

Usage

Add the service provider to config/app.php

'providers' => array(
    // providers...

    'Rutorika\Sortable\SortableServiceProvider',
)

publish the config:

php artisan vendor:publish

Add models you need to sort in the config config/sortable.php:

'entities' => array(
     'articles' => '\App\Article', // entityNameForUseInRequest => ModelName
     // or
     'articles' => ['entity' => '\App\Article'],
     // or for many to many
     'posts' => [
        'entity' => '\App\Post',
        'relation' => 'tags' // relation name (method name which returns $this->belongsToSortedMany)
     ]
),

Add route to the sort method of the controller:

Route::post('sort', '\Rutorika\Sortable\SortableController@sort');

Now if you post to this route valid data:

$validator = \Validator::make(\Input::all(), array(
    'type' => array('required', 'in:moveAfter,moveBefore'), // type of move, moveAfter or moveBefore
    'entityName' => array('required', 'in:' . implode(',', array_keys($sortableEntities))), // entity name, 'articles' in this example
    'positionEntityId' => 'required|numeric', // id of relative entity
    'id' => 'required|numeric', // entity id
));

// or for many to many

$validator = \Validator::make(\Input::all(), array(
    'type' => array('required', 'in:moveAfter,moveBefore'), // type of move, moveAfter or moveBefore
    'entityName' => array('required', 'in:' . implode(',', array_keys($sortableEntities))), // entity name, 'articles' in this example
    'positionEntityId' => 'required|numeric', // id of relative entity
    'id' => 'required|numeric', // entity id
    'parentId' => 'required|numeric', // parent entity id
));

Then entity with \Input::get('id') id will be moved relative by entity with \Input::get('positionEntityId') id.

For example, if request data is:

type:moveAfter
entityName:articles
id:3
positionEntityId:14

then the article with id 3 will be moved after the article with id 14.

jQuery UI sortable example

Note: Laravel 5 has csrf middleware enabled by default, so you should setup ajax requests: http://laravel.com/docs/5.0/routing#csrf-protection

Template

<table class="table table-striped table-hover">
    <tbody class="sortable" data-entityname="articles">
    @foreach ($articles as $article)
    <tr data-itemId="{{{ $article->id }}}">
        <td class="sortable-handle"><span class="glyphicon glyphicon-sort"></span></td>
        <td class="id-column">{{{ $article->id }}}</td>
        <td>{{{ $article->title }}}</td>
    </tr>
    @endforeach
    </tbody>
</table>

Template for many to many ordering

<table class="table table-striped table-hover">
    <tbody class="sortable" data-entityname="posts">
    @foreach ($post->tags as $tag)
    <tr data-itemId="{{ $tag->id }}" data-parentId="{{ $post->id }}">
        <td class="sortable-handle"><span class="glyphicon glyphicon-sort"></span></td>
        <td class="id-column">{{ $tag->id }}</td>
        <td>{{ $tag->title }}</td>
    </tr>
    @endforeach
    </tbody>
</table>
    /**
     *
     * @param type string 'insertAfter' or 'insertBefore'
     * @param entityName
     * @param id
     * @param positionId
     */
    var changePosition = function(requestData){
        $.ajax({
            'url': '/sort',
            'type': 'POST',
            'data': requestData,
            'success': function(data) {
                if (data.success) {
                    console.log('Saved!');
                } else {
                    console.error(data.errors);
                }
            },
            'error': function(){
                console.error('Something wrong!');
            }
        });
    };

    $(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();

                    if ($previous.length > 0) {
                        changePosition({
                            parentId: $sorted.data('parentid'),
                            type: 'moveAfter',
                            entityName: entityName,
                            id: $sorted.data('itemid'),
                            positionEntityId: $previous.data('itemid')
                        });
                    } else if ($next.length > 0) {
                        changePosition({
                            parentId: $sorted.data('parentid'),
                            type: 'moveBefore',
                            entityName: entityName,
                            id: $sorted.data('itemid'),
                            positionEntityId: $next.data('itemid')
                        });
                    } else {
                        console.error('Something wrong!');
                    }
                },
                cursor: "move"
            });
        }
    });

Development

sudo docker build -t rutorika-sortable .
sudo docker run --volume $PWD:/project --rm --interactive --tty --user $(id -u):$(id -g) rutorika-sortable vendor/bin/phpunit

rutorika-sortable's People

Contributors

boxfrommars avatar chrissi2812 avatar christoph-kluge avatar dath avatar fabianmu avatar giordanolima avatar mvrkljan avatar peterbabic avatar scrutinizer-auto-fixer avatar srwiez avatar stevebauman avatar timothyasp avatar tonystatic avatar vluzrmos avatar yozaz avatar zazmaster avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

rutorika-sortable's Issues

Is it possible to have empty rows

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.

Sorting with a where clause

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

After composer update, previous() and next() queries have "LIMIT 0"

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)

syncWithoutDetaching does not work properly on belongsToSortedMany relations

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.

Strict equality of the sortable group field values that are cast is uncertain

if ($entity1->$field !== $entity2->$field) {

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

Database table cannot be found if model is using a specific database connection

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.

Issue and Solution: Sort the second item to first item

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

SoftDelete & Restore

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?

Laravel 5.4 compatible?

Class App\Model contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (App\Model ::getBelongsToManyCaller)

working example?

Thank you for this package. Is there any working example?
Also will it work on laravel 5.6?

belongsToSortedMany has issue with same values inserted (laravel 5.4)

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.

After the move operation

playlist_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

sorted scope should sort with respect to sortableGroupField

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);
    }

Call to undefined method Illuminate\Database\Query\Builder::siblingssiblings()

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

Moving between two numbers

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.

How to change primaryKey ?

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

Sorting by two group fields

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.

`byPosition` scope

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?

Sorting Pivot tables

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...

Confused by Setup

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.

General error: 1364 Field 'position' doesn't have a default value

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?

"entityClass":["The entity class field is required."]

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.

Call to undefined function Rutorika\Sortable\array_get()

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?

Only returning object

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?

Array to string conversion error if $sortableGroupField is an array

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);
            }
    }

You can't move entities with different sortable group

You can't move entities with different sortable group: 5 4

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

Laravel 5 (v.3.4.0) manyToMany sync() doesn't update position

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?

Position is not getting saved

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

Position actual number

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...

No Re-Sorting after Delete?

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() ?

Laravel 5.5 support

Hello!

I got error

Array to string conversion

when use morphedBySortedMany

On 5.4 this code work fine.

The selected id is invalid. - Laravel 5.5

I keep getting these errors when trying to sort:

2018-02-12_17h27_20

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"
                });
            }
        });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.