0

I am trying to add document set content type from site collection to a library, but I am failing to do that.

Please help me to solve this issue. I am trying to use React and SPFx for SharePoint Online Modern site.

AddContentTypeToList=()=>
  {
    let ctEndpointUrl = `${this.props.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.props.list}')/ContentTypes/AddAvailableContentType`;
    let listUrl = `${this.props.context.pageContext.web.absoluteUrl}/${this.props.list}`;
    let options : ISPHttpClientOptions= { 
      method: "POST", 
      
      body: JSON.stringify(
        { 'Title' : "Test New CT" , 'Path' : listUrl }),
        headers: {
          'Accept': 'application/json;odata=verbose',
          'Content-Type': 'application/json;odata=verbose', 
          'odata-version': '',
           type: "POST",
           data: JSON.stringify({  
            "contentTypeId": "0x0120D52000B6B95AFB1E9F5444905DA0AFE9C8F2CF0014BD370B726AB045A140BBF6DA440933"
            }) 
        }
      };
    
      this.props.context.spHttpClient.post(listUrl,
      SPHttpClient.configurations.v1, options).then((d:SPHttpClientResponse) => {
        d.json().then(res => {
          // success
          alert("CT Created");
          console.log(res);
        })                
      }).catch(e => {
        // error
        console.log(e);
      });
}
11
  • Please add more details to your question. maybe the current code you are using/trying to do the same. – Ganesh Sanap Aug 10 '20 at 4:49
  • Thanks for reply bro, updated the code. – San Aug 10 '20 at 5:21
  • Are you getting any error in browser console while running this code? – Ganesh Sanap Aug 10 '20 at 5:34
  • yes bro, Error making HttpClient request in queryable [404] – San Aug 10 '20 at 5:38
  • Try to check the complete error message in console or network tab. You must be passing wrong library name or field names or content type ID. – Ganesh Sanap Aug 10 '20 at 5:44
0

Try my test code,this works well in my environment.Remember to change the contentTypeId.

update() {

    const requestHeaders: Headers = new Headers();
    requestHeaders.append('Content-type', 'application/json;odata=verbose');
    requestHeaders.append('Accept', 'application/json;odata=verbose');


    const body: ISPHttpClientOptions = {
      body: JSON.stringify({
        'contentTypeId': "0x0120D520"

      }),
      headers: requestHeaders
    };
    this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists/getByTitle('Doc')/contenttypes/AddAvailableContentType`,
      SPHttpClient.configurations.v1, body)
      .then((response: SPHttpClientResponse) => {
        response.json().then((responseJSON: any) => {
          console.log(responseJSON);
        });
      });
  }
4
  • Thanks for the reply, when I tried the above code, I am facing issue like this: @Amos_MSFT sp-webpart-workbench-assembly_en-us_d342d4b5e6f80229d85d049dc5a8e181.js:1 Uncaught TypeError: Cannot read property 'post' of undefined – San Aug 10 '20 at 6:39
  • You could try to console.log(this.props.context.pageContext.web.absoluteUrl) to check if the url is right. – Amos Aug 10 '20 at 7:03
  • mysan.sp.com/sites/MySite/_api/web/lists/… I am directly giving this in url, but still I am facing same issue – San Aug 10 '20 at 7:13
  • If you configure custom context,change this.context.spHttpClient.post to this.props.context.spHttpClient.post – Amos Aug 10 '20 at 7:50
0

I think you are missing the webpart context in your react component. First of all you need to pass the webpart context from your main webpart file to react component like below:

public render(): void {
   const element: React.ReactElement<any > = React.createElement(
     HelloWorld,
     {
        description: this.properties.description,
        context: this.context
     }
   );

   ReactDom.render(element, this.domElement);
}

Then you can use it in your react component file like:

let webUrl = this.props.context.pageContext.web.absoluteUrl

Reference: How to retrieve pageContext in SPFx?

Once you get the SPFx context and spHttpClient correctly then you can add the content type to your library. For that follow the code given in above answer by Amos or below article:

SharePoint Online: Add Content Type to List using Rest API - Make sure to replace the name of library and content type ID.

0

See the below code, Below code is the

private AddContentTypeToList = () => {
  let ctEndpointUrl = `${this.props.context.pageContext.web.absoluteUrl}/_api/web/lists/getbytitle('${this.props.list}')/ContentTypes/AddAvailableContentType`;
  let options: ISPHttpClientOptions = {
     headers: {
        'Accept': 'application/json;odata=nometadata',
        'Content-type': 'application/json;odata=nometadata'
     },
     body: JSON.stringify({
        "contentTypeId": "0x0120D520"
     })
  };

  this.props.context.spHttpClient.post(ctEndpointUrl,
     SPHttpClient.configurations.v1, options)
     .then((d: SPHttpClientResponse) => {
        d.json().then(res => {
           alert("CT Created");
           console.log(res);
        });
     }).catch(e => {
        // error
        console.log(e);
     });

}

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.