Recommended Posts

If you've ever needed to insert links to a large number of files within CKEditor you may have found that the standard PW link modal is a somewhat slow way to do it.

This module provides a quicker way to insert links to files on the page being edited. You can insert a link to an individual file, or insert an unordered list of links to all files on the page with a single click.

CKEditor Link Files

Adds a menu to CKEditor to allow the quick insertion of links to files on the page being edited.

link-files

Features

  • Hover a menu item to see the "Description" of the corresponding file (if present).
  • Click a menu item to insert a link to the corresponding file at the current cursor position. The filename is used as the link text.
  • If you Alt-click a menu item the file description is used as the link text (with fallback to filename if no description entered).
  • If text is currently selected in the editor then the selected text is used as the link text.
  • Click "* Insert links to all files *" to insert an unordered list of links to all files on the page. Also works with the Alt-click option.
  • Menu is built via AJAX so newly uploaded files are included in the menu without the page needing to be saved. However, descriptions are not available for newly uploaded files until the page is saved.

Installation

Install the CKEditor Link Files module.

For any CKEditor field where you want the "Insert link to file" dropdown menu to appear in the CKEditor toolbar, visit the field settings and add "LinkFilesMenu" to the "CKEditor Toolbar" settings field.

 

http://modules.processwire.com/modules/cke-link-files/

https://github.com/Toutouwai/CkeLinkFiles

  • Like 19

Share this post


Link to post
Share on other sites

Hi Robin,
I added "LinkFilesMenu" to the "CKEditor Toolbar" settings field and the icon appear in the toolbar.  But it doesn't show the pdf files when I click the icon. No dropdown.
Do I have to name the file-field in a special way?
It's a multi-language site.

Share this post


Link to post
Share on other sites

@Nick Belane, you don't need to name file fields in any special way. There should still be a dropdown even when there are no files that can be linked to. See screenshot:

2018-02-05_115209.png.6885e77e9ff6aad35501ef99e550bc17.png

So if you are not getting a dropdown then my guess is that there could be a Javascript error. Do you see any JS errors in the console panel of your browser dev tools?

I don't know anything about multi-language sites sorry (no demand for them in my country). Maybe someone else can confirm if the module works or not with multi-language?

Share this post


Link to post
Share on other sites

I went to test on a ML site, but I don't actually even see the button and I do get these JS errors.

image.png.70411dcffa0d53a439f0493e7b2c319f.png

 

This is my settings:

image.png.d7454b8712d9b14a3e86b9edbb1e9e34.png

 

Let me know if there is anything I can do to debug.

  • Like 1

Share this post


Link to post
Share on other sites

@Nick Belane, the issue with multi-language fields is hopefully fixed in v0.1.2. Please update and let me know if you are still seeing an issue.

Thanks @adrian for debugging help.

  • Like 1

Share this post


Link to post
Share on other sites
52 minutes ago, Nick Belane said:

now it works in Chrome but not in FF (58.0.1).

It's working here in Firefox, and it's unlikely that there will be a difference between browsers in how that JS works.

I think it must be a caching issue. Please visit Modules > Site and click "Refresh", and then scroll down and click "Clear compiled files".

  • Like 3

Share this post


Link to post
Share on other sites

Hi @Robin S, would you mind if I add this to AOS? I've made some changes, eg. display description + filename in the menu (if there's no description, use the basename without extension), and hide the menu when clicking outside of it. The latter is handy on a multilanguage site as the menu doesn't stay open when clicking to another language tab. Of course this happens only if you don't click on a menu item. I also plan to make it more ML-friendly by adjusting the description per language (some day).

  • Like 2

Share this post


Link to post
Share on other sites
59 minutes ago, tpr said:

would you mind if I add this to AOS?

No, I don't mind. Go right ahead.

  • Like 3

Share this post


Link to post
Share on other sites

Thanks, will do. I've just finished making it multilanguage-ready but need to check first on non-ML site too, though the way it's set up I don't expect any issue. I ended up adding multiple divs to the DOM containing the list of files, one for each language (#link-files-menu, #link-files-menu__1088, and so on). Then on menu toolbar click I get the current lang ID of the editor (from data-configname and ckeditor ID) and show/hide the corresponding menu.

Update: see here

  • Like 4

Share this post


Link to post
Share on other sites

This is great Robin!

Is there any way to make the description (if available) the default text for the link rather than the filename? I can handle the alt+ trick, but won't be able to teach that to 60+ users. It would be great if it were an option, same with setting a default target for the generated links (we always have files open in a new tab).

Share this post


Link to post
Share on other sites
Posted (edited)
4 hours ago, Arcturus said:

Is there any way to make the description (if available) the default text for the link rather than the filename?

