Using the module Services to create a node with required custom fields may be challenging. Most of the problems fall on formatting the data to be sent.
Here are three examples of how to figure out how format the data. The first example is the easiest, it will show how to post a Text
field. The second example will use a fivestar field. Finally, the third example will show how to use a node reference field with auto complete widget.
I will send the data in JSON format, but this tutorial can be used for any format your web service accepts.
Tools I will use:
- The Services module
- Devel module - to use
dpm()
- Firefox Poster add-on - to do tests and debugging.
- To help editing and validating the JSON data:
- Edit the JSON data using http://braincast.nl/samples/jsoneditor/
- Validate the JSON data using http://jsonformatter.curiousconcept.com/
Step-by-step
-
Figure out how Drupal wants to receive the data structure
-
Build the data structure
-
POST the data structure
-
Verify if it worked
-
Figure out how Drupal wants to receive the data structure
-
Build the data structure
-
POST the data structure
-
Verify if it worked
For all examples, the first step is to figure out how Drupal handles the data object of that node. An easy way to do it is to use add a custom block to the page which has the form used to create the node. Use PHP format and input this code:
<?php
dpm($_POST);
?>
This code will output the data object right after you create a new node.
Then, try it once to see this structured data. You will see something like:
The important parts are:
The Text field
The fivestar field
The node reference field
The Text field is the easiest. You have to build the same structure you see on the dpm()
:
{
"field_review":[
{
"value":"The user comments"
}
]
}
Compare with the dpm()
data:
If you use http://braincast.nl/samples/jsoneditor/ to build your JSON tree, you can see the path as json['field_review'][0]['value']
, which matches the Text field structure on the dpm()
. The value "The user comments" is the text value sent for the Text field.
Note that there is no "0" (zero) in the structure. In this very specific case, it would work. However, in other cases, such as the node review field with auto complete, it may lead errors!
It works without the zero because JSON already put it on the path as the first index of arrays.
The structure for the fivestar field is the following:
{
"field_fivestar_value":[
{
"rating":"100",
"target":"0"
}
]
}
Compare to:
Note again I did not use "0", even knowing it would work. Moreover, in this specific example, I'm not targeting the fivestar rating. In my case, the only allowed values for "rating" were "20", "40", "60", "80", or "100".
The tricky part is the node reference field, when it is set to use the auto complete widget. You have to query "[nid:xxxx]" to avoid errors such as "found no valid post with that title".
This field on JSON format looks like:
{
"field_establishment":[
{
"nid":{
"nid":"[nid:26686]"
}
}
]
}
Compare to:
The first thing you should know before posting is that a node requires a title field. In addition, to create the node, you have to specify the node type you are creating. Then, include this data:
{
"title":"Review",
"type":"establishment_review"
}
Now, get everything together:
{
"title":"Review",
"type":"establishment_review",
"field_establishment":[
{
"nid":{
"nid":"[nid:26686]"
}
}
],
"field_fivestar_value":[
{
"rating":"20",
"target":"0"
}
],
"field_review":[
{
"value":"comments about the restaurant"
}
]
}
Note that there is no curly brackets ({ nor }) surrounding each field. This is very important, and it will not work if you leave them there.
Your data is ready to be POSTed.
Use the firefox add-on Poster to test it:
Note that the data is not indented and I am not using multiple lines to organize the data. This is to avoid errors. It happened once when I copied the code to OneNote, and later pasted again in Poster. The format changed with some extra unwanted spaces and it messed the data. It may lead to false errors!. Again, use a single line of data when using Poster.
The URL is your Drupal web address + your Services endpoint + requested resource. In this case:
Drupal address: http://example.com
Services endpoint: /rest_api
Requested resource: /node
Also change the Content Type to application/json
You should get a response like:
Note the HTTP 200 OK status. It means the web service processed your request.
If you want the response also in JSON, change the URL to http://example.com/rest_api/node.json
A you can see on the response:
<?xml version="1.0" encoding="utf-8"?>
<result><nid>5138098</nid><uri>http://example.com/rest_api/node/5138098</uri></result>
Just put write on your browser address bar: http://example.com/node/5138098
. The browser should open your new node.
Add on for Field Collection
In case you are using Field Collection in your node here is example how to deal with such type of fields.
Example:
You have Field Collection for mobile number having two fields:
1. Mobile Number (Text Field)
2. Privacy Options (List Dropdown): Dropdown Values(1 => 'Private', 2 => 'Public')
Here is JSON Structure for this:
"field_mobile_number_collection": {
"und": [
{
"field_mobile_number": {
"und": [
{
"value": "123456789"
}
]
},
"field_privacy_options": {
"und": "1"
}
}
]
}
Attachment | Size |
---|---|
img1-0.jpg | 61.27 KB |
text-field-dpm.jpg | 81.69 KB |
fivestar-field-dpm.jpg | 81.67 KB |
node-reference-field-dpm.jpg | 80.92 KB |
text-field-dpm - crop.jpg | 17.97 KB |
fivestar-field-dpm - crop.jpg | 24.11 KB |
node-reference-field-dpm - crop.jpg | 20.36 KB |
Firefox-Poster.jpg | 90.91 KB |
Firefox-Poster-response.jpg | 92 KB |
Field_Collection.png | 2.84 KB |
Comments
Image Field
Hello. I was wondering if you have successfully POSTed an Image Field via Services 3 (I'm using Drupal 6)? - Format is JSON
I have followed your tutorial with great success, but cannot for the life of me, POST a node with an Image Field...
Thanks in advance for any advice. I surely need it.
- Jason
Hi, designbymind, did you
Hi,
designbymind, did you figure out how to post a node with an image field? I can't for the life of me figure it out.
Hope you're well and taking care of yourself.
Evelyn
Below my code for uploading images to imagefield
Below my code for uploading images to imagefield through the services. This is a external PHP-script, which can be run on external server (without Drupal).
In server resources you should check next resources: file.create, node.create, user.login.
This code makes 3 steps:
Updating file field
Have you ever had any success with this method for updating a node.
It works for me to create, but if I follow the same method for adding new files to my node on update, they will only be created (added to file_managed) but not connected to the node. But if I update title or description on an existing file it will be updated. It seems like you only can specify fid for the files when creating, not updating. It will skip those files.
Here is the array for the PUT.
Use the files resource..
Use the files resource to get the json obj of the file. endpoint/file/185.json
Then use it to update the node. node.field_files[und][0] = jsonObj;
Something to add
Nice script but I was coming to madness because file was uploaded but not attached to node.
Till I eventually realize it would be better to replace :
by :
So we can decode the json response and get the fid (else it is null).
I hope it will be usefull
And for private file ?
Thank you for your sample.
But how do you do for private files ?
retrieve and update through services module
please tell me how to retrieve and update through services module ?
I have create node through services module.
Isnt there a simpler way than
Isnt there a simpler way than this. To clean up a node for a node.create for the services? Right now I'm looking into doing a "prepare for service" function to automatically clean $node object for posting. I think it's strange that there isnt one in Drupal/Services already?
Trouble populating Text field
I am having a lot of trouble populating a simple field through the method you have outlined here. I have created a content type called basic_content which has a field called text with machine name field_text which is a text field with a Text field widget. Now I can create instances of this content type with the method you have outlined but the Text field never gets populated. Here is my json string:
Any idea why this might not work?
Thanks for your awesome tutorial!
Try <?php{ "title":"online
Try something like
Some debugging tips
I was stuck with a similar issue, and found it very useful to put the following debugging code at the end of node.modules' node_submit()-function (line 1005 in v. 7.15):
Now make a new node of the content type you are working with and (if you're logged in and have the devel module installed) you should get more or less correctly formatted json data. This is the only way I figured out how to get json data that would get saved in my fields when posted with the Firefox Poster plugin.
See my issue here for more details
This made the trick
Thanks!
Merci
Thanks a lot you saved me some good time from try and error
Problem removing references
Following the example for node references using the auto complete widget, I could finally save reference to other nodes. Now, imagine the oposite, I want to remove a reference, what should be the format for that? I tried just remove it from the JSON object but actually it don change anything.
For example, this is the current data:
{"und":[{"nid":"[nid:431]"},{"nid":"[nid:561]"},{"nid":"[nid:563]"}]}
An this is a simple change
{"und":[{"nid":"[nid:431]"},{"nid":"[nid:561]"}]}
But if I execute the PUT with this data, I keep the same old value. Any one know how to fix that?
Hey I know you posted this
Hey I know you posted this awhile a go but did you find the solution? can't find any answers out there.
a simple way to find und
would like to share a simple way that I'm using ...
1. Inspect target custom element using the browser development tool
2. Find the corresponding "name" attribute within the html DOM element
3. Translate the "name" into JSON format
That's it! Simple enough?
following is an example image how to find geofield und using Firefox inspector,
An example how to find und using just browser inspector
P.S: Uploading image at here is much harder than finding interesting und format.. :)
Thanks for sharing
This is a really cool approach!
I agree D.O should change to make it easier to add images here at comments.
Adding it:
Date CCK
Here is a Date CCK in D6.
Using dummy node
Hi all,
I'm trying to node.create objects of a certain content type to a XML-RPC server.
Because I do not know what custom fields are attached to the content type i am using a node.retrieve to load an existing object of that content type as a template. I then strip the object of nid, created etc.
My idea was that now I have a new object, with all custom fields attached, ready to be posted to the XML-RPC server. Unfortunaly the server doesn't save the new node due to field errors.
I compared the POST data (see Step 1 in this tutorial) with the 'Called arguments array' the server received ... and they differ.
Example 'POST data':
Example 'Called argument array':
Some other custom fields are accepted and some not.
Does anyone have an idea how to get my template node object into the right format?
Remove or turn off booleans and check-box widgets
Hi everyone,
I'm having a hard time trying to figure out how to turn off a boolean field.
Something similar happens with taxonomy terms and the check-box widget, selecting items is not a problem but if I want to update the node and deselect all of the items nothing happens.
Does anybody knows how to achieve this?
Turn off boolean checkbox
Did you ever manage to do this? I'm having the same problem at the moment.
set/unset boolean field
I got stuck with this too and this is the only thread that I came across with similar issue. So, even though the question is really old I hope my answer will help someone else in future. Only way I found how I can set or unset a boolean field is by including or excluding the field with my data for create. I am using rest+json to push content. So, if I want to enable/check a boolean field I am including it with my data and to leave it inactive/unchecked I exclude the field from my post data e.g.
To check
data['field_name']['und'][0]['value'] = 1; // Doesn't matter what the value is as long as it is included
To uncheck
Just don't include the field
But during update to uncheck
data['field_name']['und'] = null;
If anyone else can provide a better or more elegant solution that would be really great.
Cheers!
Drupal 7 Services Boolean Field
Agreed, to set a boolean field to FALSE in Drupal 7 with the Services module, you set the value as NULL, for example:
field_private: { und: null }
To set it to TRUE, you set the value to 1
field_private: { und: [ {value: 1 } ] }
FiveStar + Drupal 7
I cant seem to get my node create working, I have the end point set up for node create, and nodes are being created the 5 start value is not getting set.
Here is my array:
I have also tried:
with out much luck, the debug log for services doesnt really help it shows the data getting called and passed but when viewing the node or looking in devel nothing is assigned to field_fsraiting
any ideas?
ahhh, got caught with usually
ahhh, got caught with usually doing value = some int, with five star it needs to be this, after re-reading this post..
so it should look like :
select and checkbox widget problem.
Hi,
i have a problem inserting/modifying a simple List(text) field.
When i call a node via Services i have a structure like this
but if I try to insert with the same structure i have back this error
How can i insert this field?
Different requests lead to different results
The structure for getting and inserting information may be different. You my even have just get or just insert for some information.
DO NOT follow the same Services structure to post and get. Try using the Devel module to see how your node is created using the UI. There you will see an more accurate structure.
To figure out how Drupal expects your data to be inserted, read again the first step "Figure out how Drupal wants to receive the data structure"
I read 'Figure out how Drupal
I read 'Figure out how Drupal wants to receive the data structure' but i don't understand why this insert don't work.
I have this dsm() output:
Structure image
so this code should be right:
PROBLEM SOLVED!
I don't know why but this code works.
Submit select drop-down form field with Services
I also do not know why this works, but removing the bracket allows the value to be submitted to Drupal select form fields using Services successfully.
Thanks!
A Project Ricochet, Drupal Developers Team Member
Entity Reference
Did anybody manage to POST/PUT entity reference fields?
I tried a lot of variations, and according to the data scheme it should be
"field_reference":{"und":[{"target_id":12}]}
(?), but nothing worked.Solved!
Ok, I figured it out:
My entity reference field widget was "autocomplete tagging". I switched it to "select box", now if i provide data like
"field_reference": [ entity_id_1, entity_id_2 ...]
it simply works.My REST-API depends now on field widgets configured for the frontend ... not a thing of beauty.
JSON format depends on Widget type.
Regarding entity reference..Totally dependent on the widget used.
For Autocomplete ;
"field_reference": {
"und":[{
"target_id":"Anything (69)"
}]
}
The title of the node is required but it appears any string will do. I suspect the nid is ripped out with a regex call.
For checkboxes it reads "field_reference": { 1:1, 2:2, ... ,nid:nid} and for select box "field_reference": [1,2,3 ... nid].
Atucomplete tag style
If anyone get autocomplete tag style working it would be great.
Have another thread here. https://www.drupal.org/node/2297251
//PiJa Media & Management AB din apputvecklare
for my use case, the correct
for my use case, the correct value is:
field_expert: {und: [entity_id_1]},
Chinese drupal tutorials Think in Drupal
Sample location field
This is how you format something for the geo location field:
"field_location":{"und":[{"address":{"field":"Lund, Sweden"},"lat":"55.7046601","lng":"13.191007300000024"}]}
Didn't work for location and geo location modules
I tried this sample location field for location module:
and geo location module:
but didn't work.
For the first case the location table is updated with longtitude and latitude both set to 0.000000.
Any suggestions?
Language grouped fields
In Drupal 7, each field's data is grouped by the language, so the array structure need to look like the following:
Based on http://drupal.stackexchange.com/questions/3207/simple-rest-request-to-cr...
$_POST empty?
Hi!
I created a block with the content given above, but the $_POST array is empty all the time.
Where exactly do I have to put the block? It is in the header region of every content type now. No matter what kind of node i create, the array will be empty. :(
Thanks for any hints or help.
Post date data
Hi I try to set poster to test the creation of node.
Firstly the custom block with the code
returns an empty array. So I see the properties of fields from devel tab of my content type entry.
See our structure at http://www.easytechservers.gr/temp/drupal-devel-services-date-bug.png
I can set simple textfileds data and create the node from poster except a date filed of my content type. See out json structure here.
I'm very confused how the structure of fields must be to works the post. What happens with nested array and dictionaries of a general structure and how we have to construct the json? Please some more useful explanation about the construction of json in general.
Thanks.
Part solution
I found this structure of date json that works
But I could not set the date in format 25/12/2013 only 12/25/2013.
And in general I could not find instructions for construction of json for services module.
Solution for empty dpm($_POST)
Checking the option "Display redirection page" in the Devel settings solved the problem for me
Add field collection via API
Hi,
I have field collection "field_collection_images" with two fields: field_collection_image (it's node reference) and field_collection_image_comment field (usual textarea field).
And I need that this field collection will be created through services. But when I pass params, a node is created, but field collection values are empty.
I create next params in the request:
$data = array('node[type]' => "test", 'node[title]'=>'test', 'node[uid]' => 1, 'node[language]' => 'und', 'node[body][und][0][value]' => 'test test', 'node[field_collection_images][und][0][value]' => "[nid:1]");
OR
$data = array('node[type]' => "test", 'node[title]'=>'test', 'node[uid]' => 1, 'node[language]' => 'und', 'node[body][und][0][value]' => 'test test', 'node[field_collection_image][und][0][nid]' => 1);
Could someone help me - how the params should be formed ?
Regards,
Max.
drupal 7 date format for services
user can pass value in poster using this format.
Name Value
field_field_date[und][0][value][date] 1 Jan 2014
field_field_date[und][0][value][time] 11:45am
field_field_date[und][0][value2][date] 3 Jan 2014
field_field_date[und][0][value2][time] 11:45pm
field_field_date[und][0][show_todate] 1
field_field_date[und][0][all_day] 0
Populating image fields on new nodes broken with update
I have a system that more or less follows the "upload file, save file id, create node and add file id" pattern described earlier by Romka. Everything was working great until I updated Drupal from 7.24 to 7.26.
I'm not using JSON, my post body looks like this:
field_sales_contact[und][0]=3&type=sales_lead&title=Manuel%20Uptonloader&field_business_card[und][0][fid]=151
I started down this path after some messages started showing up in Drupal's logs:
I'm not ready to point fingers at a particular file or update yet, but I thought I'd start sharing some of my troubles.
I report the same error
I report the same error Undefined offset: 0 with json. The node has been created but hasn't a file attached. I think there is a bug or same kind of hole in documentation.
Can someone document how actually create a node that has a file field with the current version of drupal and the current version of the services module?
Thanks
Brennino
Is there someone that could
Is there someone that could help with this error please? I have also check the documentation here http://drupanium.org/api but seems outdated for services 3.5+
In that documentation, I have tried the procedure showed here http://drupanium.org/api/82 but without success, same error.
I believe there is also an approach using the resource node/file_attach but isn't present in the documentation at drupanium.
I need help for attach a file to a node field and I believe there was someone else in my same situation.
Thanks
you can not upload files
you can not upload files directly in the node / entity.
First upload the file via services, look at the response body of the new created file. there is the "fid" in it.
When you create a node / entity you can use this fid now to reference your file.
It's me, BENNOS.
I try to post a node with
I try to post a node with organic groups.
This is not working. :
Also tried to add the group id, not working either.
Changed widget to autocomplete, select, checkbox, etc.
Response allways is something like this
<form_errors><og>You must select one or more groups for this content.</og></form_errors>
Solved
This works in combination with the selectbox widget.
I feel stupid, but just humor me...
I get almost everything in this entire tutorial.
I'm writing a program in Delphi that is going to accomplish this, and have had great success.
But, I have on simple question:
This:
Precisely where to I put that to get it to display this.
I've created a block that can evaluate PHP and all it did was give me a blank screen.
Pretend I'm stupid and use a big font and small words.
Thanks!
Anyone?
Anyone?
C'mon?
The goods.
OK.
Important details.
You don't actually have to put that PHP code anywhere.
You need to download and install "devel" module from here:
https://www.drupal.org/project/devel
Then go and enable the 3 Modules "Devel, Devel Node Access, Devel Generate" and those will give you tools to see things.
Then, create a node, and view it. You will see a 3rd tab beside View and Edit called Devel
Click on Object stdClass and it will give you everything else.
This worked for me Custom text field
just made a text field with m-name "field_somfield" -
this is application/json poster example
that worked for me.
solution for dates (drupal 7)
I founded a solution for dates
https://www.drupal.org/node/2325521
Post text field with multiplevalue
Hi,
how can i format the data to post a Text field with multiple value?
This post
field_address[und][0][value]=Via numero 1
field_address[und][1][value]=Via numero 2
not work, save only Via numero 1
Thanks
Tommaso
Post text field with multiplevalue - SOLVED
First POST (create):
field_address[und][0][value]=Via numero 1
insert Via numero 1
then PUT (update):
field_address[und][1][value]=Via numero 2
insert Via numero 2
then PUT (update)
field_address[und][2][value]=Via numero 3
insert Via numero 3
and so on.
Can you write this on json
Can you write this on json format.
File attach in private folder
Hi,
i upload a file in private://... and i have a fid
then when i PUT (update) a node with the fid, this file is not attached
&filed_fileprivate[und][0][fid]=123
&field_fileprivate[und][0][description]=File privato
&field_fileprivate[und][0][display]=1
&filed_fileprivate[und][0][status]=1
Put(sDomain + sEndPoint + "/node/3452")
Why?
Thanks,
Tommaso
Example with Hierarchical Select, Dropdown, Taxonomy, Location
https://www.drupal.org/node/1447020#comment-10323523
Post image field value
Can anyone guide me how to post image with raw json ?
I tried like:
Problem:Node is created,but image is not
Image Base64 Formatter - Post Images in binary format.
Hi,
You can post your image in binary format by using Image Base64 Formatter module.
Image Base64 Formatter is module simply provides a formatter for image fields that prints the image encoded with base64. This is particularly useful when transmitting data through services.
Hi,
Hi,
for all fields I succeed to create the JSON format, expept a multiple date-field.
The first date entry is correctly created, but the second date is not created.
What is the best solution to create the Json output?
Thanks
multiple field values
look at comment-9486123
you can use put after the post to add the rest of the data.
form_errors on creation node from service with json
for an radio button list that reference some products from commerce module "field_ref_produit"
I need to transform this json:
to this:
for make it works without 'form_errors'... bizarre.
Stève
how pass file ?
how we can pass file to file field with REST?
I have be born to be mankind
Files can not be posted
Files can not be posted directly in one step.
First create the file. (send the data base64 encoded)
Second: create the entry referencing the file over the file:id (fid)
It's me, BENNOS.
Add image to image field in node
Hi!
I have tried to make the creation of a node with an image field.
I followed these steps:
1 - Upload image file to service /serviceendpoint/file.json;
2 - get the fid from the result {"fid":"639","uri":"http://mysite/serviceendpoint/file/639"}
3 - node creation with:
{
"title": "test node creation",
"field_price": {
"und": [{
"value": 123
}]
},
"field_currency": {
"und": {
"value": "EUR"
}
},
"field_image_ca": {
"und": [{"fid":"639"}]
},
"body": {
"und": [{
"value": "test test test test"
}]
},
"type": "classified_noex"
}
The node is created but the field_image_ca is empty!
I've tried with:
"field_image_ca": {
"und": [{"fid":"639"}]
}
"field_image_ca": {
"und": [{"fid":"639", "uid":295}]
}
"field_image_ca": {
"und": [{"fid":"639","title":"test","description":"test"}]
}
"field_image_ca": {
"und": [{"fid":"639","title":"test","description":"test", "display":1}]
}
"field_image_ca": {
"und": [{"fid":"639","title":"test","description":"test", "display":1, "status":1}]
}
but the result is always the same!!!
The image is correctly uploaded to server and in http://mysite/serviceendpoint/file/639 I've all informations! but the link between the node and the image is impossible!
In reports i found:
Notice: Undefined offset: 0 in image_field_widget_form() (linea 358 di /var/www/html/serv/modules/image/image.field.inc).
Notice: Undefined offset: 0 in file_field_widget_form() (linea 533 di /var/www/html/serv/modules/file/file.field.inc).
Any idea or alternative?
TY
What about the cookie and token doing
I was successful to created new article with the poster ,but i change to the C# and use the cookie + token has "Access denied for user anonymous". Somebody help.
C# code with below :
first login
I have question at the login/user->token and session/token ,which the difference? and which one is the right?
second ,post the create data:
I has the content:Access denied for user anonymous.
I do this change the request.addheader("cookie"...) -> request.addparamenter("session_name","session_id",parametertype.cookie);
what about the json data of
what about the json data of taxonomy_term reference and entity_reference in drupal 7?
I would suggest to create a
I would suggest to change the data structure and use hook_node_presave to get the tid or create a new term.
Just pass the term name in your data structure.
I don't know if this approach is the best solution or not.
Add Field Collection with mutli-value field
Hello, i am trying to create a node that have a field collection with multi-values, but this only save the first value and the second not.
I am trying in the following way:
Thank you very much for your help in advance.
Posting MULTIPLE field_collections is not working
Hi,
Not sure if this thread is still active... I have the same issue as @bennyrock20 above... I have a content type that I created which contains a field collection that has 15 fields in it. It is no problem for me to POST new nodes of that content type and all the field collection values come through using Services 3.
But now my content type allows multiple field_collections to be added to it. So even when I do a static post in which I set it up like this:
I get a node that has 2 items in the field_item collection but the second one does not contain any values, it is completely blank...
Any ideas?
Thanks
- V
Long time issue
https://www.drupal.org/node/2224803
did you solve this issue? i
did you solve this issue? i have the same problem
I'm using select other module
I'm using select other module, for select list, how to pass it to the json?
did you manage to post and
did you manage to post and saving multiple field_collection values?