Workaround for maximum 25 data types

  • Created: May 11, 2017
  • Author: Nollymar Longa
  • Title: Java Developer
  • Company: dotCMS

Description

The idea is to create additional fields using a custom field and save their values as a JSON object into the custom field. This idea was suggested by a client in a Bootcamp session. I implemented it using Velocity. The Velocity code included creates three input fields using a custom field, then it saves the input fields values as a json object into the custom field. As a simple test, you can add a custom field to the News content type as defined here (using the attached velocity code): https://dotcms.com/docs/latest/custom-field

Code

## This example uses a custom field that is called "test" and has the variable name "test"
 
## first we get the content (we have access to all our 
## velocity tools, including any custom ones that have been written
 
 
#set($content = $dotcontent.find($request.getParameter("inode")))
 
 
## then we write some ugly js to get and set the values on the edit content form - 
## the dom.id of the hidden field that stores the value is just the velocity variable name
## so watch out for js variable scope issues
 
<script>
    var jsonObj = { 
      "extendedField1"  :  "First field", 
      "extendedField2"  :  "Second field", 
      "extendedField3"  :  "Third field" 
    }
    
    if (document.getElementById('test').value != ''){
        jsonObj = JSON.parse(document.getElementById('test').value);
    }
	function myButtonClick(){
		document.getElementById('test').value=JSON.stringify(jsonObj);
		document.getElementById('customValue').innerHTML=JSON.stringify(jsonObj);
	}
</script>
 
 
 
## then we write out our user controls, displaying the value stored in the content object by default
## with a button (dojo styled) that calls our js

#foreach($i in [1..3])
    <input type="text" id="extendedField$i" /></br>    
    <script type="text/javascript"> 
        document.getElementById("extendedField$i").value = jsonObj["extendedField$i"];
        
        document.getElementById("extendedField$i").onblur = function() {
          jsonObj["extendedField$i"] = this.value;
        };
    </script>
#end

Custom Value: <span id="customValue">$!content.test</span> </br>  
<button dojoType="dijit.form.Button" id="myButton" onclick="myButtonClick">Click me!</button>