@Arcturus, this module's functionality has been merged into AdminOnSteroids. If you are a user of that module it might be better to post your request in the support thread for AOS.

If you're not an AOS user then I guess I could make a config option to reverse the click/Alt-click behaviour. Let me know.

4 hours ago, Arcturus said:

It would be great if it were an option, same with setting a default target for the generated links (we always have files open in a new tab).

I'm not keen to go down this road. There are a large number of attributes a link can potentially have and I don't want to try and support them all. This module is intended as a time-saving tool for power-users who are tasked with loading/editing large amounts of content - I have in mind the superuser who must do an initial loading of content supplied by a client. The module isn't intended to be a full replacement of the PW link dialog. For anything beyond what this module provides I suggest you use the link dialog, or perhaps a textformatter module to apply link attributes like target in a systematic way. TBH, if my clients were 60+ and not all that computer literate I would have them stick to the core link dialog so they don't have to learn something new.

Edit: you can also add a target attribute to internal file links via a simple piece of jQuery on the front-end:

// Add target attribute to internal file links
$('a[href^="/site/assets/files/"]').attr('target', '_blank');

 

Edited by Robin S
Added jQuery snippet

Share this post


Link to post
Share on other sites

Thanks for getting back to me. I'm not using AOS, but I can understand why you wouldn't want to maintain a separate project. No problem though, it only took me a few minutes to apply both of my desired changes to your existing plugin.  

For anyone else who's interested, here are the altered lines (91-96) from plugin.js

			} else if(use_description && $(this).attr('title').length) {
				text = $(this).text();
			} else {
				text = $(this).attr('title');
			}
			html = '<a href="' + $(this).data('url') + '" target="_blank">' + text + '</a>'

Those 60+ users are coming over to PW from ExpressionEngine, so this will be an entirely new process to them anyway. But much easier for me to teach them now. ;)

Share this post


Link to post
Share on other sites
2 minutes ago, Arcturus said:

Those 60+ users are coming over to PW from ExpressionEngine, so this will be an entirely new process to them anyway.

What I meant is that they have to learn how to use the core link dialog regardless because I'm sure they'll need to create non-file links, and then they have to also learn a different method if using this module for file links.

5 minutes ago, Arcturus said:

No problem though, it only took me a few minutes to apply both of my desired changes to your existing plugin.

Glad you have it working how you like. This module isn't likely to get many updates now that it is merged into AOS, but bear in mind if you do see an update available you will need to either avoid updating or reapply your changes to the updated module files.

Share this post


Link to post
Share on other sites

Thanks a lot for sharing this useful plugin and it proved it very useful and understability and all is really worth useful .

Share this post


Link to post
Share on other sites

I've created a module based almost entirely on this module, and my problem occurs both with my new module and the original. So even though CKE Insert Links has been incorporated into AOS, this seems the best place to post.

My new module allows users to insert links from a list of page names. It is little more than the original module with some renaming of functions and variables, and getting a list of pages rather than a list of attached files; then the menu is displayed in a CKE dialog rather than from the toolbar.

My new module and CKE Insert Links work fine in Firefox for all users, and work in Chrome for superusers. But they fail in Chrome (and Edge on early testing) if the user is not a superuser.

The failure manifests itself with CKE Insert Links as the menu showing "No files for this page", and in my module with the equivalent error message.

I have debugged as far as finding that the problem seems to be with the $.getJSON() function in plugin.js, which is failing to return anything. In the code below, if(data.length) is evaluating to false.

Note that the new code is very close to the original module, with functions and variables renamed.

function addReferencesDialogMenu(page_id) {

  	// Adds data for dialog menu to DOM
  
	$('#link-references-dialog').remove();
	var ajax_url = config.urls.admin + 'module/edit?name=CkeLinkRefsDialog&pid=' + page_id;

 	var $list = $('<ul></ul>');
	$.getJSON(ajax_url).done(function(data) {

		if(data.length) {
			$.each(data, function(index, value) {
				$list.append( $('<li title="' + value.description + '">' + value.insertionvalues + '</li>') );
			});
		} else {
			$list.append( $('<li title="' + config.CkeLinkRefsDialog.no_references_text + '">' + config.CkeLinkRefsDialog.no_references_text + '</li>') );
			//$list.append( $('<li class="no-references" title="' + config.CkeLinkRefsDialog.no_references_text + '">NO DATA</li>') );
		}
	});

	$('body').append( $('<div id="link-references-dialog"></div>').append($list) );
}

The AJAX response section of the .module file is as follows. Again, just like the original, except the middle section that gets page info instead of attached-file info.
 

