fetch all fields in a g_form

georgechen
Kilo Guru

Hi folks again,

Is there a way to loop through available fields in a g_form, instead of hard-coding each field name.     g_form has a method getControl which expects a field name, the control can be fetched, but you have to specify the fieldname, I wonder if the fields can be dynamically lopped through the g_form fields (or variable something like this)

Any advice would be appreciated.

Thanks,

GlideForm (g form) - ServiceNow Wiki

10.2 getControl

HTMLElement getControl(fieldName)

Returns the HTML element for the specified field. Compound fields may contain several HTML elements.
Generally not necessary as there are built-in methods that use the fields on the form.
Parameters:
fieldName - specifies the name of the field.
Returns:
HTMLElement - the specified HTML element(s).
Note: If the field is of type reference and the control is a choice list, getControl() may not return control as expected. In this case, use sys_select.<table name>.<field name>.
12 REPLIES 12

Very nice solution thanks

petercawdron
Kilo Guru

You can do this with a little jQuery (if your client script isn't isolated)

	var allFields = this.jQuery('[id*="element."]');
	var thisTable = allFields[0].id.match(/element\.([\S\s]+)\./)[1];

	this.jQuery.each(allFields,function(field){
		var fieldName = allFields[field].id.replace('element.'+thisTable+'.','');
		console.log(fieldName + ' = ' + g_form.getValue(fieldName));
	});
	




shallom
Tera Contributor

For Native UI

 

var elements = g_form.elements
    var params = [];

    // Collect all field values
    elements.forEach(function(field) {
        var fieldName = field.fieldName;
        if (fieldName) {
            var value = g_form.getValue(fieldName);
            if (value) {
                params.push(fieldName + '%3d' + value);
            }
        }
    });

 

 

For Workspace

 

var elements = g_form.getFieldNames()
        var params = [];

        // Collect all field values
        elements.forEach(function(field) {
            var value = g_form.getValue(field);
            if (value) {
                params.push(field + '%3d' + value);
            }
        });