Creating a choice field in SPFx

Published 25, Oct 2017

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!

Ajax Blog Choice Field Extensions Gruntjs Gulp Html And Javascript Javascript Js Display Templates Nodejs Odata Type Rest Sass Scss Sharepoint 2016 Sharepoint Development Sharepoint News Sharepoint Online Sharepoint Online Permissions Sp Field Sp Fieldchoice Spfx Sphttpclient Sphttpclientresponse Tony Phillips Typescript Web Parts Workbench Yeoman

Find out more about learning solutions tailored to your school or trust

A global personalised menu for easy clear navigation into Teams and sites, even for beginners. Central Resource areas help teachers reuse department resources from within each class and assignment. A global personalised menu for easy clear navigation into Teams and sites, even for beginners.

Discover more from Cloud Design Box

Subscribe now to keep reading and get access to the full archive.

Continue reading