@kat-vetal

ActiveField и Dropzone.js?

Добрый день. Помогите разобраться. Есть свой класс ActiveField унаследованный от ActiveField yii2 в нем реализован метод fileUpload который собственно реализует dropzone. Все отлично работает пока на странице данный метод вызывается в единственном экземпляре, но как только их много то перестает работать.
Привязка активации самого dropzone идет к переменной $inputId = static::getInputId();
на тестируемой странице таких dropzone 9 шт. Мультизагрузка в данном случае не используется ввиду того что для каждого изображения есть отдельные поля типа название, описание и т.д.
Так вот если в самом коде активации распечатать console.log('$inputId');
то в консоле вместо

logotypes-0url
logotypes-1-url
logotypes-2-url
logotypes-3-url
logotypes-4-url
logotypes-5-url
logotypes-6-url
logotypes-7-url
logotypes-8-url
logotypes-9-url

получаю

logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
logotypes-9-url
Ну и соответственно отрабатывает только dropzone с id logotypes-9-url

public function fileUpload($action, $options=[])
    {
        DropZoneAsset::register(Yii::$app->view);
        $width = isset($options['dropzoneWidth']) ? $options['dropzoneWidth'] : $width = '100';
        $height = isset($options['dropzoneHeight']) ? $options['dropzoneHeight'] : $height = '100';
        $size = isset($options['size']) ? $options['size'] : $size = 'original';
        $title = isset($options['title']) ? $options['title'] : $title = $this->t('', 'Перетащите сюда файлы или нажмите для загрузки');
        $info = isset($options['info']) ? $options['info'] : $info = $this->t('', 'Выбранные файлы не загружены');
        $delete = $this->t('', 'Удалить');
        if(empty($action)){
            throw new InvalidCallException('You must enter an action in the form ' . get_called_class());
        }
        if($size == null && $size == 'original'){
            $size = 'original';
        }elseif($size == 'mini'){
            $size = '29x29';
        }
        if($width !== null && $height !== null){
            $size = 'original';
        }
        $this->textInput()->template = "{input}";

        $InputHtml = $this->textInput(['class' => 'form-control']);
        $label = isset($options['label']) ? $options['label'] : $label = "";
        if (!array_key_exists('id', $options)) {
            $inputId = static::getInputId();
        }

        if(strstr($this->attribute, '[')){
            $attr = explode(']', $this->attribute);
            $id = str_replace('[', '', $attr[0]);
        }
        else
        {
            $id = 0;
        }

        $inputCol = explode('-', $this->column);
        $labelCol = 12 - $inputCol[2];
        $labelColumn = 'control-label col-md-' . $labelCol;
        $labelTemplate = "<label class='$labelColumn'>" . $this->model->getAttributeLabel($label) . "</label>";


        $domain = Yii::$app->params['filebox']['domain'];
        $attribute = $this->getCleanedAttributeName($this->attribute);
        $urlResize = Filebox::getUrlResize($this->model->$attribute, $size);

        $customTemplate = "<div class='form-group dropzone-wrap'>" . $labelTemplate . "<div class='$this->column'><div id='my-dropzone-$id' class='dropzone dropzone-file-area' action='$action'><h3 class='sbold'>$title</h3><p>$info</p></div></div><div class='clearfix'></div>". str_replace('control-label', $labelColumn, $InputHtml) . "</div>";

    Yii::$app->view->registerJs(<<<EOD

       var FormDropzone$id = function () {
        return {
            //main function to initiate the module
            init: function () {
              console.log('$inputId');

                Dropzone.options.myDropzone$id = {
                    //thumbnailWidth: $width,
                    //thumbnailHeight: $height,
                    acceptedFiles: 'image/*, application/*',
                    headers: {
                        "Accept": "",
                        "Cache-Control": "",
                        "X-Requested-With": "XMLHttpRequest"
                    },
                    dictDefaultMessage: "",
                    init: function() {

                    if ($("#$inputId").val() != '') {
                        var id = $("#$inputId").val();
                        id = id.replace('$domain', '');
                        var dropzone = this;
                        $.ajax({
                            url: '$domain/file/info/',
                            dataType: 'json',
                            data: {
                                id : id
                            },
                        }).success(function(mockFile){
                            dropzone.emit("addedfile", mockFile);
                            dropzone.emit("thumbnail", mockFile, '$urlResize');
                            $("#$inputId").val();
                            $('.dz-progress').hide();
                        });
                    }
                        this.on("addedfile", function(file) {
                            // Create the remove button
                            var removeButton = Dropzone.createElement("<a href='javascript:;'' class='btn red btn-sm btn-block'>$delete</a>");

                            // Capture the Dropzone instance as closure.
                            var _this = this;

                            // Listen to the click event
                            removeButton.addEventListener("click", function(e) {
                                // Make sure the button click doesn't submit the form:
                                e.preventDefault();
                                e.stopPropagation();

                                // Remove the file preview.
                                _this.removeFile(file);
                                // If you want to the delete the file on the server as well,
                                // you can do the AJAX request here.
                            });

                            // Add the button to the file preview element.
                            file.previewElement.appendChild(removeButton);
                        });
                        this.on("success", function(file, responseText) {
                            var result = jQuery.parseJSON(responseText);
                        console.log(result.domain + result.File);
                        console.log(result);
                        if (result.File != null) {
                            $('#$inputId').val(result.domain + result.File);
                           
                        }
                            // Handle the responseText here. For example, add the text to the preview element:

                        });
                        //console.log($('#$inputId').val())
                    }
                }
            }
        };
    }();
    jQuery(document).ready(function() {
        FormDropzone$id.init();
        

       });
EOD
                , yii\web\View::POS_END
            );
        return $customTemplate;
    }
  • Вопрос задан
  • 332 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы