Recommended Posts

Hi guys I'm relatively new to PW and just finished developing a page for a client. I was able to include all necessary functionality using the core fieldtypes but now I it seems that I need to extend them with a custom one. What I need is a simple button, that copies the absolute url (frontend not PW-backend) of the page which is currently edited to the clipboard. As this feature is only needed inside a specific template, I tend to use a custom fieldtype which provides this feature. I've been looking inside the core modules code (eg. FieldtypeCheckbox.module) but I don't really get the structure of it and how its rendered to the admin page. I also didn't find a lot of tutorials covering custom fieldtypes.

Maybe some of you could give me some tips on how to write a basic custom fieldtype that renders a button which copies the value of

page->httpUrl()

to the clipboard using JS. Thanks!

Share this post


Link to post
Share on other sites

Sounds to me like a good option is the RuntimeMarkup module, so you can basically render whatever you want in the inputfield, and add the necessary javascript to do the whole copy-paste to clipboard. 

  • Like 2

Share this post


Link to post
Share on other sites
13 hours ago, Thomas Diroll said:

I need is a simple button, that copies the absolute url (frontend not PW-backend) of the page which is currently edited to the clipboard.

Hello,

I have something similar I hope you can adapt it to your needs. Mine is for user templates:

<?php 
//adds a button to the end of the user edit page:
$this->addHook('ProcessPageEdit::buildForm', function (HookEvent $event) {
    $current_page = $event->object->getPage();

    if ($current_page->template->name != 'user') return; // this button is for the user edit page only
    if (empty($current_page->user_family_name)) return; // custom field is not yet filled in, which means the new User has not been saved but still being edited in the admin

    $id = (int) $current_page->id;
    if ($id != 0) {
        if ($current_page->hasRole('mycustomrole')) {

            $href = createLink($current_page); // this is a custom function to be implemented, it must generate and return the required URL 
            $field = $this->modules->get('InputfieldButton');
            $field->attr('class', $field->class . " my-custom-css-class-if-needed"); // this is just opitional, I left it here as an example
            $field->attr('value', 'Copy URL to clipboard...');
            $field->attr('data-clipboard-text', $href); // data-clipboard-text is needed by https://clipboardjs.com/
            $field->attr('href', ''); // $href

            $event->return = $event->return->append($field);
        }
    }
});

The copy to clipboard action is performed by https://clipboardjs.com/ which can be loaded by the admin using various techniques or free modules (such as AdminOnSteroids or Admin Custom Files) or one can simply put this line into config.php: $config->scripts->add($config->urls->templates . "clipboard.min.js"); where clipboard.min.js is in the templates directory, for example.

EDIT: I forgot to note that the hook goes into init.php

  • Like 6

Share this post


Link to post
Share on other sites

Thanks for all your answers!!! This was really fast and seems like a very active community! I'm sure the code snippet by @szabesz and the fieldtype by @kixe will work as well and are definitely more lightweight. I went with the RuntimeMarkup fieldtype suggested by @elabx as it was the fastest and easiest one to apply. Here is my php snippet for the runtime field:

return "
<a id='custom-action-button' href='#' onclick='copyUrlToClipboard(event);'>Copy URL to clipboard</a>
<input type='text' value='" . $page->httpUrl() . "' id='target-page-url'>
<p id='action-executed-hint'>Successfully copied URL to clipboard!</p>

<style>
#custom-action-button {
color: #FFF;
background: #93BF0D;
font-weight: bold;
padding: 0.6em 1.1em;
font-size: 1em !important;
border-radius: 5px;
}
#custom-action-button:hover {
color: #FFF;
background-color: #DB1174;
}
#custom-action-button:active {
color: #FFF;
background-color: #860A47;
}
#custom-action-button:visited {
color: #FFF;
}
#target-page-url {
position: absolute;
left: -9999px;
top: -9999px;
opacity: 0;
pointer-events: none;
}
#action-executed-hint {
display: none;
}
#action-executed-hint.show {
display: inline;
}
</style>

<script>
function copyUrlToClipboard(event) {
event.preventDefault();
var urlText = document.getElementById('target-page-url');
urlText.select();
document.execCommand('copy');
var hint = document.getElementById('action-executed-hint');
hint.className += ' show';
}
</script>
";

It creates an a-tag which is styled like a backend button. Hope its useful for someone else!

  • Like 7

Share this post


Link to post
Share on other sites
On 8/9/2018 at 7:13 PM, Thomas Diroll said:

Here is my php snippet for the runtime field:

Just seen this. Welcome to the forums @Thomas Diroll. It's better (readability, maintenance, etc) to throw the code in a file and call it using the wireRenderFile() method. 

If using ProcessWire 3.x, you will need to use namespace as follows:

return ProcessWire\wireRenderFile('name-of-file');

Share this post


Link to post
Share on other sites

We also have: 

$files->render()

these days.

  • Like 2

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 ridgedale
      Reference: PW 3.0.111 and uikit3 based site using the Regular-Master profile.
      I am trying to add a field that provides a dropdown menu but there are no Options or Selector(s) type available - see attached image of field types available.
      The following reference under the docs does not appear to be applicable any more:
      https://processwire.com/api/modules/select-options-fieldtype/
      I can't see how to achieve this. Any assistance would be appreciated.

    • By mjut
      Hello!
      I am trying to get some extra css-file into my admin templates. I managed to modify my admin.php to this:
      <?php namespace ProcessWire; require($config->paths->adminTemplates . 'controller.php'); echo "<link rel='stylesheet' type='text/css' href='" . $config->urls->templates . "css/admin.css'>"; By doing so, the css <link> is added to the very end of each parsed admin-html. (right AFTER the closing </body> tag.)
      That causes some trouble. e.g. the page tree is not displaying any more. Although, other pages are working - like the edit form of a page.
      My question: is there a correct way of adding my extra css to the admin area?
      Thanks for you help!
      Stephan
       
    • 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/
    • By Mike Rockett
      As I mentioned in this issue, I've create a new textformatter for ParsedownExtraPlugin, which adds some oomph to your markdown.
      Repo: Parsedown Extra Plugin
      Unlike the built-in textformatter for Parsedown and Parsedown Extra, this should be used when you want to use Extra with additional configuration/customisation.
      Some examples:
      ### Test {.heading} - A [external link](https://google.com/){.google} with `google` as a class that opens in a new tab if the config property is set. - [Another link](/page){target=_blank} that opens in a new tab even though it isn't external. ```html .html <p>Test</p> ``` There's some config options available to you, such as setting attributes on all/external images and links, setting table and table-cell alignment classes, adjusting footnote classes and IDs, adding <code> attributes to their parent <pre> elements, and changing the <code> class if your syntax highlighter does not use language-*.
      I was thinking about adding the ability to make links open in a new tab by appending a plus to the link syntax, but only external links should be opening in a new tab anyway. Further, this would add extra, unnecessary processing time.
      Please let me know if you bump into any problems. ☺️