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 18

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 thomasaull
      Some time ago I created a site profile for creation of a REST API with ProcessWire. Since I kept struggeling with updating stuff between different projects which use this, I decided to convert it into a module. It is now ready for testing: https://github.com/thomasaull/RestApi
      Additionally I added a few small features:
      automatic creation of JWT Secret at module install routes can be flagged as auth: false, which makes them publicly accessible even though JWT Auth is activated in module settings To check things out, download and install the module and check the folder /site/api for examples.
      If you find any bugs or can think of improvements, please let me know!
    • By kongondo
      Sites Manager
       
      16 September 2018:
      FOR NOW, PLEASE DO NOT USE THIS MODULE IN A PRODUCTION SITE. A  RECENT ProcessWire UPDATE HAS BROKEN THE MODULE. I AM WORKING ON A FIX.
       
      ################
       
      Sites Manager is a module for ProcessWire that allows Superusers to easily create/install ProcessWire sites on the same serverspace the module is running in. Only Superusers can use the module. You can create both stand-alone and multi-sites.
       
      Single/Stand-alone Sites
      Stand-alone or single-sites are sites that will run in their own document root/directory with their own wire and site folders, .htaccess, index.php, etc. In other words, a normal ProcessWire site.
      Multiple Sites
      Multi-sites are sites that will run off one wire folder (shared amongst two or more sites) each having their own site folder and database. In this regard, it is important to note that Sites Manager is not in itself a multiple sites solution! Rather, it is a utility that helps you create multi-sites to be run using the ProcessWire core multiple sites feature. For more on this core feature, see the official ProcessWire documentation, specifically the solution referred to as Option #1.
      Option #1 approach requires the site admin to initially install ProcessWire in a temporary directory for each new site. The directory then needs to be renamed as site-xxx, where ‘xxx’ is any name you want to use to differentiate the installation from other sites, before it is moved to the webroot. For instance, site-mysite, site-another, site-whatever. In addition, the /wire/index.config.php file must be copied/moved to the webroot. Each time a site is added, the index.config.php has to be edited to add ‘domain’ => ‘site-directory’ key=>value pairs for the site. This process can become a bit tedious. This module aims to automate the whole multi-site site creation process.
      The module is based off the official ProcessWire installer. Creating a site is as simple as completing and submitting a single form! You also have the option to type and paste values or reuse a pre-defined install configuration.
       
      The module will:
      Install a ProcessWire site in your named directory, applying chmod values as specified
      Move the directory to your webroot
      Update/Create a Superuser account as per the submitted form, including setting the desired admin theme and colour
      For multi sites, update sites.json (used by index.config.php to get array of installed sites)
       
      For multi sites, the only difference in relation to the core multi-sites index.config.php is that this file is slightly different from the one that ships with ProcessWire.
      Download from GitHub: Sites Manager (Beta Release)
      Features
      Install unlimited number of sites in one (multi-sites) or independent (single-site) ProcessWire installs. Install by completing a Form, Typing or pasting in configurations or using pre-created install configurations. Choose an Admin Theme to auto-install along with the site installation. For single-sites installation, download, save and reuse ProcessWire versions of your choice. Install and maintain site profiles for reuse to create other sites. Create install configurations to speed up installation tasks. Client and server-side validation of site creation values. Edit uploaded profiles (e.g., replace profile file). Lock installed sites, configurations and profiles to prevent editing. Bulk delete items such as site profiles, installed site directories and/or databases (confirmation required for latter two). View important site details (admin login, chmod, etc). Links to installed sites home and admin pages. Timezones auto-complete/-suggest. Pre-requisites, Installation & Usage
      Please see the documentation.
      Technicalities/Issues
      Only Superusers can use the module.
      ProcessWire 2.7 - 3.x compatible
      Currently using ProcessWire 2.7 installer (install.php)
      For multi-sites, potential race condition when sites.json is being updated on a new site install vs. index.config.php accessing the json file?
      Not tested with sub-directory installs (for instance localhost/pw/my-site-here/)
      Currently not doing the extra/experimental database stuff (database charset and engine)
      Future Possibilities
      Install specified modules along with the ProcessWire install
      Profile previews?
      Credits
      @ryan: for the ProcessWire installer
      @abdus: for the index.config.php reading from JSON idea
      @swampmusic: for the challenge
      Video Demo
      Demo  showing how quick module works on a remote server [YMMV!]. Video shows downloading and processing two versions of ProcessWire (~takes 7 seconds) and installing a single/stand-alone ProcessWire 3 site using the new Admin Theme UI Kit (~2 seconds) on a remote server.
       
      Screens
      1

      2

       
       
    • By Robin S
      Breadcrumb Dropdowns
      Adds dropdown menus of page edit links to the breadcrumbs in Page Edit.

      Installation
      Install the Breadcrumb Dropdowns module. The module requires ProcessWire >= v3.0.83 and AdminThemeUikit.
      There is a checkbox option in the module config that determines if the breadcrumb dropdowns will include pages that the user does not have permission to edit.
      Features/details
      The module adds an additional breadcrumb item at the end for the currently edited page. That's because I think it's more intuitive for the dropdown under each breadcrumb item to show the item's sibling pages rather than the item's child pages. In the dropdown menus the current page and the current page's parents are highlighted in a crimson colour to make it easier to quickly locate them in case you want to edit the next or previous sibling page. Unpublished and hidden pages are indicated in the dropdowns with similar styling to that used in Page List. If the option to include uneditable pages is selected then those pages are indicated by italics with a reduced text opacity and the "not-allowed" cursor is shown on hover. There is a limit of 25 pages per dropdown for performance reasons and to avoid the dropdown becoming unwieldy. If the current user is allowed to add new pages under the parent page an "Add New" link is shown at the bottom of the breadcrumb dropdown. If the currently edited page has children or the user may add children, a caret at the end of the breadcrumbs reveals a dropdown of up to the first 25 children and/or an "Add New" link. Overriding the listed siblings for a page
      If you want to override the siblings that are listed in the dropdowns you can hook the BreadcrumbDropdowns::getSiblingsmethod and change the returned PageArray. For most use cases this won't be necessary.
      Incompatibilities
      This module replaces the AdminThemeUikit::renderBreadcrumbs method so will potentially be incompatible with other modules that hook the same method.
       
      https://modules.processwire.com/modules/breadcrumb-dropdowns/
      https://github.com/Toutouwai/BreadcrumbDropdowns
    • By bernhard
      Some of you might have followed the development of this module here: https://processwire.com/talk/topic/15524-previewdiscussion-rockdatatables/ . It is the successor of "RockDataTables" and requires RockFinder to get the data for the grid easily and efficiently. It uses the open source part of agGrid for grid rendering.
       
      WHY?
      ProcessWire is awesome for creating all kinds of custom backend applications, but where it is not so awesome in my opinion is when it comes to listing this data. Of course we have the built in page lister and we have ListerPro, but none of that solutions is capable of properly displaying large amounts of data, for example lists of revenues, aggregations, quick and easy sorts by the user, instant filter and those kind of features. RockGrid to the rescue 😉 
       
      Features/Highlights:
      100k+ rows Instant (client side) filter, search, sort (different sort based on data type, eg "lower/greater than" for numbers, "contains" for strings) extendable via plugins (available plugins at the moment: fullscreen, csv export, reload, batch-processing of data, column sum/statistics, row selection) all the agGrid features (cell renderers, cell styling, pagination, column grouping etc) vanilla javascript, backend and frontend support (though not all plugins are working on the frontend yet and I don't plan to support it as long as I don't need it myself)  
      Limitations:
      While there is an option to retrieve data via AJAX the actual processing of the grid (displaying, filtering, sorting) is done on the client side, meaning that you can get into troubles when handling really large datasets of several thousands of rows. agGrid should be one of the most performant grid options in the world (see the official example page with a 100k row example) and does a lot to prevent problems (such as virtual row rendering), but you should always have this limitation in mind as this is a major difference to the available lister options that do not have this limitation.
      Currently it only supports AdminThemeUikit and I don't plan to support any other admin theme.
       
      Download: https://gitlab.com/baumrock/FieldtypeRockGrid
      Installation: https://gitlab.com/baumrock/RockGrid/wikis/Installation
      Quikckstart: https://gitlab.com/baumrock/RockGrid/wikis/quickstart
      Further instructions: https://gitlab.com/baumrock/RockGrid/wikis/quickstart#further-instructions
      Changelog: https://gitlab.com/baumrock/FieldtypeRockGrid/raw/master/changelog.md
       
      Module status: alpha, License: MIT
      Note that every installation and uninstallation sends an anonymous google analytics event to my google analytics account. If you don't want that feel free to remove the appropriate lines of code before installation/uninstallation.
       
      Contribute:
      You can contribute to the development of this and other modules or just say thank you by
      testing, reporting issues and making PRs at gitlab liking this post buying me a drink: paypal.me/baumrock/5 liking my facebook page: facebook.com/baumrock hiring me for pw work: baumrock.com  
      Support: Please note that this module might not be as easy and plug&play as many other modules. It needs a good understanding of agGrid (and JavaScript in general) and it likely needs some looks into the code to get all the options. Please understand that I can not provide free support for every request here in the forum. I try to answer all questions that might also help others or that might improve the module but for individual requests I offer paid support for 60€ per hour (excl vat).
       
      Use Cases / Examples:
      Colored grid cells, Icons, Links etc. The Grid also has a "batcher" feature built in that helps communicating with the server via AJAX and managing resource intensive tasks in batches:

      Filters, PW panel links and instant reload on panel close:

      You can combine the grid with a chart library like I did with the (outdated) RockDataTables module:

    • By Ken Muldrew
      I'm trying to get a short routine to run once per day that will look at some pages and send a reminder email when that customer's subscription (yearly) is about to expire. When I run the code in a template then it works without issue, but inside my lazycron service routine, I get an "Error: Uncaught Error: Call to a member function get() on null" as if the database cannot be found. My autoload module is just the sample HelloWorld module included with ProcessWire, editted to perform this task. The whole of it is included below (I've stripped out the code that generates the email because it never gets past $pages->find):
       
      <?php namespace ProcessWire;
      /**
       * ProcessWire 'LazyCronLoad'  module
       *
       */
      class LazyCronLoad extends WireData implements Module {
          public static function getModuleInfo() {
              return array(
                  'title' => 'LazyCronLoad', 
                  'version' => 1, 
                  'summary' => 'Just loads a lazy cron callback.',
                  'singular' => true, 
                  'autoload' => true, 
                  );
          }
          public function init() {
              // initialize the hook in the AutoLoad module
              $this->addHook('LazyCron::everyDay', $this, 'myHook');
              
          }
          public function myHook(HookEvent $e) {
              // called once per day
              wire('log')->save('user_activities',' lazy cron service routine');
                  $transport_pages = $pages->find("template=aggregate-entry, aggregate_type.title='Transport'");
                  foreach ($transport_pages as $page) {
                      if (($page->purchase_date + 30325800 < time()) && ($page->purchase_date + 30412600 > time())) { // between 351 and 352 days
                          wire('log')->save('user_activities', $page->id . ' email reminder sent');
                          // send email
                  }
              }
          }        
          
      }
      The first wire('log') shows up but the second one doesn't (the purchase_date condition is met (as demonstrated by running the code in a template close in time to when the lazycron routine executes)). The error log gives the Uncaught Error shown above. 
      I think this is a beginner's mistake with something obvious being missed and would be grateful for any assistance in fixing it.