Koha plugin development reference

From Koha Wiki
Jump to navigation Jump to search

A plugin to inject javascript to a koha page.

Koha plugins come as kpz files which are simple zip archives.

A customer requested a new hotkey feature on /cgi-bin/koha/cataloguing/addbiblio.pl and a plugin seemed like the smartest way to implement it.

hooks

Koha has plugin hooks and I am using the intranet_js hook to inject javascript into a staff page.

code

mkdir -p ~/koha-plugin-addhotkeys/Koha/Plugin/AddHotkeys
cd ~/koha-plugin-addhotkeys/Koha/Plugin/
vim AddHotkeys.pm
package Koha::Plugin::AddHotkeys;

use Modern::Perl;

use base qw(Koha::Plugins::Base);

our $VERSION = "0.1";

our $metadata = {
    name            => 'AddHotkeys',
    author          => 'David Schmidt',
    date_authored   => '2021-03-09',
    date_updated    => "2021-03-09",
    minimum_version => '19.05.00.000',
    maximum_version => undef,
    version         => $VERSION,
    description     => 'this plugin adds javascript hotkeys to addbiblio.pl',
};

sub new {
    my ( $class, $args ) = @_;

    $args->{'metadata'} = $metadata;
    $args->{'metadata'}->{'class'} = $class;

    my $self = $class->SUPER::new($args);
    $self->{cgi} = CGI->new();

    return $self;
}

sub intranet_js {
    my ( $self ) = @_;
    my $cgi = $self->{'cgi'};
    my $script_name = $cgi->script_name;

    my $js = <<'JS';
    <script>
      function hotkey(e) {
        if (e.ctrlKey && e.altKey) {
          let next_tab_id;
          if ( /^[0-9]$/.test(e.key) ) {
            next_tab_id = e.key;
          }
          if ( e.key === 'ArrowRight' || e.key === 'ArrowLeft' ) {
            let active_tab = document.querySelector('.toolbar-tabs li.selected a');
            let active_tab_id = active_tab.getAttribute('data-tabid');
            next_tab_id = parseInt(active_tab_id, 10);
            if (e.key === 'ArrowRight') { next_tab_id = next_tab_id + 1; }
            if (e.key === 'ArrowLeft') { next_tab_id = next_tab_id - 1; }
            if (next_tab_id < 0) { next_tab_id = 9; }
            if (next_tab_id > 9) { next_tab_id = 0; }
          }
          if ( typeof next_tab_id !== 'undefined' ) {
            let tab = document.querySelector('.toolbar-tabs li a[data-tabid="' + next_tab_id + '"]');
            if (tab) { tab.click(); }
          }
        }
      }
      document.addEventListener('keyup', hotkey, false);
    </script>
JS

    # inject JS only for the addbiblio.pl page
    if ( $script_name =~ /addbiblio\.pl/ ) {
        return "$js";
    }
}

1;


kpz file

cd ~/koha-plugin-addhotkeys
zip -r koha-plugin-addhotkeys.kpz Koha/

installation

  1. enable plugin usage for your koha instance. [1]
  2. upload kpz file on the koha plugins page. Koha > Tools > Plugins
  3. after the upload you should see a list with the new plugin.
  4. activate the plugin (click the Activate link)