1

I am building lists and adding fields via the following. I am wondering if I can add a calculated field and how you set the formula in this (or another method):

function onCreateRootCause() {
    var clientContext = new SP.ClientContext.get_current();
    var oWebsite = clientContext.get_web();   
    var listCreationInfo = new SP.ListCreationInformation();
    listCreationInfo.set_title('LedgerLikeList');
    listCreationInfo.set_templateType(100);
    this.oList = oWebsite.get_lists().add(listCreationInfo);
    clientContext.load(oList);
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreatedExampleList), Function.createDelegate(this, this.onQueryFailed));
}


function onCreatedExampleList() {
    var clientContext = new SP.ClientContext.get_current();
    var oList = clientContext.get_web().get_lists().getByTitle('Description');
    this.fieldValue = oList.get_fields().addFieldAsXml('<Field DisplayName=\TransDescription\' Type=\Text\' />', true, SP.AddFieldOptions.defaultValue);
    var fieldVal= clientContext.castTo(fieldValue,SP.FieldNumber);
    fieldVal.set_defaultValue('[Example Ledger Transaction Description]');
    fieldVal.update();
    clientContext.load(fieldValue);

    this.fieldValue = oList.get_fields().addFieldAsXml('<Field DisplayName=\'Income\' Type=\'Number\' />', true, SP.AddFieldOptions.defaultValue);  
    var fieldVal = clientContext.castTo(fieldValue,SP.FieldNumber);
    fieldVal.set_defaultValue(0.0);
    fieldVal.update();
    clientContext.load(fieldValue);

    this.fieldValue= oList.get_fields().addFieldAsXml('<Field DisplayName=\'Expenditures\' Type=\'Text\' />', true, SP.AddFieldOptions.defaultValue);   
    var fieldVal = clientContext.castTo(fieldValue,SP.FieldNumber);
    fieldVal.set_defaultValue(0.0);
    fieldVal.update();
    clientContext.load(fieldValue);

    // is there a way I can via this method, or another add a balance column that calculates as simple as Income - Expenditure = Balance (I know this is not complete, this list is just for example).


    clientContext.executeQueryAsync(Function.createDelegate(this, this.onCreatedFieldsCallback), Function.createDelegate(this, this.onQueryFailed));
}
2

Following is an example of Calculated field schema:

"<Field Type=\"Calculated\" " +
"DisplayName=\"New_Field_Display_Name\" ResultType=\"Currency\" " +
"ReadOnly=\"TRUE\" Name=\"New_Field_Internal_Name\">" +
"<Formula>=Currency_Field_Name*100</Formula>" +
"<FieldRefs><FieldRef Name=\"Currency_Field_Name\" />" + 
"</FieldRefs></Field>";

Code taken from below msdn link:

http://msdn.microsoft.com/en-us/library/office/ms457586.aspx

Even though the example there is for server object model, the code should work in client object model as well.

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.