Název Text Název Text Název Text

symfony 6 sortable row with sortable.js

34 Views Asked by At

In my view I have

<table class="table table-striped bg-white table-sm">
        <thead>
        <tr>
            <th scope="col">Název</th>
            <th scope="col">Text</th>
            <th scope="col">Pořadí</th>
            <th scope="col">Smazat</th>
        </tr>
        </thead>
        <tbody class="list-group" id="listWithHandle">
        {% for userSample in samples %}
            <tr class="list-group-item">
                <td>
                    <span class="glyphicon glyphicon-move" aria-hidden="true"></span></td>
                Drag me by the handle
                <td class="pe-5">{{ userSample.sample.name }}</td>
                <td class="pe-5">{{ userSample.sample.text }}</td>
                <td class="pe-5">{{ userSample.position}}</td>
                <td class="pe-5"><td><a href="{{ path('delete_user_template', {id: userSample.id}) }}"><i class="fa fa-trash"></i></a></td>
            </tr>
        {% endfor %}
        </tbody>
    </table>

I try the row in table may be oreordered by drag and drop. I find the javascipt library Sotrable.js that looks very fine https://github.com/SortableJS/Sortable. In symfony i use webpack encore, I install sortable through napm and in my app.js i Have the line

import Sortable from 'sortablejs';

but after compiling In console i see error that

Sortable is not defined in view I have block

<script>
        // Simple list
        Sortable.create(simpleList, { /* options */ });

        // List with handle
        Sortable.create(listWithHandle, {
            handle: '.glyphicon-move',
            animation: 150
        });

but sortable is not function

1

There are 1 best solutions below

1
Clément DELORD On

You need to put the Sortable variable in the global scope to access it later :

In your entrypoint (app.js) you can do :

import Sortable from 'sortablejs';
window.Sortable = Sortable

Then you'll be able to access it in your inline script