Jump to content
kixe

FieldtypeColor

Recommended Posts

FieldtypeColor is on github

Fieldtype stores a 32bit integer value reflecting a RGBA value.

Input
5 types of Inputfields provided

  1. Html5 Inputfield of type='color' (if supported by browser)   
  2. Inputfield type='text' expecting a 24bit hexcode string (RGB). Input format: '#4496dd'.
    The background color of the input field shows selected color
  3. Inputfield of type='text' expecting 32bit hexcode strings (RGB + alpha channel) Input format: '#fa4496dd'
  4. Inputfield with Spectrum Color Picker
    (Options modifiable)
  5. Inputfield type='text' with custom JavaScript and/or CSS (since version 1.0.3)

Output
Define output format under 'Details' tab in field settings. Select from the following 9 options

  1. string 6-digit hex color. Example: '#4496dd'
  2. string 8-digit hex color (limited browser support).  Example: '#fa4496dd'
  3. string CSS color value RGB. Example: 'rgb(68, 100, 221)'
  4. string CSS color value RGB. Example: 'rgba(68, 100, 221, 0.98)'
  5. string CSS color value RGB. Example: 'hsl(227, 69.2%, 56.7%)'
  6. string CSS color value RGB. Example: 'hsla(227, 69.2%, 56.7%, 0.98)'
  7. string 32bit raw hex value. Example: 'fa4496dd'(unformatted output value)
  8. int 32bit. Example: '4198799069' (storage value)
  9. array()
    array(
            [0] => 0-255, // opacity
            [1],['r'] => 0-255,
            [2],['g'] => 0-255,
            [3],['b'] => 0-255,
            ['rx'] => 00-ff,
            ['gx'] => 00-ff,
            ['bx'] => 00-ff,
            ['ox'] => 00-ff, // opacity
            ['o'] => 0-1 // opacity
        )

     

The Fieldtype includes
Spectrum Color Picker by Brian Grinstead


SCREENSHOTS

Input type=text with changing background and font color (for better contrast)
5961bca865f8b_Bildschirmfoto2017-07-09um07_15_59.jpg.f1eb7e6755c9f4294ed153c55ce21099.jpg5961bcada5afb_Bildschirmfoto2017-07-09um07_15_44.jpg.7973bcaf133505bbd00e2f7d376a766b.jpg5961bcbc7a5e4_Bildschirmfoto2017-07-09um07_15_28.jpg.2d5a1f057957060664401e59a5cd5c27.jpg5961bcc326fc1_Bildschirmfoto2017-07-09um07_15_11.jpg.5c5e04f682c8c45ede37075f6754b108.jpg

Input type=color (in Firefox)

5961bd89d58be_Bildschirmfoto2017-07-09um07_11_36.jpg.dbfabd7c9baa0539c0955b3ab75c15ae.jpg


Javascript based input (Spectrum Color Picker)

5961be102fdb8_Bildschirmfoto2017-07-09um06_38_04.jpg.650494794d4f7c37be8f458270726ac7.jpg


Settings Output

5961bdf1aa93a_Bildschirmfoto2017-07-09um07_10_19.jpg.0fb6aff0e5d1eed95778a886a1544d52.jpg

 

Settings Input
5961bdf624096_Bildschirmfoto2017-07-09um07_09_03.jpg.f19af3f408630fde0681923577569cd2.jpg

  • Like 21

Share this post


Link to post
Share on other sites

hi kixe,

thanks for sharing this :) would you mind adding some screenshots or a sample usecase to know when your module would be useful? maybe you could also point out the differences to somas colorpicker module?

thanks!

  • Like 1

Share this post


Link to post
Share on other sites

Updated to Version 1.0.3 with one more Inputfield Option which allows to use any custom JavaScript.
59621ba2834e7_Bildschirmfoto2017-07-09um13_56_41.thumb.jpg.c1bfb55ab2e59b3a0da77e28c8c8a47b.jpg

  • Like 5

