4

Is it possible to retrieve all fields of a list (or default view) through the JavaScript Client Object Model and filter the fields on type (e.g. I only want the Choice fields).

    var clientContext = new SP.ClientContext.get_current();
    var web = clientContext.get_web();
    var list = web.get_lists().getByTitle(listName);
    var defaultview = list.getView('00000000-0000-0000-0000-000000000000');
    this.listFields = defaultview.get_viewFields();
    clientContext.executeQueryAsync(Function.createDelegate(this, 
        this.onListFieldsQuerySucceeded), Function.createDelegate(this, 
        this.onListFieldsQueryFailed));

    function onListFieldsQuerySucceeded() {
        var fieldEnumerator = listFields.getEnumerator();
        while (fieldEnumerator.moveNext()) {
            var oField = fieldEnumerator.get_current();
            ...
        }
    }

Right now I'm getting following exception on listFields.getEnumerator()

Microsoft JScript runtime error: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.

Same problem if I get the fields on the list directly.

2
  • Have you tried this.listFields.getEnumerator()? Commented Jan 5, 2012 at 13:01
  • It's not required to add this, but yes I tried.
    – Bart
    Commented Jan 5, 2012 at 13:13

1 Answer 1

10

You missed this line: clientContext.load(this.listFields); right after this.listFields = defaultview.get_viewFields(); , because your code not actually loads fields.

Complete code with field type checking looks like this one:

var clientContext = new SP.ClientContext.get_current();
    var web = clientContext.get_web();
    var list = web.get_lists().getByTitle(listName);
    this.listFields = list.get_fields();
    clientContext.load(this.listFields);
    clientContext.executeQueryAsync(Function.createDelegate(this, 
        this.onListFieldsQuerySucceeded), Function.createDelegate(this, 
        this.onListFieldsQueryFailed));

    function onListFieldsQuerySucceeded() {
        var fieldEnumerator = listFields.getEnumerator();
        while (fieldEnumerator.moveNext()) {
            var oField = fieldEnumerator.get_current();
            var fType = oField.get_fieldTypeKind();
            if(fType === SP.FieldType.choice) {
               .....
            }
        }
    }  

To verify field type you can use get_fieldTypeKind() or typeAsString() methods.

2
  • 1
    and what about getting a specific listItem?
    – fallout
    Commented Feb 16, 2012 at 9:05
  • get_fieldTypeKind is not a function. Everthing goes good until this. Why please ?
    – ameliapond
    Commented Apr 7, 2016 at 13:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.