EasyAdminBundle icon indicating copy to clipboard operation
EasyAdminBundle copied to clipboard

Text editor "Attach Files" is doing nothing

Open lukepass opened this issue 6 years ago • 11 comments

Hello, I am really new to EasyAdminBundle since I always used SonataAdminBundle :smile:

Describe the bug I have a simple text field configured like this:

        Article:
            class: App\Entity\Article
            form:
                fields:
                    - title
                    - { property: 'text', type: 'text_editor' }

It's working correctly as an HTML text editor. I noticed that there is an "Attach Files" icon that inserts a preview of an image / file inside the text.

The problem is that this icon is doing absolutely nothing and all the file is stripped away and not saved in the database.

Before save:

image

After save:

image

To Reproduce EasyAdminBundle v2.3.4

(OPTIONAL) Additional context I know that I can configure CKEditor but Trix seems very easy to use and so I would like to configure it.

lukepass avatar Dec 11 '19 11:12 lukepass

Hi! Thanks for reporting this. Sadly, this is a known limitation of the current implementation. We're not planning to add this feature to 2.x branch, but after the release of EasyAdmin 3.0, we'll reconsider this feature. Thanks for understanding it and thanks for your patience!

javiereguiluz avatar Jan 16 '20 19:01 javiereguiluz

Hi! Does it work with ckeditor or do we have to implement it manually ? Regards.

sarramegnag avatar Jan 23 '20 17:01 sarramegnag

@sarramegnag With ckeditor you can install a bundle that will do it for you.

manu-sparheld avatar Jan 24 '20 08:01 manu-sparheld

@manu-sparheld Ok thanks, I will try. The doc looks rough, but I'll maybe write an article to ease the setup 😃

sarramegnag avatar Jan 24 '20 08:01 sarramegnag

@sarramegnag its already simple. You can install https://github.com/helios-ag/FMElfinderBundle And you are good to go

manu-sparheld avatar Jan 24 '20 09:01 manu-sparheld

Hello! It is possible to create own upload implementation. Here it is an example that just moves file to filesystem without creating file entity and saving to db and return file path to Trix editor.