Share this post


Link to post
Share on other sites

Some time ago, I made a site for a company which sells wool. In this case I use the fieldtype color for the different colors of a wool product (as a color scheme board). In this case I use the old color picker field (I think it was from Soma). This could be a possible usecase example for this fieldtype.

Share this post


Link to post
Share on other sites

I played around a bit with custom JS based Input. Here are the settings for 3 individual JS based input options:

ColorPicker by Stefan Petr (http://www.eyecon.ro/colorpicker/)

initial JS

$('#{id}').ColorPicker({
    color: '{value}',
    onChange: function (hsb, hex, rgb) {
        $('#{id}').attr('value', '#' + hex);
    }
});

include JS
colorpicker/js/colorpicker.js

include CSS
colorpicker/css/colorpicker.css

5996bb73a3eba_Bildschirmfoto2017-08-17um10_25_35.jpg.dd8c3958bde64fc22e9d0f83bb1191de.jpg

 

 

JSColor by Jan Odvarko (http://jscolor.com/)

initial JS

var input = document.getElementById('{id}');
var picker = new jscolor(input);

include JS
jscolor-2.0.4/jscolor.js

5996bb39235e0_Bildschirmfoto2017-08-17um10_56_43.jpg.2fe2df34fbaed5354c851f8a20e515f4.jpg

 

 

Color Picker (http://dematte.at)

initial JS

$('#{id}').colorPicker();

include JS
dematte/jQueryColorPicker.min.js

Pull js file from here: https://github.com/PitPik/colorPicker/blob/master/jQuery_implementation/jQueryColorPicker.min.js

5996baff218b8_Bildschirmfoto2017-08-17um11_22_03.jpg.ce0d7c3e52b7a163a15ebe2d8ab50f37.jpg


 

 

 

 

  • Like 2

Share this post


Link to post
Share on other sites

Thanks  kixe for this great picker, but I do not know why when saving color lost settings to the defolt? I'm using processwire 3.0.62 Master

Share this post


Link to post
Share on other sites

@rafaoski
Are you talking about the field settings? Could you please explain more detailed what happened that I can reproduce the issue. Thanks.

Share this post


Link to post
Share on other sites

I'm sorry kixe for my bad english ... Maybe this video will bring something ... Maybe somewhere I make a mistake when configuring the plugin ... View and rate ...

 

Share this post


Link to post
Share on other sites

@rafaoski
thanks for the video. Unfortunately I cannot reproduce. Could you check if the value is changed in the database? It looks like the setting is falling back to a previous default value. Could you unset the default value and try again?

I made a screenshop of the fieldsettings. Is it similar to yours? Did you try custom js code?

59a4293c5a7f7_Bildschirmfoto2017-08-28um16_30_10.jpg.f4f13eb7b7a389c6775407e186f16d53.jpg

Share this post


Link to post
Share on other sites

Thanks kixe for the reply ... My table is out of date:

Firefox_Screenshot_2017-08-28T16-16-44_798Z.thumb.png.92609adda1bb8ddee5c973591e71369d.png

And Field Settings Screenshot :

Firefox_Screenshot_2017-08-28T15-25-58_186Z.png.b7928a5f9bcbfaf1b510b675fadc8096.png

I did not add my own js code ... How to solve the problem I will let you know ... Thanks again for help ...

Share this post


Link to post
Share on other sites

I tested on Hosting and it works Correctly ... It's a bit weird, maybe it's through the Win 10 + Xampp Server ...

Share this post


Link to post
Share on other sites

I will be testing Laragon ... I just started to refresh the partition on some Linux derivative (maybe manjaro) ... I have to admit that Processwire has very good people around you who help ... Thank you both @kixe and you @bernhard ... Next time before I start looking for problems I will check on other machines - Such a lesson for the future :)

  • Like 1

Share this post


Link to post
Share on other sites

I'm having the problem that i always get the 2nd option output (8 digit hex color, and no hash), no matter what i select for the Output Format.

Right now i'm doing an ltrim($widget->color, 'ff');  on the output, and then adding the hash myself, but would be good to get this fixed...

TIA

Share this post


Link to post
Share on other sites

@Macrura

Page output formatting?

$page->of(false);
var_dump($page->color); // string(8) "ff5a01fd"
$page->of(true);
var_dump($page->color); // string(7) "#5a01fd"

 

  • Like 1

Share this post


Link to post
Share on other sites

Yes - thanks, i'm using the color on an admin dashboard, which is being wireRendered from a module, so i assume that output formatting is off; Is there any way to get the formatted output in this situation?

Share this post


Link to post
Share on other sites

If $widget is a page object it should be possible to put outputformatting on just to grab the value and switch it of after.

If not you can use the formatValue() function from the module. You need a page and a field object as arguments. $page can be any page in this case but $field should be the one where the OF type is stored.

$FieldtypeColor = wire('modules')->get('FieldtypeColor');
$field = new Field();
$unformattedColor = "ff5a01fd";
$page = new Page();
$field->type = $FieldtypeColor;
$field->outputFormat = 0;
$color = $FieldtypeColor->formatValue($page,$field,$unformattedColor);
var_dump($color); // string(7) "#5a01fd" 

 

  • Like 3

Share this post


Link to post
Share on other sites

this does work:

    $FieldtypeColor = wire('modules')->get('FieldtypeColor');
    $field = $fields->get('dw_color');
    $field->outputFormat = 0;
    $widgetColor = $FieldtypeColor->formatValue($widget,$field,$widget->dw_color);

i just wonder if it is simpler/more efficient to do it this way:

$widgetColor = '#' . ltrim($widget->dw_color, 'ff');

 

Share this post


Link to post
Share on other sites

Hi, thanks for this really nice module.

I'm trying to initiate this module from within another module and have no luck so far. This is my config:

$colors[] = [
    'name'         => 'color',
    'type'         => 'color',
    // 'inputType'    => 3,
    'outputFormat' => 3,
    'showInput'    => true,
    'defaultValue' => '#ff0080ff',
    'collapsed'    => 0,
    'alpha'        => 0,
    'spectrum'     => "showInput: true\nallowEmpty:true\nshowAlpha: true\nshowInitial: true\nchooseText: \"Alright\",\ncancelText: \"No way\"\npreferredFormat: \"hex3\"",
    'class'        => 'FieldtypeColor',
    'label'        => $this->_($key),
    'description'  => $this->_(''),
    'required'     => false,
    'value'        => '#ff3300',
    'columnWidth'  => 25,
    'notes'        => $this->_('Initial value: ' . $value),
];

If I comment in "inputType => 3", ProcessWire returns "The process returned no content." when saving my modules config. Ok, as a workaround, I could live without Spectrum. When is commented out, it saves and returns the modules config page correctly.

But the field "color" doesn't show the value of #ff0000. It returns in JS console: "The specified value "#00000" does not conform to the required format." That's weird: where has my Value of "#ff3300" gone? Alright, it seems to return the FieldtypeColor's default of "#000000". But wait, there is a "0" missing in JS error log's message...

Obviously I'm doing something wrong here. I hope someone has an idea how to call this module from within my other custom module correctly. Thanks in advance.

Share this post


Link to post
Share on other sites

@titanium

Sorry for the extremely delayed answer.

On 22.10.2017 at 9:28 PM, titanium said:

But wait, there is a "0" missing in JS error log's message...

Thanks for pointing on this. I pushed an update which allows to use InputfieldColor as a config field for modules.

I have made some changes in the code you have posted and tested it within the following module. Everything seems to work. Please check out.

<?php namespace ProcessWire;

class My2Module extends WireData implements Module, ConfigurableModule {

	/**
	 *
	 * @return array
	 *
	 */
	public static function getModuleInfo() {

		return array(
			'title' => 'My2Module',
			'summary' => 'Module with Config Input of type Color', 
			'version' => 100
			);
	}

	static public function getDefaultConfig() {
		return array(
			'color' => '#ff3300'
		);
	}

	public function __construct() {
		foreach(self::getDefaultConfig() as $key => $value) {
			$this->$key = $value;
		}
	}

	/**
	 * Initialize, attach hooks 
	 *
	 */
	public function init() {
		// ...
	}

	/**
	 * module settings
	 *
	 */
	static public function getModuleConfigInputfields(array $data) {
		
		$fields = new InputfieldWrapper();
		$defaults = self::getDefaultConfig();
		$data = array_merge($defaults, $data);
	
		$colors = [
				'name'         => 'color',
				'inputType'    => 3,
				'type'         => 'color', // will search for 'InputfieldColor'
				// 'outputFormat' => 3, // REMOVED outputFormat is related to the Fieldtype and not to the Inputfield
				// 'defaultValue' => '#ff0080ff', // REMOVED @see getDefaultConfig() and __construct()
				// 'alpha'        => 0, // REMOVED related to 'inputType=4', otherwise automatically set by the Inputfield
				'spectrum'     => "showInput: true\nallowEmpty:true\nshowAlpha: true\nshowInitial: true\nchooseText: \"Alright\"\ncancelText: \"No way\"\npreferredFormat: \"hex3\"",
				// 'class'        => 'FieldtypeColor', // REMOVED (unnecessary)
				'label'        => __('Label'),
				'description'  => __('Description'),
				'required'     => false,
				'value'        => $data['color'],
				'notes'        => __('Initial value: '.$defaults['color']),
			];

		$fields->add($colors);
		return $fields;
	}
}

 

  • Like 3

Share this post


Link to post
Share on other sites

@kixe - it might be worth noting that this module requires PHP's bcmath extension because of the call to: bcmod (and maybe others). 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      A community member raised a question and I thought a new sanitizer method for the purpose would be useful, hence...
      Sanitizer Transliterate
      Adds a transliterate method to $sanitizer that performs character replacements as defined in the module config. The default character replacements are based on the defaults from InputfieldPageName, but with uppercase characters included too.
      Usage
      Install the Sanitizer Transliterate module.
      Customise the character replacements in the module config as needed.
      Use the sanitizer on strings like so:
      $transliterated_string = $sanitizer->transliterate($string);
       
      https://github.com/Toutouwai/SanitizerTransliterate
      https://modules.processwire.com/modules/sanitizer-transliterate/
       
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version to 2.10, add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "http://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


    • By thomasaull
      I created a little helper module to trigger a CI pipeline when your website has been changed. It's quite simple and works like this: As soon as you save a page the module sets a Boolean via a pages save after hook. Once a day via LazyCron the module checks if the Boolean is set and sends a POST Request to a configurable Webhook URL.
      Some ideas to extend this:
      make request type configurable (GET, POST) make the module trigger at a specified time (probably only possible with a server cronjob) trigger manually Anything else? If there's interest, I might put in some more functionality. Let me know what you're interested in. Until then, maybe it is useful for a couple of people 🙂
      Github Repo: https://github.com/thomasaull/CiTrigger
    • By Robin S
      I created this module a while ago and never got around to publicising it, but it has been outed in the latest PW Weekly so here goes the support thread...
      Unique Image Variations
      Ensures that all ImageSizer options and focus settings affect image variation filenames.

      Background
      When using methods that produce image variations such as Pageimage::size(), ProcessWire includes some of the ImageSizer settings (height, width, cropping location, etc) in the variation filename. This is useful so that if you change these settings in your size() call a new variation is generated and you see this variation on the front-end.
      However, ProcessWire does not include several of the other ImageSizer settings in the variation filename:
      upscaling cropping, when set to false or a blank string interlace sharpening quality hidpi quality focus (whether any saved focus area for an image should affect cropping) focus data (the top/left/zoom data for the focus area) This means that if you change any of these settings, either in $config->imageSizerOptions or in an $options array passed to a method like size(), and you already have variations at the requested size/crop, then ProcessWire will not create new variations and will continue to serve the old variations. In other words you won't see the effect of your changed ImageSizer options on the front-end until you delete the old variations.
      Features
      The Unique Image Variations module ensures that any changes to ImageSizer options and any changes to the focus area made in Page Edit are reflected in the variation filename, so new variations will always be generated and displayed on the front-end.
      Installation
      Install the Unique Image Variations module.
      In the module config, set the ImageSizer options that you want to include in image variation filenames.
      Warnings
      Installing the module (and keeping one or more of the options selected in the module config) will cause all existing image variations to be regenerated the next time they are requested. If you have an existing website with a large number of images you may not want the performance impact of that. The module is perhaps best suited to new sites where image variations have not yet been generated.
      Similarly, if you change the module config settings on an existing site then all image variations will be regenerated the next time they are requested.
      If you think you might want to change an ImageSizer option in the future (I'm thinking here primarily of options such as interlace that are typically set in $config->imageSizerOptions) and would not want that change to cause existing image variations to be regenerated then best to not include that option in the module config after you first install the module.
       
      https://github.com/Toutouwai/UniqueImageVariations
      https://modules.processwire.com/modules/unique-image-variations/
    • By Sebi
      I've created a small module which lets you define a timestamp after which a page should be accessible. In addition you can define a timestamp when the release should end and the page should not be accessable any more.
      ProcessWire-Module: http://modules.processwire.com/modules/page-access-releasetime/
      Github: https://github.com/Sebiworld/PageAccessReleasetime
      Usage
      PageAccessReleasetime can be installed like every other module in ProcessWire. Check the following guide for detailed information: How-To Install or Uninstall Modules
      After that, you will find checkboxes for activating the releasetime-fields at the settings-tab of each page. You don't need to add the fields to your templates manually.
      Check e.g. the checkbox "Activate Releasetime from?" and fill in a date in the future. The page will not be accessable for your users until the given date is reached.
      If you have $config->pagefileSecure = true, the module will protect files of unreleased pages as well.
      How it works
      This module hooks into Page::viewable to prevent users to access unreleased pages:
      public function hookPageViewable($event) { $page = $event->object; $viewable = $event->return; if($viewable){ // If the page would be viewable, additionally check Releasetime and User-Permission $viewable = $this->canUserSee($page); } $event->return = $viewable; } To prevent access to the files of unreleased pages, we hook into Page::isPublic and ProcessPageView::sendFile.
      public function hookPageIsPublic($e) { $page = $e->object; if($e->return && $this->isReleaseTimeSet($page)) { $e->return = false; } } The site/assets/files/ directory of pages, which isPublic() returns false, will get a '-' as prefix. This indicates ProcessWire (with activated $config->pagefileSecure) to check the file's permissions via PHP before delivering it to the client.
      The check wether a not-public file should be accessable happens in ProcessPageView::sendFile. We throw an 404 Exception if the current user must not see the file.
      public function hookProcessPageViewSendFile($e) { $page = $e->arguments[0]; if(!$this->canUserSee($page)) { throw new Wire404Exception('File not found'); } } Additionally we hook into ProcessPageEdit::buildForm to add the PageAccessReleasetime fields to each page and move them to the settings tab.
      Limitations
      In the current version, releasetime-protected pages will appear in wire('pages')->find() queries. If you want to display a list of pages, where pages could be releasetime-protected, you should double-check with $page->viewable() wether the page can be accessed. $page->viewable() returns false, if the page is not released yet.
      If you have an idea how unreleased pages can be filtered out of ProcessWire selector queries, feel free to write an issue, comment or make a pull request!
×
×
  • Create New...