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.
[code lang=”js”]
const spOpts: ISPHttpClientOptions = {
body: "{‘Title’: ‘Group’, ‘FieldTypeKind’:2,’Required’:false, ‘EnforceUniqueValues’: ‘false’,’StaticName’: ‘Group’}"
};
[/code]
Then we create the REST call and receive the response.
[code lang=”js”]
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);
});
});
[/code]
However, we get an error when trying to create a choice column using the following body:
[code lang=”js”]
body: "’Title’: ‘Behaviour’, ‘FieldTypeKind’:6,’Required’:true, ‘EnforceUniqueValues’: ‘false’, ‘StaticName’: ‘Behaviour’, Choices: [‘Choice1’, ‘Choice2’, ‘Choice3’] }"
[/code]
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:
[code lang=”js”]
body: {‘@odata.type’: ‘SP.FieldChoice’,’Title’: ‘Behaviour’, ‘FieldTypeKind’:6,’Required’:true, ‘EnforceUniqueValues’: ‘false’, ‘StaticName’: ‘Behaviour’, Choices: [‘Choice1’, ‘Choice2’, ‘Choice3’] }
[/code]
Hope someone finds this useful and saves you a lot of time!