Jump to content
kongondo

Module: RuntimeMarkup Fieldtype & Inputfield

Recommended Posts

Thanks @adrian

@Robin S's module is simple and sweet. Sadly cannot use in FormBuilder as it has both the Inputfield class and the Fieldtype class within the FieldtypeRuntimeOnly.module file. FormBuilder looks for module files prefixed with 'Inputfield' in its list of approved input types.

I use @bernhard's module 'RockMarkup2' elsewhere in the project and only discovered that it's designed to only work in admin and it's been deprecated. However, just tried it in FormBuilder and it works a treat.

Maybe Robin and Bernhard can get together to come up with an easy to use module that has separate files for Fieldtype & Inputfield. That would be awesome! 

Share this post


Link to post
Share on other sites

Hey @psy I'd create a custom runtime module, it's not too hard:

1) Create the fieldtype:

2) Create the inputfield:

RockMarkup is deprecated because I don't plan to use it as base module for other Fieldtypes in the future. I think it makes things more complicated and that's not worth it. Building custom fieldtypes + inputfields is easy once you know how things work. Especially runtime fields are easy because you don't need all the DB related parts.

If you need any help just ask.

  • Like 2

Share this post


Link to post
Share on other sites
3 minutes ago, bernhard said:

I'd create a custom runtime module

Thanks @bernhard, after looking at your RockMarkup2 and Adrian's RuntimeOnly modules + your tutorials, am sure I could figure it out. For this project however, I'm under the gun with a rapidly approaching deadline. Will explore creating my own module when the pressure is off.

Share this post


Link to post
Share on other sites

@psy, in theory you don't need any sort of special module to put runtime markup into a field. Instead just add a Markup field to the form and then hook before the form is rendered to put whatever markup you want into it.

Having said that, there are some oddities with Markup fields in FormBuilder. I raised some questions that Ryan answered here: 

 