public function ajaxResponse(HookEvent $event) {

    // Must be AJAX request, must be for this module, must include pid GET variable
    if(!$this->config->ajax || $this->input->get->name !== $this->className() || !$this->input->get->pid) return;
    $page = $this->pages->get( (int) $this->input->get->pid );
    if(!$page->editable) return;
    $event->replace = true;
    $event->cancelHooks    = true;
    $result = array();
    
    // Get all relevant pages
    $referencePages = wire('pages')->find('template=reference');
    
    // Build array of page info for menu
    foreach($referencePages as $refPage) {
        $pageUrl = $refPage->url;
        $pageTitle = $refPage->title;
        $pageTitleArr = explode("|", str_replace("). ",")|",$pageTitle));
        $result[] = array(
            'description'=> $this->truncate($pageTitle, 60),
            'insertionvalues' => $pageTitleArr[0]."|".$pageUrl
        );
    }

    $event->return = json_encode($result);
}


I am unable to understand how or why superuser permissions (or absence of such permissions) have any effect.

Any help gratefully received!

  • Like 1

Share this post


Link to post
Share on other sites
10 hours ago, BillH said:

The failure manifests itself with CKE Insert Links as the menu showing "No files for this page", and in my module with the equivalent error message.

Thanks for reporting this issue. It should be fixed in v0.1.5 of CKEditor Link Files. If you check the changes in this commit you can apply something similar in your module.

@tpr, this issue will affect the version included in AdminOnSteroids too. I thought a hook before module edit would trigger before the access control kicks in but it seems not. Sort of obvious in hindsight. I really didn't want to have to add a page just for the AJAX response so went looking for some other process to hook into. I settled on ProcessLogin::executeLogout as this is one process module/method that should be accessible for any user. You might want to update AOS with a similar fix.

  • Like 2

Share this post


Link to post
Share on other sites

Thanks for getting back to me. I'll have a go with the changes this afternoon.

Share this post


Link to post
Share on other sites

Excellent. All works fine now. Thanks @Robin S.

B.t.w., if anyone is reading this thread, ignore the remarks in my first post about different browsers. I was just getting in a muddle with how I was logged in with each :-(

Also worth noting is that CKEditor Link Files works in a really neat way and is great for adapting if you want to insert PW content into CKEditor text. I've actually built a couple of modules based on it, and have one or two more in mind!

  • Like 1

Share this post


Link to post
Share on other sites

The bug seems to have returned.

It's the same as before: the module doesn't work (the menu shows "No files for this page") if the user is not logged in as superuser.

I'm using the latest version of the the module, 0.1.5. (And I'm getting the same problem with my own variants of the module.)

I thought the issue might be caused changing to PW 3.0.98, but reverting to 3.0.96 and 3.0.62 doesn't help.

In the browser, the Console isn't returning any errors, and there's nothing I recognize as relevant under Network.

Something must have changed, but can't think what. In fact, not much (that I can remember) has changed on the back end of the site at all in the last week or so.

I'm a bit stumped on what to try next!

Share this post


Link to post
Share on other sites

@BillH, I can't reproduce the issue. For me the module is working as expected for non-superusers.

The list of files is generated in the ajaxResponse() method. To debug you could use Tracy Debugger (best option) or $log to check that the method is firing and is returning JSON for files on the page.

Edit: if you updated from an earlier version of the module you might need to do a hard refresh in case the browser is caching the old version of plugin.js - not sure if CKEditor itself does any kind of cachebusting and there is no way to do this within the module for CKEditor plugins.

Share this post


Link to post
Share on other sites

@Robin S Thanks for the advice on debugging.

I'd never noticed the $log stuff in PW before, and have been wondering whether the Tracey Debugger module might be a good idea.

I've tried every bit of cache clearing I could think of, but perhaps there's something about CKEditor I missed

