Drupal:如何使用 AJAX POST 从 REST 服务提交 webfrom
I am having web form module in drupal. I want to submit a form into webform from external app with REST service using the AJAX POST method. I can able to retrieve the web form (node/1) using ajax. On submitting it should not create as new node, instead it will get add into web form.
Thanks in advance for any help.....
解决方案To be able to retrieve data from and send data to Webform module with an external application I suggest you to use Webform Service module of Drupal that makes REST API available for your surveys.
Once you've installed and configured the modules and its dependencies (if any) you'll be able to retrieve the serialized data of a survey. Also you can send submission by an appropriate request to the endpoint with proper HTTP method (GET, POST etc..). See description of endpoints on the page of Webform Service module.
You need to know the format of the data you are going to submit. Hereby you will find the right format of JSON object. The value of the values
key is an array either it has one or more values, so most of the time it looks like this:
{'values':{0:"put your value here"}}
In case of multiple values (checkbox, multi-select) it is possible to use values
like this:
{'values':{
0:"put your value1 here",
1: "put your value2 here",
}}
Finally here is a snippet of HTML and AngularJS to prepare and post a request to the REST API.
HTML
<form ng-submit="submit('put the UUID of the survey here')" ng-controller="formCtrl">
<label>Your name:</label><br/>
<input type="text" ng-model="formData[1]['values'][0]" /><br/>
<label>I like tea</label><br/>
<input type="checkbox" ng-model="formData[2]['values'][0]" value="tea" /><br/>
<label>I like coffee</label><br/>
<input type="checkbox" ng-model="formData[2]['values'][1]" value="coffee" /><br/>
<input type="submit" value="Send" />
</form>
Note that you don't need to write static HTML form, but you can retrieve the data of the survey from the API and build the form by a script.
JavaScript
var app = angular.module('webformApp', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller('formCtrl', function($scope, $element, formService) {
$scope.submit = function(uuid){
formService.postForm(uuid, this);
};
});
app.service('formService', function($http){
return {
postForm: function(uuid, $scope){
var toPost = {
webform: uuid,
submission: {
data: $scope.formData
}
};
console.log(toPost);
console.log(JSON.stringify(toPost));
return $http.post('http://example.com/yourendpoint/submission', toPost);
}
};
});
To try/test the API itself you can use Postman extension of Chrome browser. This JS will log the JSON string to the console to send it to API.
Have fun!
相关文章