Labels on top of fields

From pmusers
Jump to: navigation, search

JavaScript can be used to place labels on top of fields in a DynaForm. The code changes the classes in fields, so that the labels always appear on top of fields, instead of to their left.


DynaForm: Labels on top.json (right click and select Save link as)
Author: Amos Batto (amos@processmaker.com)
Version: 1.0 (2018-07-19)
Tested in: ProcessMaker 3.2.1 Community in Debian 8.4 with PHP 5.6.20 and Firefox 51


Create a DynaForm which contains input fields:

formInDesigner.png

Add the following JavaScript to the DynaForm to move the labels above their fields:

function labelOnTop(fieldId, colWidth) {
  var aFieldTypes = ['text', 'textarea', 'checkbox', 'checkgroup', 'dropdown', 'suggest', 
                   'radio', 'datetime', 'file', 'multipleFile', 'image', 'link'];
  var oField = $("#"+fieldId);
  var type = '';
  
  if (typeof oField.getInfo === 'function' && oField.getInfo() != null) {
    type = oField.getInfo().type;
  }
  
  if (aFieldTypes.indexOf(type) == -1) {
    return;
  }
  
  var oDivs = oField.children("div");
  if (type == 'multipleFile') {
    oDivs = oDivs.children("div");
  }
  
  oDivs.eq(0).removeClass();
  oDivs.eq(0).addClass("col-sm-"+colWidth+" col-md-"+colWidth+" col-lg-"+colWidth);
  oDivs.eq(0).find("label").css("float", "left");
    
  //remove classes that start with "col-":
  var aClasses = oDivs.eq(1).attr('class').split(/\s+/);
  $.each(aClasses, function(index, className) {
    if (className.match(/^col-/)) {
      oDivs.eq(1).removeClass(className);
    }
  });
    
  oDivs.eq(1).addClass("col-sm-"+colWidth+" col-md-"+colWidth+" col-lg-"+colWidth);
  oDivs.eq(1).css("float", "left");
  oDivs.eq(1).css("padding-left", "0");
}

function processFormFields(aRows) {
  for (i in aRows) { 
    for (ii in aRows[i]) {
      if (aRows[i][ii].type == 'form')
        processFormFields(aRows[i][ii].items);
      else 
      	labelOnTop( aRows[i][ii].id, "12" );
    }
  }
}  

var aItems = getFormById( $("form").prop("id") ).model.attributes.items;
processFormFields(aItems);

This code gets the list of fields in the form's .model.attributes.items which is an array of fields inside an array of rows. For each field, it calls the labelOnTop() function, which changes the classes in the field's label from "col-sm-2 col-md-2 col-lg-2" to "col-sm-12 col-md-12 col-lg-12" so it will take up all available space. The input field also has its classes set to "col-sm-12 col-md-12 col-lg-12".

When the DynaForm is displayed, all the labels will be on top:

formWithLabelsOnTop.png