How to Submit a React.Js based web form using REST API in React JS and Store submission data in Drupal 8 backend

  0 comments

In previous blog we had covered on how to use a REST API in Drupal with React APP using React Library.

This blog is about sending React webform data and storing the submitted record in Drupal8 as a webform entity.

First we need to write component for web form. Which will be as follows
 

class QuoteForm extends React.Component {
  render() {
    return (
       div className="quote_form" id="quote_form" >
        <h2 className="block-title">Get Free Quote</h2>
        <form className="form-inline my-2 my-lg-0" onSubmit={this.handleSubmit}>
          <input id="edit-name" className="form-control" type="text" placeholder="Name" aria-label="Name" name="name" />
          <input id="edit-email" className="form-control" type="email" placeholder="Email" aria-label="Email" name="email"  />
          <textarea  className="form-textarea form-control resize-vertical" id="edit-comment" name="comment" rows="5" cols="60" placeholder="Comment"></textarea>

          <button className="webform-button--submit button button--primary js-form-submit form-submit btn-primary btn" type="submit">Submit</button>
        </form>
      </div>
    )
  }
}


In above code you will find that I am using a submit function "handleSubmit". So, we will need to write that function in same component class. Which will be as follows?
 

  handleSubmit (event) {	
	event.preventDefault();
  }


Now we need a API which will submit the data in Drupal backend.
 


To make the API for form submission follow these steps.
 

1. Download and install Webform REST

2. Now go onto this link http://example.com/admin/config/services/rest and enable "Webform Submit" ret API.


Step1 :
 


Click on enable button in front of "Webform Submit"
 

webform_rest

Step2 :


Select same option as screenshot.
 

webform_rest

Now you are able to use an API to submission of webform. So, this will be information of API

 

Details of Webform Submit API

 

End Point:/webform_rest/submit
Method:POST
Content-Type:application/json
Parameter:
	    'webform_id':'get_free_quote',
            'entity_type' : null,
            'entity_id' : null,
            'in_draft' : false,
            'uri' : ['/webform/webform_id/api'],
	    'name' : 'John Smith', 
	    'email' : 'email@email.com',
            'comment' : 'Comment'


Note: If there will be more element than name, email and comment then you can add like we have used for name, email and comment.
 

In above screenshot we had selected “Authentication providers” as cookie. So, to use this API We have to pass "X-CSRF-Token" along with API's header.
 

So, before calling this API we will call an another API which is default provided by drupal
 

Details of Token API
 

End Point: /session/token
Method:GET
Content-Type:application/json


So, code will be as follows:
 

 handleSubmit (event) {	
	event.preventDefault();
	const email = event.target.email.value;
	const comment = event.target.comment.value;
	const name = event.target.name.value;
    
	axios.get('http://example.com/session/token').then(result => {
		console.log(result);
      if (200 === result.status) {
		const csrfToken = result.data;
        fetch('http://example.com/webform_rest/submit?_format=json', {
		  method: 'POST',
		  headers: {
		    'Content-Type': 'application/json',
		    'X-CSRF-Token': csrfToken
		  },
		  body: JSON.stringify({
			'webform_id':'webform_id',
            'entity_type' : null,
            'entity_id' : null,
            'in_draft' : false,
            'uri' : ['/webform/webform_id/api'],
			'name' : name, 
			'email' : email,
			'comment' : comment,
		  }),
		})
        .then(response => response.json())
		.then(
		  (data) => {
            //on success you do whatever you will want
            console.log('success', data);
		  },
          (error) => {
            console.log('error', error);
		  }
		);
      }
    });

  }


View the full code below :-
 

<div id="quote_form" />

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>

<script type="text/jsx">
class QuoteForm extends React.Component {
 handleSubmit (event) {	
	event.preventDefault();
	const email = event.target.email.value;
	const comment = event.target.comment.value;
	const name = event.target.name.value;
    
	axios.get('http://example.com/session/token').then(result => {
		console.log(result);
      if (200 === result.status) {
		const csrfToken = result.data;
        fetch('http://example.com/webform_rest/submit?_format=json', {
		  method: 'POST',
		  headers: {
		    'Content-Type': 'application/json',
		    'X-CSRF-Token': csrfToken
		  },
		  body: JSON.stringify({
			'webform_id':'webform_id',
            'entity_type' : null,
            'entity_id' : null,
            'in_draft' : false,
            'uri' : ['/webform/webform_id/api'],
			'name' : name, 
			'email' : email,
			'comment' : comment,
		  }),
		})
        .then(response => response.json())
		.then(
		  (data) => {
            //on success you do whatever you will want
            console.log('success', data);
		  },
          (error) => {
            console.log('error', error);
		  }
		);
      }
    });

  }
  render() {
    return (
       div className="quote_form" id="quote_form" >
        <h2 className="block-title">Get Free Quote</h2>
        <form className="form-inline my-2 my-lg-0" onSubmit={this.handleSubmit}>
          <input id="edit-name" className="form-control" type="text" placeholder="Name" aria-label="Name" name="name" />
          <input id="edit-email" className="form-control" type="email" placeholder="Email" aria-label="Email" name="email"  />
          <textarea  className="form-textarea form-control resize-vertical" id="edit-comment" name="comment" rows="5" cols="60" placeholder="Comment"></textarea>

          <button className="webform-button--submit button button--primary js-form-submit form-submit btn-primary btn" type="submit">Submit</button>
        </form>
      </div>
    )
  }
}
ReactDOM.render(
  React.createElement(QuoteForm, null, null),
  document.getElementById('quote_form')
);
</script>

Add new comment