Dropzone add id on init function and sort

Viewed 1512

I need to get id of my existing images into dropzone preview and ability of sending sort order to backend

What I have

  1. get existing images
  2. sort images

What I need

  1. Add images IDs to preview
  2. send sort order to back-end

Code

Each part of the code is commented for better understanding

Dropzone.autoDiscover = false;
  var myDropzone = new Dropzone("#my-awesome-dropzone", {
    headers: {
      "X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
    },
    acceptedFiles: ".jpeg,.jpg,.png,.gif",
    dictDefaultMessage: "Drag an image here to upload, or click to select one",
    maxFiles: 15, // Maximum Number of Files
    maxFilesize: 8, // MB
    addRemoveLinks: true,
    url: '{{ url('admin/dropzoneStore') }}/'+encodeURI('{{$product->id}}'),
    dictRemoveFile: 'Remove',
    dictFileTooBig: 'Image is bigger than 8MB',

    // get uploaded images in dropzone box
    init: function() {
      myDropzone = this;
      // get current images
      const images = @json($images);
      $.each(images, function(index, value) {
        var mockFile = {name: value.name, size: value.size, id: value.id };
        myDropzone.options.addedfile.call(myDropzone, mockFile);
        myDropzone.options.thumbnail.call(myDropzone, mockFile, "/images/"+value.name);
        myDropzone.options.complete.call(myDropzone, mockFile);
        myDropzone.options.success.call(myDropzone, mockFile);
      });
    }
  });
  // remove files from both view and database
  myDropzone.on("removedfile", function(file,response) {
      $.ajax({
          url: '{{ url('admin/destroyOnEdit') }}/'+encodeURI(file.name),
          type: 'DELETE',
          dataType: "JSON",
          data: {
              "name": file.name,
              "_method": 'DELETE',
              "_token": "{{ csrf_token() }}",
          },
          success:function(data) {
            myDropzone.removeFile(file);
          }
      });
  });
  // sort images in preview (need to send this sort to back-end and update images "sort" column value)
  $(function() {
    $(".dropzone").sortable({
      items: '.dz-preview',
      cursor: 'move',
      opacity: 0.5,
      containment: '.dropzone',
      distance: 20,
      tolerance: 'pointer',
      stop: function(event, ui) {
        var cloned = $('div#botofform').clone()
        $('#botofform').html("")
        $('.dropzone .dz-complete').each(function() {
          var data_id = $(this).data('id')
          console.log('event', event)
          console.log('ui', ui)
          console.log('data_id', data_id)
          $(cloned).find("input[data-id=" + data_id + "]").clone().appendTo($('#botofform'))
        });
      }
    });
  });

Any idea?

1 Answers

As your id is unique you can use this id to identify each images in your dropzone .So, inside init function whenever you append new images you can add data-id to each preview div using attr('data-id', value.id) and append input-box inside your bottom div .

Demo Code :

Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("#my-awesome-dropzone", {
  headers: {
    "X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
  },
  acceptedFiles: ".jpeg,.jpg,.png,.gif",
  dictDefaultMessage: "Drag an image here to upload, or click to select one",
  maxFiles: 15, // Maximum Number of Files
  maxFilesize: 8, // MB
  addRemoveLinks: true,
  //url: '{{ url('admin/dropzoneStore') }}/'+encodeURI('{{$product->id}}'),
  dictRemoveFile: 'Remove',
  dictFileTooBig: 'Image is bigger than 8MB',

  // get uploaded images in dropzone box
  init: function() {
    myDropzone = this;
    // get current images
    // const images = @json($images);

    var images = [{
      id: 103,
      img_alt: "svsss",
      name: "IMG_20201007_110637.jpg",
      sort: 0
    }, {
      id: 104,
      img_alt: "svsss1",
      name: "IMG_20201019_131338.jpg",
      sort: 1
    }, {
      id: 105,
      img_alt: "svsss3",
      name: "IMG_2020101_131339.jpg",
      sort: 2
    }, {
      id: 106,
      img_alt: "svsss4",
      name: "IMG_2020101_131340.jpg",
      sort: 3
    }]
    $.each(images, function(index, value) {
      var mockFile = {
        name: value.name,
        size: value.size,
        id: value.id
      };

      myDropzone.options.addedfile.call(myDropzone, mockFile);
      myDropzone.options.thumbnail.call(myDropzone, mockFile, "/images/" + value.name);
      myDropzone.options.complete.call(myDropzone, mockFile);
      myDropzone.options.success.call(myDropzone, mockFile);
      $(mockFile.previewElement).attr('data-id', value.id); //add data-id to preview div
      $('#botofform').append('<input type="text" class="cimages" name="cimages[]" data-id = "' + value.id + '" value="' + value.name + '" sort="' + value.sort + '">'); //append image value(name) and data-id(id) and sort(value as well)

    });
  }
});

$(function() {
  $(".dropzone").sortable({
    items: '.dz-preview',
    cursor: 'move',
    opacity: 0.5,
    containment: '.dropzone',
    distance: 20,
    tolerance: 'pointer',
    stop: function(event, ui) {
      var cloned = $('div#botofform').clone()
      $('#botofform').html("")
      console.clear()
      $('.dropzone .dz-complete').each(function(i) {
        var data_id = $(this).data('id')
        console.log('data_id-- ' + data_id + " || sort --" + i)
        //find input change attr and then clone same...
        $(cloned).find("input[data-id=" + data_id + "]").attr("sort", i).clone().appendTo($('#botofform'))
      });
    }
  });
});
<link rel="stylesheet" href=" http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/4.3.0/dropzone.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="dropzone" id="my-awesome-dropzone" action="#">
  <div class="fallback">
    <input name="cimages[]" type="file" multiple />
  </div>
  <div class="clearfix"></div>
</div>
<div id="botofform"></div>

Related