Creating a choice field in SPFx

When using the SharePoint Framework (SPFx), we can use spHttpClient to manage our REST calls. Creating new fields (columns) in lists is like using jQuery ajax methods, first we feed in the body of our call in JSON format.

const spOpts: ISPHttpClientOptions = {
      body: "{'Title': 'Group', 'FieldTypeKind':2,'Required':false, 'EnforceUniqueValues': 'false','StaticName': 'Group'}"
    };

Then we create the REST call and receive the response.

this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/GetByTitle('List Name')/Fields`, SPHttpClient.configurations.v1, spOpts)
      .then((response: SPHttpClientResponse) => {
        console.log(`Status code: ${response.status}`);
        console.log(`Status text: ${response.statusText}`);
        response.json().then((responseJSON: JSON) => {
          console.log(responseJSON);
        });
      });

However, we get an error when trying to create a choice column using the following body:


      body: "'Title': 'Behaviour', 'FieldTypeKind':6,'Required':true, 'EnforceUniqueValues': 'false', 'StaticName': 'Behaviour', Choices: ['Choice1', 'Choice2', 'Choice3'] }"

Error: “The property ‘Choices’ does not exist on type ‘SP.Field’. Make sure to only use property names that are defined by the type.”

To resolve this issue, we need to add the data type to the request, we structure the JSON in a different way (compared to jQuery ajax calls). This is the JSON required to create a choice column:

body: {'@odata.type': 'SP.FieldChoice','Title': 'Behaviour', 'FieldTypeKind':6,'Required':true, 'EnforceUniqueValues': 'false', 'StaticName': 'Behaviour', Choices: ['Choice1', 'Choice2', 'Choice3'] }

Hope someone finds this useful and saves you a lot of time!

Leave a Reply

Your email address will not be published. Required fields are marked *