First, create custom upload controller.

    /**
     * @Route("/admin/trix-upload", name="admin_trix_upload")
     */
    public function upload(Request $request, ValidatorInterface $validator): Response
    {
        /** @var UploadedFile $file */
        $uploadedFile = $request->files->get('file');

        // Set up validation rules you need.
        $violations = $validator->validate($uploadedFile, [
            new NotBlank(),
            new File([
            'mimeTypes' => [
                'image/*',
                'application/pdf',
            ]
        ])]);

        // Send error message if any.
        if ($violations->count() > 0) {
            /** @var ConstraintViolation $violation */
            $violation = $violations[0];
            return new Response($violation->getMessage(), Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        $newFilename = uniqid() . '.' . $uploadedFile->guessExtension();

        // Here you can create file entity and attach to post entity and so on.
        // As a simple example, just move file to public directory without saving to DB.
        $uploadedFile->move($this->getParameter('trixUploadsDir'), $newFilename);

        return new Response('/' . $this->getParameter('trixUploadsPublicDir') . '/' . $newFilename);
    }

And add js (small modifications based on https://trix-editor.org/js/attachments.js):

(function() {
  var HOST = "/admin/trix-upload"

  addEventListener("trix-attachment-add", function(event) {
    if (event.attachment.file) {
      uploadFileAttachment(event.attachment)
    }
  })

  function uploadFileAttachment(attachment) {
    uploadFile(attachment.file, setProgress, setAttributes)

    function setProgress(progress) {
      attachment.setUploadProgress(progress)
    }

    function setAttributes(attributes) {
      attachment.setAttributes(attributes)
    }
  }

  function uploadFile(file, progressCallback, successCallback) {
    var key = createStorageKey(file)
    var formData = createFormData(key, file)
    var xhr = new XMLHttpRequest()

    xhr.open("POST", HOST, true)

    xhr.upload.addEventListener("progress", function(event) {
      var progress = event.loaded / event.total * 100
      progressCallback(progress)
    })

    xhr.addEventListener("load", function(event) {
      if (xhr.status == 200) {
        var attributes = {
          url: xhr.response,
          href: xhr.response
        }
        successCallback(attributes)
      }
      else if (xhr.status = 422) {
        alert(xhr.response);
      }
    })

    xhr.send(formData)
  }

  function createStorageKey(file) {
    var date = new Date()
    var day = date.toISOString().slice(0,10)
    var name = date.getTime() + "-" + file.name
    return [ "tmp", day, name ].join("/")
  }

  function createFormData(key, file) {
    var data = new FormData()
    data.append("key", key)
    data.append("Content-Type", file.type)
    data.append("file", file)
    return data
  }
})();

Nikeev avatar Oct 03 '20 21:10 Nikeev

Hi! Is the integration of this feature still on track?

MrAnyx avatar Oct 28 '22 20:10 MrAnyx

It seems that with EA3, the issue still remains. Uploading seems partially not possible when using Drag n Drop.

bytes-max avatar Oct 30 '22 19:10 bytes-max

no update?

SaItiplouf avatar Dec 07 '23 15:12 SaItiplouf

Its a closed ticket. Open a new one if you need more attention.

bytes-max avatar Dec 07 '23 22:12 bytes-max

Working example with Symfony 6/7 & EA4:

  1. First, override styles that hide the "upload" button:
trix-toolbar .trix-button-group--file-tools {
  display: flex !important;
}

trix-toolbar .trix-button--icon-attach:before {
  bottom:0 !important;
  top:0 !important;
}
  1. Next, this is a rewrite of original example so it looks more clean and understandable. It doesn't use any keys, you just send a file and get url back.
// {projectRoot}/public/scripts/trix-upload.js
(function () {
    const UPLOAD_URL = "/admin/upload/trix";

    addEventListener('trix-before-initialize', () => {
        Trix.config.attachments.preview.caption = { name: false, size: false }
    });

    addEventListener("trix-file-accept", function (evt) {
        // Prevent attaching anything except images
        if (!evt.file.type.startsWith("image/")) {
            evt.preventDefault()
        }

        // Prevent attaching files > 10MB
        if (evt.file.size > 10_000_000) {
            evt.preventDefault()
        }
    })

    addEventListener("trix-attachment-add", function (evt) {
        if (evt.attachment.file) {
            uploadFileAttachment(evt.attachment)
        }
    })

    function uploadFileAttachment(attachment) {
        const xhr = new XMLHttpRequest()
        xhr.open("POST", UPLOAD_URL, true)
        xhr.responseType = "json";

        xhr.upload.addEventListener(
            "progress",
            evt => {
                attachment.setUploadProgress(evt.loaded / evt.total * 100)
            }
        );

        xhr.addEventListener(
            "load",
            evt => {
                if (xhr.response.ok) {
                    attachment.setAttributes({
                        url: xhr.response.url
                    })
                } else {
                    alert(xhr.response.error || "Error while uploading attachment")
                    console.error("Upload error: ", xhr.response);
                }
            }
        );

        const data = new FormData();
        data.append("file", attachment.file)
        xhr.send(data);
    }
})();
  1. In your crud controller you configure field as follows:
TextEditorField::new('article')
    ->addJsFiles(Asset::new('/scripts/trix-upload.js')->onlyOnForms())
  1. The upload route: In my case images are uploded into S3
#[Route("/admin/upload/trix", name: "admin_trix_upload")]
public function upload(Request $request, ValidatorInterface $validator): Response
{
    /** @var UploadedFile $uploadedFile */
    $uploadedFile = $request->files->get('file');

    // Set up validation rules you need.
    $violations = $validator->validate($uploadedFile, [
        new NotBlank(),
        new File(['mimeTypes' => ['image/*']])
    ]);

    // Send error message if any.
    if ($violations->count() > 0) {
        return $this->json([
            'ok' => false,
            'error' => (string)$violations,
        ]);
    }

    $newFilename = "temp/trix-upload/" . date('Y-m') . '/'
        . date('Y-m-d') . '_' . uniqid() . '.' . $uploadedFile->guessExtension();

    $result = $this->s3Client->putObject([
        'Bucket' => "my-s3-bucket",
        'Key' => $newFilename,
        'Body' => $uploadedFile->getContent(),
        'ContentType' => $uploadedFile->getMimeType(),
    ]);

    $storedUrl = $result['ObjectURL'];

    return $this->json([
        'ok' => true,
        'url' => $storedUrl,
    ]);
}

There's one more little problem with displaying though. When you output a saved HTML later, images inside will lose size constraints and alignment. Trix saves it's own "class" attributes in resulting HTML instead of independent "style" attributes, so you will need to include trix's css for them to work.

klkvsk avatar Feb 08 '24 13:02 klkvsk