0

I am programatically adding new fields to a list through Javascript. My code looks like:

var addColumnToList = function(title, fieldName, type) {
    var context = SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(title);
    this.field = list.get_fields().addFieldAsXml("<Field DisplayName='" + fieldName + "' Type='" + type + "' />", true, SP.AddFieldOptions.defaultValue);

    var fieldNumber = context.castTo(field, SP.FieldNumber);
    fieldNumber.update();

    context.load(field);
    context.executeQueryAsync(
        Function.createDelegate(this, this.onColAddSuccess),
        Function.createDelegate(this, this.onColAddFail)
    );
};

var onColAddSuccess = function() {
    console.log(field.get_title() + " successfully added to list!\n");
};

var onColAddFail = function(sender, args) {
    console.log("Add column request failed! " + args.get_message());
};

The default value of every item defaults to "null". My question is: Is there any way to specify a default value for all items when adding a new field to a SP list?

1 Answer 1

1

Yes, you must use Default element (child of Field element) in Field XML.

UPDATE:

Example based on your code:

var addColumnToList = function(title, fieldName, type, defaultValue) {
    var context = SP.ClientContext.get_current();
    var list = context.get_web().get_lists().getByTitle(title);
    this.field = list.get_fields().addFieldAsXml(
        "<Field DisplayName='" + fieldName + "' Type='" + type + "'>" +
            "<Default>" + defaultValue + "</Default>" +
        "</Field>",
        true,
        SP.AddFieldOptions.defaultValue
    );

    context.load(field);
    context.executeQueryAsync(
        Function.createDelegate(this, this.onColAddSuccess),
        Function.createDelegate(this, this.onColAddFail)
    );
};
3
  • Could you give an example please? I tried: <Field DisplayName="name" Type="Boolean"><Default>true</Default></Field> - no dice. Thank you.
    – ICW
    Commented Feb 22, 2017 at 19:41
  • 1
    In Boolean field you should use 0/1 instead of false/true. Commented Feb 22, 2017 at 22:43
  • Hawrylak Thank you for the example, but that still did not work for me sadly.
    – ICW
    Commented Feb 27, 2017 at 14:21

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.