Jump to content

No-Module Color Picker (One Simple Hook)


bernhard
 Share

Recommended Posts

Ever needed a color picker on some kind of settings page? Didn't want to install and setup a full-blown colorpicker module? Here's a quick and dirty hook to change a regular text field into an <input type="color"> type of input:

Before:

IVR83Bx.png

After:

bhifzzr.png

<?php

public function init(): void
{
  wire()->addHookBefore('Inputfield::render', $this, 'changeFieldType');
}

public function changeFieldType(HookEvent $event): void
{
  $f = $event->object;
  $colorFields = [
    Site::field_col_primary,
    Site::field_col_secondary,
    Site::field_contrast_primary,
    Site::field_contrast_secondary,
  ];
  if (!in_array($f->name, $colorFields)) return;
  $f->attr('type', 'color');
}

So right before the text input is rendered we change its "type" property to "color" and the browser will render a default color picker ๐Ÿ˜Ž

It once more shows how versatile ProcessWire is. And maybe it helps someone... ๐Ÿ™‚ 

PS: Be advised that with that hack you only modify the optics of the field. The field will under the hood still be a regular text field, which means you'll not get any sanitisation or such from it and you might have to take care of that on your own. In my case it's a superuser-only settings page. So it is no issue at all.

  • Like 8
  • Thanks 2
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
ร—
ร—
  • Create New...