Key / Value fields provide an easy way to add non-structured information to your content.
This information is handled using key/value pairs that get stored in the content as a map than can then easily be displayed on a widget.
This field is helpful in creating a table of features for content.
Go to the Structure Manager and click on Add New Field.
Select Key/Value from the field types menu.
Content Type fields can be re-ordered by dragging and dropping them in the desired order.
Once added, while editing content you can add key/value pairs to each piece of content.
These can also be deleted and / or reordered.
To display the key/value fields, access the field by the variable name and then loop through the map returned.
#foreach($mapEntry in $content.getKeyValueProperty('mykeyvaluefield').entrySet())
$mapEntry.key : $mapEntry.value
#end
Depending on where your code is used, you may need to first pull the entire contentlet via find. So the code would look like this:
#set($content = $dotcontent.find("$CONTENT_INODE"))
#foreach($mapEntry in $content.mykeyvaluefield.map.entrySet())
$mapEntry.key : $mapEntry.value
#end
Whitelisting
As of version 22.05
, dotCMS supports creating a whitelist of valid keys for a given Key/Value field, as well as pre-defined values for said keys.
While configuring the Key/Value field in the Content Type editor, simply set a key of whiteList
and then its definition, using JSON syntax, in the corresponding value field.
Example
Let's say you want create a whitelist containing the following:
- One predefined key with two possible predefined values
- Two other predefined keys permitting arbitrary value entry
You might create this whitelist as follows:
Key | Value |
---|---|
whiteList | { "key1":["val1", "val2"], "key2":[], "key3":[] } |
Users inputting data into this Key/Value field will find a dropdown menu in the Key position contining key1
, key2
, and key3
. Moreover, while key1
is selected, the Value field will change from a text input to a dropdown containing val1
and val2
.