Goal
Add composite multifield items dynamically based on coral select change. In sample below, the value of coral select "./count" defines the count of multi field items "./products"
Demo | Package Install | Github
Solution
1) Login to CRXDE Lite, create folder (nt:folder) /apps/eaem-touchui-select-change-dynamic-multifield
2) Create clientlib (type cq:ClientLibraryFolder) /apps/eaem-touchui-select-change-dynamic-multifield/clientlib and set property categories of String[] type to cq.authoring.dialog.all and dependencies String[] to lodash
3) Create file ( type nt:file ) /apps/eaem-touchui-select-change-dynamic-multifield/clientlib/js.txt, add the following
select-change-dynamic-multifield.js
4) Create file (type nt:file) /apps/eaem-touchui-select-change-dynamic-multifield/clientlib/select-change-dynamic-multifield.js, add the following code
(function ($, $document, gAuthor) {
var COUNT_SELECT = "./count",
PRODUCTS_MF = "./products";
$document.on("dialog-ready", addSelectListener);
function addSelectListener(){
var $countSelect = $("coral-select[name='" + COUNT_SELECT + "']");
if(_.isEmpty($countSelect)){
return;
}
var countSelect = $countSelect[0];
countSelect.on("change", adjustMultifieldItems);
}
function adjustMultifieldItems(event){
var countSelect = event.target,
$productsMF = $("coral-multifield[data-granite-coral-multifield-name='" + PRODUCTS_MF + "']");
if(_.isEmpty($productsMF)){
return;
}
var maxCount = parseInt(countSelect.value),
productsMF = $productsMF[0],
mfItems = productsMF.items.getAll();
if(mfItems.length <= maxCount){
for(var c = mfItems.length; c < maxCount; c++){
productsMF.items.add();
}
}else{
for(var c = (mfItems.length - 1) ; c >= maxCount; c--){
productsMF.items.remove(mfItems[c]);
}
}
}
}(jQuery, jQuery(document), Granite.author));