I'll investigate further and report back.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By BitPoet
      MediaLibrary
      Update: MediaLibrary can now be found in the official module list.
      Out of necessity, I've started to implement a simple media library module.
      The basic mechanism is that it adds a MediaLibrary template with file and image fields. Pages of this type can be added anywhere in the page tree.
      The link and image pickers in CKEditor are extended to allow quick selection of library pages from dropdowns. In the link picker this happens in the MediaLibrary tab, where you can also see a preview of the selected image. In the image picker, simply select a library from the dropdown at the top, everything else is handled by standard functionality.
      I've put the code onto github. This module is compatible with ProcessWire 3.
      Steps to usage:
      Download the module's zip from github (switch to the pw3 branche beforehand if you want to test on PW 3.x) and unpack it into site/modules Click "Modules" -> "Refresh" in the admin Click "Install" for MediaLibrary For testing, create a page with the MediaLibrary template under home (give it an expressive title like 'Global Media') and add some images and files Edit a differnt page with a CKEditor field and add a link and an image to see the MediaLibrary features in action (see the screencap for details) Optionally, go into the module settings for MediaLibrary Note: this module is far from being as elaborate as Kongondo's Media Manager (and doesn't plan to be). If you need a feature-rich solution for integrated media management, give it a look.
      Feel free to change the settings for MediaFiles and MediaImages fields, just keep the type as multiple.
      There are some not-so-pretty hacks for creating and inserting the correct markup, which could probably be changed to use standard input fields, though I'm a bit at a loss right now how to get it to work. I've also still got to take a look at error handling before I can call it fit for production. All feedback and pointers are appreciated (that's also why I post this in the development section).

      Edit 09.03.2016 / version 0.0.4: there's now also a "Media" admin page with a shortcut to quickly add a new library.

      Edit 01.05.2016:
      Version 0.0.8:
      - The module now supports nested media libraries (all descendants of eligible media libraries are also selectable in link/image picker).
      - There's a MediaLibrary::getPageMediaLibraries method you can hook after to modify the array of available libraries.
      - You can switch between (default) select dropdowns or radio boxes in the module configuration of MediaLIbrary to choose libraries.
      Edit 10.10.2018:
      Version 0.1.3:
      - Dropped compatibility for ProcessWire legacy versions by adding namespaces
      - Allow deletion of libraries from the Media overview admin page
      - Added an option to hide media libraries from the page tree (optionally also for superusers)
    • By Smirftsch
      I've got some odd problem adding additional styles to mystyles.js. After reading some and following the article here: https://github.com/ryancramerdesign/ProcessWire/blob/dev/wire/modules/Inputfield/InputfieldCKEditor/README.md#custom-editor-js-styles-set
      I was able to add a custom style. So far so good 😉
      It is displayed in the Styles menu and can be selected there. Now the odd thing starts, if I add a custom style like this:
       
      ... { name: 'Box Top', element: 'span',attributes: { 'class': 'box_top' } }, { name: 'Box Bottom', element: 'span', attributes: { 'class': 'box_bottom' } }  
      it works and can be selected just fine.
      However, if I add this:
      { name: 'Box Top', element: 'div',attributes: { 'class': 'box_top' } }, { name: 'Box Bottom', element: 'div', attributes: { 'class': 'box_bottom' } } It is also displayed, can be selected - BUT - once the edit is saved, it is gone, won't be displayed in the page and won't be shown anymore in the editor as selected style, it goes back to "normal".
       
      Can anyone give me a hint what I missed?
    • By rgaikema
      Hi all,
      Hopefully there's somebody who can help me with an issue while unzipping files.
      My goal is to show banners in a portfolio.
      In ProcessWire I have created a field, type 'Files', where I can upload the .zip files, one at a time.
      I've selected the option Decompress ZIP files, but any subfolder in the .zip somehow disappears.
      For example the 'assets' folder is gone after I uploaded the .zip file (see the attachment for the file structure).
      I'm curious, is there a way to preserve the file structure inside a .zip file after unzipping it?
       
      Kind regards,
      Remco

    • By Guy Incognito
      I added some custom styles to the CKeditor menu bar using the example mystyles.js and the PW tutorial. This worked fine for fields when editing on the frontend. But none of our custom styles showed in the backend editor dropdown unless we edited the core copy of mystyles.js in wire/modules.
      Is this correct behaviour, a bug or a mistake on my part? Tried clearing cache, logging in/out etc but the backend ignores our custom styles in the site/modules path.
    • By Robin S
      This module corrects a few things that I find awkward about the "Add New Template" workflow in the PW admin. I opened a wishlist topic a while back because it would good to resolve some of these things in the core, but this module is a stopgap for now.
      Originally I was going to share these as a few standalone hooks, but decided to bundle them together in a configurable module instead.
      Add Template Enhancements
      A module for ProcessWire CMS/CMF. Adds some efficiency enhancements when adding or cloning templates via admin.

      Features
      Derive label from name when new template added: if you like to give each of your templates a label then this feature can save some time. The label can be added automatically when templates are added in admin, in admin/API, or not at all. There are options for underscore/hyphen replacement and capitalisation of the label. Edit template after add: when adding only a single template, the template is automatically opened for editing after it is added. Copy field contexts when cloning: this copies the field contexts (a.k.a. overrides such as column width, label and description) from the source template to the new template when using the "Duplicate/clone this template?" feature on the Advanced tab. Copy field contexts when duplicating fields: this copies the field contexts if you select the "Duplicate fields used by another template" option when adding a new template. Usage
      Install the Add Template Enhancements module.
      Configure the module settings according to what suits you.
       
      https://github.com/Toutouwai/AddTemplateEnhancements
      https://modules.processwire.com/modules/add-template-enhancements/