But I still had some other problems (I can't remember exactly what they were now) that I ended up resolving by making a clone of the core InputfieldMarkup module with some minor changes. I've attached the resulting InputfieldCustomMarkup module. If you install this module and enable it for use in FormBuilder then you can use it the same as a Markup field but without the snags.

InputfieldCustomMarkup.zip

  • Like 2

Share this post


Link to post
Share on other sites

@Robin S

Thank you! So many options and as said to Bernhard, will explore when I have time. Right now RockMarkup2 is doing the job with FB and elsewhere in the project.  Will replace when the pressure is off

Share this post


Link to post
Share on other sites

Great module, but I'm having a couple of minor issues (unrelated, I think).

The first issue seems intermittent and I can't work out why In some cases, I can't get the inclusion of .js and .css to work. I've triple-checked all the naming etc. but the files just don't seem to load. My work-round (easy enough) is just to load the files in the php.

The second issue may be because I am stretching the fieldtype's capability! I am using it within a PageTable field as follows.

The PageTable field ("panelled_carousel") has a template "Panelled_carousel" which has fields "title", "imagePages" (a page reference field linking to a page with template "Image" and an image field "image_single") and "runtime_markup_images" (a runtime markup field with php file "RuntimeMarkup/Images.php").

The php file is (including a bit of debugging):

$imagePages = $page->imagePages;
bd($page, 'page with carousel');
$out = '';
wire()->log->save('debug', 'Page is ' . $page->title);
foreach ($imagePages as $imagePage) {
    bd($imagePage, 'imagePage');
    foreach ($imagePage->image_single as $image) {
        bd($image, 'image');
       if (is_a($image, '\ProcessWire\Pageimage')) $out .= '<img src="' . $image->pia("width=200")->url . '"/>';
    }
}
return  $out;

The RM field is updated when the imagePages field changes by javascript/AJAX :

When editing the Page Table field, this all works well - any changes in the imagePages (add/re-order/delete etc) are immediately reflected in the RM field. However, when saving the Page Table Field and returning to the host page, the RM PHP throws an error unless I catch it with the condition - is_a($image, '\ProcessWire\Pageimage') - in the code above. The reason is that in some cases $image seems to be taking a string, integer or boolean value, even though $imagePage has class Page and the dump shows it is the right page. Trapping this error means that the images in the table are all blank after the save. However refreshing the page puts everything right again. So not a deal-breaker but a bit odd.

To illustrate, here is the top page with the page table (including images):

1403291032_Toppage.thumb.jpg.ba0e32c4ea399931384b1e698af6fcad.jpg

Clicking on "Blue" to edit an item we get:

837229460_EditPageTableitem.thumb.jpg.41ff6cfec4e5f679cb7e63155d4e99f2.jpg

Then, clicking save and returning to the top page, the images do not render:

431478913_Aftersave.thumb.jpg.90ed19714a18bf1d45f8a1fa99e14c93.jpg

The debugging shows that this is not because Images.php has not run, but because $image is of the wrong type (as described above).

Refreshing the page restores the images.

Any ideas?

EDIT: I should add that the problem does not seem to be related to my .js script, or even RuntimeMarkup specifically as exactly the same issue happens in a Page Table with @Robin S's RuntimeOnly module with no js attached to it. So it seems to be something to do with how the runtime markup is interacting with the page table display.

Share this post


Link to post
Share on other sites

To make this work inside a page table, I had to hack the InputfieldPageTable.js as follows:

function InputfieldPageTableDialog() {

	var $a = $(this);
	var url = $a.attr('data-url');
	var title = $a.attr('data-title');
	var closeOnSave = true;
	var $container = $(this).parents('.InputfieldPageTableContainer');
	var wrap = $(this).closest('.InputfieldPageTable'); // MDE added
	var dialogPageID = 0;
	var noclose = parseInt($container.attr('data-noclose'));
	var modalSettings = {
		close: function(event, ui) {
			if(dialogPageID > 0) {
				var ajaxURL = $container.attr('data-url') + '&InputfieldPageTableAdd=' + dialogPageID;
				var sort = $container.siblings(".InputfieldPageTableSort").val();
				if(typeof sort != "undefined" && sort.length) ajaxURL += '&InputfieldPageTableSort=' + sort.replace(/\|/g, ',');
				$.get(ajaxURL, function(data) {
					$container.html(data);
					$container.find(".Inputfield").trigger('reloaded', ['InputfieldPageTable']);
					$container.effect('highlight', 500, function() {
						var $table = $container.find('table');
						$table.find('tbody').css('overflow', 'visible');
						InputfieldPageTableSortable($table);

						// restore appearnace of any items marked for deletion
						var deleteIDs = $container.siblings("input.InputfieldPageTableDelete").eq(0).val().split('|');
						if(deleteIDs.length) {
							for(var n = 0; n < deleteIDs.length; n++) {
								var deleteID = deleteIDs[n];
								$table.find("tr[data-id=" + deleteID + "]")
									.addClass('InputfieldPageTableDelete ui-state-error-text ui-state-disabled');
							}
						}
					});
				});
				if ($(wrap).attr('id')) $('#' + wrap.attr('id')).load(document.URL +  ' #' + wrap.attr('id')); // MDE added
			}
		}
	}
                                                                ....

The new lines are the ones annotated "MDE added"

I haven't found any unwanted side-effects (so far ..) but obviously I'm a bit unhappy about amending core code unless it warrants a PR, so I would be grateful for any thoughts on this, or other ideas.

Share this post


Link to post
Share on other sites
Posted (edited)
11 hours ago, MarkE said:

The debugging shows that this is not because Images.php has not run, but because $image is of the wrong type (as described above).

Refreshing the page restores the images.

Any ideas?

Sorry Mark, I got lost in that Green Bedroom. Man, I am dog tired and could do with that rest! 😄 

OK, back to reality. I haven't used the Page Table field in ages. How does it save stuff? Via Ajax or normal POST? I am just wondering whether this has to do with renderReady() as I have had similar issues before with Media Manager and Repeaters. Currently,  I don't have time to test but hopefully can get to this soon.

I've just seen your edit: Ajax it is.

Edited by kongondo

Share this post


Link to post
Share on other sites

Putting this:

    $(document).on('pw-modal-closed', function(event) {
        var wrap = $(this).find('.InputfieldPageTable');
        if ($(wrap).attr('id')) $('#' + wrap.attr('id')).load(document.URL +  ' #' + wrap.attr('id'));
    });

in the admin js avoids the need to hack the InputfieldPageTable.js. Again, there may be side effects that I haven't noticed. One side-effect I have noticed is that, after closing the modal, the rows in the Page Table can no longer be sorted by dragging - a full window refresh is still required for that.

Share this post


Link to post
Share on other sites

Here's my complete work-round for the problem with runtime markup images in a Page Table field. Something that prevents the problem occurring in the first instance would be better though!

1. Add the following condition for images rendered in the runtime markup:

if (is_a($image, '\ProcessWire\Pageimage')) $out .= '<img src="' . $image->url . '"/>';

2. Add the following to admin.js (the 2 functions are lifted from InputfieldPageTable.js):

/*******************************************************************************************************************/
/* Work-round to reload and re-enable sorting of Page Table field, which includes runtime markup, after modal edit */
/*******************************************************************************************************************/
    $(document).on('pw-modal-closed', function(event) {
        var wrap = $(this).find('.InputfieldPageTable');
        if ($(wrap).attr('id')) $('#' + wrap.attr('id')).load(document.URL +  ' #' + wrap.attr('id') + '> *'); // To just load the inner html of wrap - avoiding duplicating it
    });

    $('.InputfieldPageTable').mouseenter(function () {
        if (!$('tbody').hasClass("ui-sortable")) {
            var $table = $('tbody').closest('table');
            InputfieldPageTableSortable($table);
        }
    });

    function InputfieldPageTableUpdate($table) {
        var value = '';
        if(!$table.is('tbody')) $table = $table.find('tbody');
        $table.find('tr').each(function() {
            var pageID = $(this).attr('data-id');
            if(value.length > 0) value += '|';
            value += pageID;
        });
        var $container = $table.parents('.InputfieldPageTableContainer');
        var $input = $container.siblings('.InputfieldPageTableSort');
        $input.val(value);
    }

    function InputfieldPageTableSortable($table) {

        $table.find('tbody').sortable({
            axis: 'y',
            start: function(event, ui) {
                var widths = [];
                var n = 0;
                $table.find('thead').find('th').each(function() {
                    widths[n] = $(this).width();
                    n++;
                });
                n = 0;
                ui.helper.find('td').each(function() {
                    $(this).attr('width', widths[n]);
                    n++;
                });
            },
            stop: function(event, ui) {
                InputfieldPageTableUpdate($(this));
            }
        });

    }

/*******************************************************************************************************************/

 

Share this post


Link to post
Share on other sites
10 hours ago, MarkE said:

Something that prevents the problem occurring in the first instance would be better though!

Still not sure whether this is a RM issue or a PageTable one.

Share this post


Link to post
Share on other sites
10 hours ago, MarkE said:

is_a

Any reason why you prefer this over instanceof? Just curious.

Share this post


Link to post
Share on other sites
7 minutes ago, kongondo said:

Any reason why you prefer this over instanceof? Just curious

Agnostic. Probably instanceof is better.

Share this post


Link to post
Share on other sites
12 hours ago, kongondo said:

Still not sure whether this is a RM issue or a PageTable one.

Nor me. It seems like PT calls the RM PHP file more than once. The first time it works properly with a Pageimage, but then later calls submit a string/integer/boolean. The code to bypass the latter has the side effect that the RM field now has nothing in it - hence the need for the reload. All pretty messy! I've tried various debugging routes, but can't work out how the multiple calls are happening.

Share this post


Link to post
Share on other sites

Hi Kongondo,

 

first of all many thanks for this useful module!

My question is about the behaviour of RM fields on save. Usually, we fill the RM fields with some static html markup. After saving pages with RM fields, these fields always are anounced as "changed", but why? Is is possible to prevent this?

 

Best regards,

Thomas.

  • Like 1

Share this post


Link to post
Share on other sites

Hi @xportde. I have noticed the same thing. I assume this is important to you because you have some hook or other that you only want to operate if fields have changed. What I do is simply catch and exclude any field changes that I'm not interested in. E.g. in a Pages::saved hook:

        $excludeFields = ['runtime_markup_parent', etc.......];
        $changes = array_diff($event->arguments(1), $excludeFields);

 

Share this post


Link to post
Share on other sites
6 hours ago, xportde said:

After saving pages with RM fields, these fields always are anounced as "changed", but why? I

Because I tend to be a silly billy often times 😄.

It's happening because RM is not letting its parent class know that it is handling the processing of its WireInputData

6 hours ago, xportde said:

Is is possible to prevent this?

Yes, it is. I'll make the changes in the repo eventually, but meanwhile....please open up InputfieldRuntimeMarkup.module for editing. Scroll down to the end of the file. Find the method ___processInput() and un-comment it. The method's body is intentionally blank, so no changes needed there. Save :-). That should do it.

  • Like 1

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 Sten
      Hello
      Till now I hacked something with the twig template but it works no more with new PW versions so I look forward to create a module. I am working on a site in multiple languages : French, English, Italian, German, Spanish, Portuguese, Hebrew, Russian. The new posts are entered in any language with a field for language. Till now, I got twig files to get the translations with constants defined for each part of the pages.
      So I'd like to create a module to include theses files added according to the url /fr/en/...
      Have you some observations to do before I begin about the direction to take ?
      Thank you
    • By ukyo
      Mystique Module for ProcessWire CMS/CMF
      Github repo : https://github.com/trk/Mystique
      Mystique module allow you to create dynamic fields and store dynamic fields data on database by using a config file.
      Requirements
      ProcessWire 3.0 or newer PHP 7.0 or newer FieldtypeMystique InputfieldMystique Installation
      Install the module from the modules directory:
      Via Composer:
      composer require trk/mystique Via git clone:
      cd your-processwire-project-folder/ cd site/modules/ git clone https://github.com/trk/Mystique.git Module in live reaction with your Mystique config file
      This mean if you remove a field from your config file, field will be removed from edit screen. As you see on youtube video.
      Using Mystique with your module or use different configs path, autoload need to be true for modules
      Default configs path is site/templates/configs/, and your config file name need to start with Mystique. and need to end with .php extension.
      Adding custom path not supporting anymore !
      // Add your custom path inside your module class`init` function, didn't tested outside public function init() { $path = __DIR__ . DIRECTORY_SEPARATOR . 'configs' . DIRECTORY_SEPARATOR; Mystique::add($path); } Mystique module will search site/modules/**/configs/Mystique.*.php and site/templates/Mystique.*.php paths for Mystique config files.
      All config files need to return a PHP ARRAY like examples.
      Usage almost same with ProcessWire Inputfield Api, only difference is set and showIf usage like on example.
      <?php namespace ProcessWire; /** * Resource : testing-mystique */ return [ 'title' => __('Testing Mystique'), 'fields' => [ 'text_field' => [ 'label' => __('You can use short named types'), 'description' => __('In file showIf working like example'), 'notes' => __('Also you can use $input->set() method'), 'type' => 'text', 'showIf' => [ 'another_text' => "=''" ], 'set' => [ 'showCount' => InputfieldText::showCountChars, 'maxlength' => 255 ], 'attr' => [ 'attr-foo' => 'bar', 'attr-bar' => 'foo' ] ], 'another_text' => [ 'label' => __('Another text field (default type is text)') ] ] ]; Example:
      site/templates/configs/Mystique.seo-fields.php <?php namespace ProcessWire; /** * Resource : seo-fields */ return [ 'title' => __('Seo fields'), 'fields' => [ 'window_title' => [ 'label' => __('Window title'), 'type' => Mystique::TEXT, // or InputfieldText 'useLanguages' => true, 'attr' => [ 'placeholder' => __('Enter a window title') ] ], 'navigation_title' => [ 'label' => __('Navigation title'), 'type' => Mystique::TEXT, // or InputfieldText 'useLanguages' => true, 'showIf' => [ 'window_title' => "!=''" ], 'attr' => [ 'placeholder' => __('Enter a navigation title') ] ], 'description' => [ 'label' => __('Description for search engines'), 'type' => Mystique::TEXTAREA, 'useLanguages' => true ], 'page_tpye' => [ 'label' => __('Type'), 'type' => Mystique::SELECT, 'options' => [ 'basic' => __('Basic page'), 'gallery' => __('Gallery'), 'blog' => __('Blog') ] ], 'show_on_nav' => [ 'label' => __('Display this page on navigation'), 'type' => Mystique::CHECKBOX ] ] ]; Searching data on Mystique field is limited. Because, Mystique saving data to database in json format. When you make search for Mystique field, operator not important. Operator will be changed with %= operator.
      Search example
      $navigationPages = pages()->find('my_mystique_field.show_on_nav=1'); $navigationPages = pages()->find('my_mystique_field.page_tpye=gallery');
    • By Robin S
      This is a module I made as an experiment a while ago and never got around to releasing publicly. At the time it was prompted by discussions around using Repeater fields for "page builder" purposes, where the depth feature could possibly be used for elements that would be nested inside other elements. I thought it would be useful to enforce some depth rules and translate the depth data into a multi-dimensional array structure.
      I'm not using this module anywhere myself but maybe it's useful to somebody.
      Repeater Depth Helper
      This module does two things relating to Repeater fields that have the "Item depth" option enabled:
      It enforces some depth rules for Repeater fields on save. Those rules are:
      The first item must have a depth of zero. Each item depth must not be more than one greater than previous item depth. It provides a RepeaterPageArray::getDepthStructure helper method that returns a nested depth structure for a Repeater field value.
      Helper method
      The module adds a RepeaterPageArray::getDepthStructure method that returns a multi-dimensional array where the key is the page ID and the value is an array of nested "child" items, or null if there are no nested children.
      Example

      The module doesn't make any assumptions about how you might want to use the depth structure array, but here is a way you might use it to output a nested unordered list.
      // Output a nested unordered list from a depth structure array function outputNestedList($depth_structure, $repeater_items) { $out = "<ul>"; foreach($depth_structure as $page_id => $nested_children) { $out .= "<li>" . $repeater_items->get("id=$page_id")->title; // Go recursive if there are nested children if(is_array($nested_children)) $out .= outputNestedList($nested_children, $repeater_items); $out .= "</li>"; } $out .= "</ul>"; return $out; } $repeater_items = $page->my_repeater; $depth_structure = $repeater_items->getDepthStructure(); echo outputNestedList($depth_structure, $repeater_items);
       
      https://github.com/Toutouwai/RepeaterDepthHelper
      https://modules.processwire.com/modules/repeater-depth-helper/
    • By MoritzLost
      Cacheable Placeholders
      This module allows you to have pieces of dynamic content inside cached output. This aims to solve the common problem of having a mostly cacheable site, but with pieces of dynamic output here and there.  Consider this simple example, where you want to output a custom greeting to the current user:
      <h1>Good morning, <?= ucfirst($user->name) ?></h1> This snippet means you can't use the template cache (at least for logged-in users), because each user has a different name. Even if 99% of your output is static, you can only cache the pieces that you know won't include this personal greeting. A more common example would be CSRF tokens for HTML forms - those need to be unique by definition, so you can't cache the form wholesale.
      This module solves this problem by introducing cacheable placeholders - small placeholder tokens that get replaced during every request. The replacement is done inside a Page::render hook so it runs during every request, even if the response is served from the template cache. So you can use something like this:
      <h1>Good morning, {{{greeting}}}</h1> Replacement tokens are defined with a callback function that produces the appropriate output and added to the module through a simple hook:
      // site/ready.php wire()->addHookAfter('CachePlaceholders::getTokens', function (HookEvent $e) { $tokens = $e->return; $tokens['greeting'] = [ 'callback' => function (array $tokenData) { return ucfirst(wire('user')->name); } ]; $e->return = $tokens; }); Tokens can also include parameters that are parsed and passed to the callback function. There are more fully annotated examples and step-by-step instructions in the README on Github!
      Features
      A simple and fast token parser that calls the appropriate callback and runs automatically. Tokens may include multiple named or positional parameters, as well as multi-value parameters. A manual mode that allows you to replace tokens in custom pieces of cached content (useful if you're using the $cache API). Some built-in tokens for common use-cases: CSRF-Tokens, replacing values from superglobals and producing random hexadecimal strings. The token format is completely customizable, all delimiters can be changed to avoid collisions with existing tag parsers or template languages. Links
      Github Repository & documentation Module directory If you are interested in learning more, the README is very extensive, with more usage examples, code samples and usage instructions!
    • By MoritzLost
      This module allows you to integrate hCaptcha bot / spam protection into ProcessWire forms. hCaptcha is a great alternative to Google ReCaptcha, especially if you are in the EU and need to comply with privacy regulations.

      The development of this module is sponsored by schwarzdesign.
      The module is built as an Inputfield, allowing you to integrate it into any ProcessWire form you want. It's primarily intended for frontend forms and can be added to Form Builder forms for automatic spam protection. There's a step-by-step guide for adding the hCaptcha widget to Form Builder forms in the README, as well as instructions for API usage.
      Features
      Inputfield that displays an hCaptcha widget in ProcessWire forms. The inputfield verifies the hCaptcha response upon submission, and adds a field error if it is invalid. All hCaptcha configuration options for the widget (theme, display size etc) can be changed through the inputfield configuration, as well as programmatically. hCaptcha script options can be changed through a hook. Error messages can be translated through ProcessWire's site translations. hCaptcha secret keys and site-keys can be set for each individual inputfield or globally in your config.php. Error codes and failures are logged to help you find configuration errors. Please check the README for setup instructions.
      Links
      Github Repository and documentation InputfieldHCaptcha in the module directory (pending approval) Screenshots (configuration)

      Screenshots (hCaptcha widget)

       
       

       
×
×
  • Create New...