Wednesday 12 November 2014

Populate dropdown in CQ5 dialog using Servlet

Dropdowns in CQ5 are easy to create and use, all that needs to be done is create a node with name options and primaryType as cq:widgetcollections and sub-nodes with options.

But problems comes in when the dropdowns with dynamic data or options is to be created. So, in this blog you will see how to address the problem of populating dropdown dynamically.

Firstly, create a source from which data is to be fetched in our case we have registered a Servlet in OSGI at path "/bin/codebrains.json" which returns a JSON object as :

{"root":[{"text":"CodeBrains_Text_0","value":"CodeBrains_Value_0"},{"text":"CodeBrains_Text_1","value":"CodeBrains_Value_1"},{"text":"CodeBrains_Text_2","value":"CodeBrains_Value_2"},{"text":"CodeBrains_Text_3","value":"CodeBrains_Value_3"},{"text":"CodeBrains_Text_4","value":"CodeBrains_Value_4"}]}

Once your servlet is ready and it gives response in the desired format, now browse to Dropdown widget node and add properties that are shown below :









Add following properties on the node :
  • xtype (Required) : selection
  • type : select
  • options (Optional but required if data is to be fetched from servlet) : <path-of-the-servlet> [Value of this property should be path of servlet which will serve the JSON data to be populated in the combo-box]. In our case its value should be "/bin/codebrains.json" as it the path at which servlet is registered in OSGI. 
  • optionsRoot  (Optional):  [Name of the property that contains options array. Use "." or dot-annotation to get till the property that contains options array. ] In our case its value should be "root" as root property of JSON object contains the Array.
  • optionsTextField (Optional): [Name of the field for the options text. This property is used if options object does not contains Text property which is read by default.
  • optionsValueField (Optional) : [Name of the field for the options value. This property is used if options object does not contains Value property which is read by default. ] (Optional)
  • allowBlank  (Optional) : [This property should have boolean value and is used to make any field mandatory. If set false that widget becomes mandatory cannot be set blank. ]





























Here is the Link to Github repository of Codebrains to refer the code : 
https://github.com/ankit-gubrani/Codebrains

No comments:

Post a Comment