How to limit the number of elements in multifield in CQ5?

Gleb picture Gleb · Apr 4, 2012 · Viewed 10.5k times · Source

I develop the site with Day CQ5 and was faced witha problem. I'm creating a component, and the dialogue for it. I use in the dialog for the component element "multifield", which contains several elements "pathfield." How can I set a specific number of elements "pathfield" and remove buttons "+" and "-"?

Answer

anotherdave picture anotherdave · Jun 24, 2012

I've come across this exact problem this week :)

It seems that by default you can't limit the number of items the editor can enter. To resolve the issue, I created an overlay of the Multifield.js placed at

/apps/cq/ui/widgets/source/widgets/form/MultiField.js

I've added a check for a 'limit' property set on the fieldConfig node under the multifield. If present & not zero, it will use this as the max number of fields a user can add.

Don't want to get into copyright issues by posting the full overlay, but the changes I made where as follows:

In the constructor (line #53), add in a check to get the value of limit from the fieldConfig node:

if (!config.fieldConfig.limit) {
        config.fieldConfig.limit = "0";
}

In the handler for the "+" button (line #71) change the function to the following:

if(config.fieldConfig.limit == 0 || list.items.getCount() <= config.fieldConfig.limit) {
    list.addItem();
} else {
    CQ.Ext.Msg.show({
        title: 'Limit reached',
        msg: 'You are only allowed to add ' + config.fieldConfig.limit + 
             ' items to this module',
        icon:CQ.Ext.MessageBox.WARNING,
        buttons: CQ.Ext.Msg.OK
    });
}

Rather than removing the buttons, I've just created a pop-up to inform the editor that 'N is the max number of fields allowed'.

Simple change, but does the job! Hope this is of use.