Created
August 30, 2017 14:44
-
-
Save harmenjanssen/6895778f4b85910ba56452abc98fdc3e to your computer and use it in GitHub Desktop.
Javascript fallback for broken default values in OctoberCMS' Repeater fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fields: | |
extra_information: | |
type: repeater | |
form: | |
fields: | |
foobar: | |
label: Foobar | |
type: text | |
# This won't work: | |
default: lorem ipsum | |
attributes: | |
# Which is why we use this attribute: | |
data-default-value: lorem ipsum |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Plugin extends PluginBase | |
{ | |
public function boot() | |
{ | |
Event::listen('backend.page.beforeDisplay', function($controller, $action, $params) { | |
$controller->addJs('/plugins/grrr/flexiblepages/assets/javascript/repeater.js'); | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$(function() { | |
if (!$.fn.fieldRepeater) { | |
return; | |
} | |
const fixDefaultValues = $item => { | |
const $inputs = $item.find("[data-default-value]"); | |
$inputs.each(function() { | |
const $input = $(this); | |
if (!$input.val()) { | |
$input.val($input.data("default-value")); | |
} | |
}); | |
}; | |
// Listen for newly added list-items | |
const observer = new MutationObserver(mutations => { | |
mutations | |
.filter(m => m.type === "childList") | |
.map(m => | |
Array.from(m.addedNodes).filter(n => n.nodeType === 1).forEach(x => | |
fixDefaultValues($(x)); | |
)); | |
}); | |
const config = { attributes: false, childList: true, characterData: false }; | |
observer.observe($(".field-repeater-items").get(0), config); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment