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.

  • Have you tried this.listFields.getEnumerator()? – Sergei Sergeev Jan 5 '12 at 13:01
  • It's not required to add this, but yes I tried. – Bart Jan 5 '12 at 13:13
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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