Last updated 7 June 2016. Created on 27 November 2011.
Edited by Mac_Weber, er.pushpinderrana, a_thakur, revagomes. Log in to edit this page.

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:

Step-by-step

  1. Figure out how Drupal wants to receive the data structure

  2. Build the data structure

  3. POST the data structure

  4. Verify if it worked

  1. Figure out how Drupal wants to receive the data structure

  2. 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:
    dpm() example

    The important parts are:

    The Text field
    dpm() of Text field

    The fivestar field
    dpm() of Fivestar field

    The node reference field
    dpm() of Node Reference field

  3. Build the data structure

  4. 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:
    Text field dpm()

    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:
    Fivestar dpm()

    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:
    Node reference dpm()

  5. POST the data structure

  6. 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:
    Firefox Poster screenshot
    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:

    Poster responseNote 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

  7. Verify if it worked

  8. 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')

Field Collection Example

Here is JSON Structure for this:

"field_mobile_number_collection": {
  "und": [ 
   {
    "field_mobile_number": {
	"und": [
	  {
	     "value": "123456789"
	  }
	]
     },
     "field_privacy_options": {
	"und": "1"
     }
   }
 ]
}

Looking for support? Visit the Drupal.org forums, or join #drupal-support in IRC.

Comments

designbymind’s picture

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

nyleve101’s picture

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

Romka’s picture

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:

  1. authorize user test_user. This user should have permissions to create node type "test" (you can change node type) and upload files.
  2. Upload image file and store fid of this file.
  3. Create a new node and attach uploaded image to imagefield with name field_main_image.
// node data

$filename = '/absolute/path/to/image.jpg';
$title = 'A node created with services 3.x and REST server';
$body = '<p>Body lorem ipsum</p>';
$tags = 'TEST_TAG, TEST_TAG2';
$type = 'test'; // node type
$vid = 2; // vid of vocabulary marked as "Tags"

$services_url = 'http://example.com/your-rest-server-endpoint';

/*
 * Server REST - user.login
 */

// REST Server URL for auth
$request_url = $services_url . '/user/login';

// User data
$user_data = array(
  'username' => 'test_user',
  'password' => 'password',
);

$user_data = http_build_query($user_data);

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $user_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $logged_user = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die('Auth error ' . $http_message);
}

// Define cookie session
$cookie_session = $logged_user->session_name . '=' . $logged_user->sessid;

/*
 * Server REST - file.create
 */

if(!file_exists($filename)) {
  die('File not exists');
}

if(!is_readable($filename)) {
  die('File not readable');
}

// file
$file = array(
  'filesize' => filesize($filename),
  'filename' => basename($filename),
  'file' => base64_encode(file_get_contents($filename)),
  'uid' => $logged_user->user->uid,
);

$file = http_build_query($file);

// REST Server URL for file upload
$request_url = $services_url . '/file';

// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $file); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $file_data = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die('Sending file error<br>' . $http_message . "\n<br>");
}

// file id (nessesary for node)
$fid = $file_data->fid;

/*
 * Server REST - node.create
 */

// REST Server URL
$request_url = $services_url . '/node';


// Node data
$node_data = array(
  'title' => $title,
  'type' => $type,
  'body' => $body,
  'taxonomy[tags][' . $vid . ']' => $tags,
  'field_main_image[]' => array('fid' => $fid, 'list' => 1, 'data' => NULL),
);
$node_data = http_build_query($node_data);


// cURL
$curl = curl_init($request_url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Accept: application/json')); // Accept JSON response
curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POST
curl_setopt($curl, CURLOPT_POSTFIELDS, $node_data); // Set POST data
curl_setopt($curl, CURLOPT_HEADER, FALSE);  // Ask to not return Header
curl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved session
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);

$response = curl_exec($curl);
$http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

// Check if login was successful
if ($http_code == 200) {
  // Convert json response as array
  $node = json_decode($response);
}
else {
  // Get error msg
  $http_message = curl_error($curl);
  die('Getting data error<br>' . $http_message . "\n<br>");
}

print_r($node);

emilkarl’s picture

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.

[field_files] => Array
(
  [und] => Array
  (
    [0] => Array
      (
        [fid] => 185
        [display] => 1
        [title] => My name
        [description] =>
      )
    
    [1] => Array
      (
        [fid] => 186
        [display] => 1
        [title] => 
        [description] => My description
      )
  )
)
jhr’s picture

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;

yannou’s picture

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 :

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));

by :

curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded','Accept: application/json'));

So we can decode the json response and get the fid (else it is null).

I hope it will be usefull

arnaud80’s picture

Thank you for your sample.

But how do you do for private files ?

Kritika Sharma88’s picture

please tell me how to retrieve and update through services module ?
I have create node through services module.

emilkarl’s picture

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?

ender2012’s picture

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:

{
   "title":"online submission",
   "type":"basic_content",
   "field_text":[
      {
         "value":"Some Text"
      }
   ]
}

Any idea why this might not work?

Thanks for your awesome tutorial!

emilkarl’s picture

Try something like

{
   "title":"online submission",
   "type":"basic_content",
   "field_text": {
      "und":[
        {"value":"Some text"}
     ]
   }
}

// Object with encode
$node= new stdClass;
$node->title = "online submission";
$node->type = "basic_content",
$node->field_text = array('und' =>array(array('value' => 'Some text'));
json_enode($node);
benjamin_dk’s picture

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):

  /* debug code start*/
  $test = drupal_json_encode($_POST);
  dpm($test);
  /*debug code end*/

  return $node;

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

a_barouch’s picture

Thanks!

rexfordnyrk’s picture

Thanks a lot you saved me some good time from try and error

luisfn’s picture

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?

lindstrom1989’s picture

Hey I know you posted this awhile a go but did you find the solution? can't find any answers out there.

manonjupiter’s picture

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.. :)

Mac_Weber’s picture

This is a really cool approach!
I agree D.O should change to make it easier to add images here at comments.
Adding it:
Only local images are allowed.

tomhung’s picture

Here is a Date CCK in D6.

"field_datecckfield":[
  {
    "value":{
      "date":"2010-01-27"
    }
  }
],
aoturoa’s picture

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':

[field_vacature_provincie] => Array
(
  [und] => 237
)

Example 'Called argument array':

[field_vacature_provincie] => Array
(
  [und] => Array
  (
    [0] => Array
    (
      [tid] => 237
    )
  )
)

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?

damianfarina’s picture

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?

vadinho’s picture

Did you ever manage to do this? I'm having the same problem at the moment.

mlhoque’s picture

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!

tyler.frankenstein’s picture

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 } ] }

gateway69’s picture

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:

// Node data
$node_data = array(
  'uid'  => 1,
  'title' => 'awesome',
  'type' => 'rating',
  'body' => array(
    'und' => array(
      'value' => 'awesome game guys!',
    ),
  ),
  'field_fsrating' => array(
		'und' => array(array(
			'value' => 100,
			'target' => 0,
			)
		)
	),
);

I have also tried:

// Node data
$node_data = array(
  'uid'  => 1,
  'title' => 'awesome',
  'type' => 'rating',
  'body' => array(
    'und' => array(
      'value' => 'awesome game guys!',
    ),
  ),

  'field_fsrating' => array(
		'und' => array(
			'value' => 100,
			'target' => 0,
			)
	),

);

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?

gateway69’s picture

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 :

// Node data
$node_data = array(
  'uid'  => 1,
  'title' => 'awesome',
  'type' => 'rating',
  'body' => array(
    'und' => array(
      'value' => 'awesome game guys!',
    ),
  ),
  'field_fsrating' => array(
		'und' => array(array(
			'rating' => 100,
			)
		)
	),
);
Shyghar’s picture

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

 "field_type": {
        "und": [{
            "value": "field_value"
        }]
    }

but if I try to insert with the same structure i have back this error

{
    "form_errors": {
        "field_type][und": "An illegal choice has been detected. Please contact the site administrator."
    }
}

How can i insert this field?

Mac_Weber’s picture

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"

Shyghar’s picture

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:

 "field_type": {
        "und": [{
            "value": "Office"
        }]
    }

PROBLEM SOLVED!

I don't know why but this code works.

 "field_type": {
        "und": {
            "value": "Office"
        }
    }
philpro’s picture

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!

pmelab’s picture

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.

pmelab’s picture

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.

tpainton’s picture

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].

Strutsagget’s picture

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

g089h515r806’s picture

for my use case, the correct value is:
field_expert: {und: [entity_id_1]},

Chinese drupal tutorials Think in Drupal

wedge’s picture

This is how you format something for the geo location field:

"field_location":{"und":[{"address":{"field":"Lund, Sweden"},"lat":"55.7046601","lng":"13.191007300000024"}]}

isinadinos’s picture

I tried this sample location field for location module:

"field_location":{
      	"und":[
          		{
                  "country":"el",
                  "latitude":"55.7046601",
                  "longitude":"13.7046601"
                }
        	]
    }

and geo location module:

{
    "field_report_location":{
      "und":[{
        "input_format" : "GEOFIELD_INPUT_LAT_LON",
        "geom": {
         "lat":"55.7046601",
         "lon":"13.191007300000024"
        }
      }]
    }
}

but didn't work.
For the first case the location table is updated with longtitude and latitude both set to 0.000000.

Any suggestions?

juampynr’s picture

In Drupal 7, each field's data is grouped by the language, so the array structure need to look like the following:

'field_ip_address' => array('und' => array(array('value' => '1.2.3.4')))

Based on http://drupal.stackexchange.com/questions/3207/simple-rest-request-to-cr...

llimit’s picture

Hi!
I created a block with the content given above, but the $_POST array is empty all the time.

    ... (Array, 0 elements)
 Called from modules/php/php.module(80) : eval()'d code, line 2  

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.

tarasiadis’s picture

Hi I try to set poster to test the creation of node.
Firstly the custom block with the code

<?php
dpm($_POST);
?>

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.

{
   "title":"test reserv from poster",
   "type":"reservation",
   "field_email":[
      {
         "value":"t@0.com"
      }
   ],
"field_phone":[
      {
         "value":"690000000"
      }
   ],
"field_date_2":[
      {
         "value":"2013-12-25 00:00:00"
      }
   ]
}

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

"field_date_2":{
      "und":[{
        "value":{"date":"12/25/2013"}
            }]}
}

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.

cedric_a’s picture

Checking the option "Display redirection page" in the Devel settings solved the problem for me

maxgor’s picture

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.

mahipal46’s picture

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

ecramer’s picture

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:

Notice: Undefined offset: 0 in file_field_widget_form() (line 526 of /Applications/XAMPP/xamppfiles/htdocs/<my site>/html/modules/file/file.field.inc).
Notice: Undefined offset: 0 in image_field_widget_form() (line 358 of /Applications/XAMPP/xamppfiles/htdocs/<my site>/html/modules/image/image.field.inc).

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.

brennino’s picture

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

brennino’s picture

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

bennos’s picture

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.

rosso69’s picture

I try to post a node with organic groups.

This is not working. :

{
"title":"My Title",
"type":"question",
"unpublish_on":1414133838,
"og_group_ref":{"und":[{
"target_id":"Testgroep 2"
}]}
}

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>

rosso69’s picture

{
"title":"My Title",
"type":"question",
"unpublish_on":1414133838,
"og_group_ref":[1]
}

This works in combination with the selectbox widget.

gbestwick’s picture

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:

dpm($_POST);

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!

gbestwick’s picture

Anyone?

C'mon?

gbestwick’s picture

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.

taggartj’s picture

just made a text field with m-name "field_somfield" -

this is application/json poster example

{
  "type":"page",
  "title":"Node title",
"field_somfield":{
      "und":[{
        "value":"some value"
            }]
},

  "body":{
    "und":[
      {
        "value":"This is the body of the test page."
      }
    ]
  }

}

that worked for me.

robschuh’s picture

I founded a solution for dates

https://www.drupal.org/node/2325521

   "field_calendar":{
      "und":[
         {
            "value":{
               "day":"17",
               "month":"9",
               "year":"2014",
               "hour":"9",
               "minute":"15",
               "ampm":"am"
            }
         }
      ]
   },
tommaso.asciolla’s picture

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

tommaso.asciolla’s picture

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.

omnia.ibrahim’s picture

Can you write this on json format.

tommaso.asciolla’s picture

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

ybthefurste’s picture

https://www.drupal.org/node/1447020#comment-10323523

{
"body":"","type":"teahouse","title":"TestingTitle","uid":"0",
"locations":[{"city":"Kalamazoo"}],
"taxonomy_vocabulary_1":{"und":{"hierarchical_select":{"selects":[1,18,35]}}},
"status":"1",
"field_redtea":{"und":[{"value":"1"}]},
"field_bubbles":{"und":[{"value":"boba poppers","format":null,"safe_value":"boba poppers"}]},
"field_hour_thu_close":{"und":"17"}
}
hiranya’s picture

Can anyone guide me how to post image with raw json ?

I tried like:

{
  "type": "article",
  "title": "Test article with image",
  "body": {
    "und": [{
      "value": "test body!"
     }]
  },
"field_image":{
"und":[{
"iVBORw0KGgoAAAANSUhEUgAAAKQAAAFzBAMAAABC179RAAAAD1BMVEUYooorZrPZwVO3Sd0M9xpwqPtgAAAACXBIWXMAAA7EAAAOxAGVKw4bAAAC70lEQVR4nO3bW2rjQBRF0XxkAoYagfEMrAFIseY/plagZdfj1r07RAXt1tFXJ6DFPvJLDvTHBz0u9MCiSJEiRYoUKVKkSJEiRYoUKVKkSJEiRYoUKVKkSJEiRYoUKVLkf0auf4/lGPJzo/bKtP371+TnOlfDQ5SC+bUMUFfMwPLhcS+qm1j8WJyWnFBHnMufqxP7Jhab52XXxGL7VO+ZWDRePR0Ti9YL0jaxaL7GTROL9tuGZVonm2Lnnch4zhvnrsbvumRqTWO2LfbeLxMg7dn9t+Amk87uk810Otv5oKin09neZ0+ViSMdssrEkd4nZJmJIz2yzMSR7ud4kYkjXbLIxJH+3UaeiSN9Ms/EkcE9UZaJIwMyy8SR0Z3bKxNHRuQrE0eG95fPTBwZks/MkWS0O76x3pfjyJjcM3EkuP1fRpPxbkCmgowjyfeeZSwJdhMyjSXBbvQdchlJkt2ITCNJspt9H1/GkWg3I9M4Eu2Gf9tYRpFsNyTTG5HzkeR2Md+FhJeSkunM5HwseVnOS9JHB5NJ5OnI+WjyIlLk78mvKzzu9BAp8p8kb0eTk8jTkdevg8nHiUn6+EBxup+YpI8PJB/vQ8KLycTp/j4kvJiMfAwj2XK6exTJltPdw0i0nO4eRqLldPc4kiynu8eRZDndPZAEy+nunQSZNHIkGS+nu59knEkjX2SYSSOHkuFyujsjo0wamZFRJo3MySCTRuZkkEkjC9LPpJEF6WfSyJJ0M2lkSbqZNLIivUwaWZFeJo2sSSeTRtakk0kjG7KfSSMb8rr+lJyqyJbsToezLbI3Hc62yN50ONskO9PhbJu8maYprsbvLNI2qWiTpknFDmmZVOyRhknFLtmaVOyTjUlFh7zeyud8cdrUFz1yex3loUWi8Qxn5Bb6QjPQSQzJHIVgTH6j67qT0xqChPw+9v8r5V3CH5L5cJEiRYoUKVKkSJEiRYoUKVKkSJEiRYoUKVKkSJEiRYoUKVKkyBOSfwC2VwFIl7c9aAAAAABJRU5ErkJggg=="

}],
},
  "language" : "und"
}

Problem:Node is created,but image is not

rahul_sankrit’s picture

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.

StijnStroobants’s picture

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

"field_activity_date":{
        "und":[
            {
                "value":{
                    "date":"15/04/2016",
                    "time":"09:30"
                }
            },
            {
                "value":{
                    "date":"16/04/2016",
                    "time":"09:30"
                }
            }
        ]
    }
rosso69’s picture

look at comment-9486123

you can use put after the post to add the rest of the data.

steveoriol’s picture

for an radio button list that reference some products from commerce module "field_ref_produit"

I need to transform this json:

{
  "type": "puce_nfc",
  "title": "YNE test",
  "field_sn": {  "und": [  {  "value": "00:69:97:92:6d:40:00"   }   ]  },
  "field_ref_produit": {  "und": [  {  "product_id": "2"   }  ]  }
}

to this:

{
  "type": "puce_nfc",
  "title": "YNE test",
  "field_sn": {  "und": [  {  "value": "00:69:97:92:6d:40:00"   }   ]  },
  "field_ref_produit": {  "und": [  "2"  ]  }
}

for make it works without 'form_errors'... bizarre.

Stève

zhilevan’s picture

how we can pass file to file field with REST?

I have be born to be mankind

bennos’s picture

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.

francesco.sessa’s picture

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

aolaze’s picture

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

private login_user2 loginAsync2(string username, string password)
    {
        try
        {
            RestClient client = new RestClient(base_url2);
            var request = new RestRequest("user/login.json", Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            client.Authenticator = new SimpleAuthenticator("username",username,"password",password);
            var restResponse = client.Execute(request);
            var content = restResponse.Content;
            if (restResponse.StatusCode==System.Net.HttpStatusCode.OK)
            {
                login_user2 loginuser = JsonConvert.DeserializeObject<login_user2>(content.ToString());                    
                request = new RestRequest("session/token", Method.GET);
                restResponse = client.Execute(request);
                loginuser.session_token = restResponse.Content.ToString();
                return loginuser;
            }
            else {
                return null;
            }
        }
        catch (Exception ex) { throw ex; }
    }

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:

RestClient client = new RestClient(base_url2);
        var request = new RestRequest("node", Method.POST);
        request.AddHeader("cache-control", "no-cache"); 
        request.AddHeader("content-type", "application/json; charset=UTF-8");
        request.AddHeader("Accept", "application/json");
        request.AddHeader("cookie", "Drupal.toolbar.collapsed=0; "+current_user2.session_name+"="+current_user2.sessid+"; has_js=1");
        request.AddHeader("x-csrf-token",current_user2.session_token);
        request.AddHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        request.AddParameter("application/json", myjobject, ParameterType.RequestBody);

        var queryresult = client.Execute(request);

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);

aolaze’s picture

what about the json data of taxonomy_term reference and entity_reference in drupal 7?

StijnStroobants’s picture

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.

$term = taxonomy_get_term_by_name($values['term'], 'vocabulary_name');

    if (isset($term)) {
      $term = array_shift(array_keys($term));
      $node->field_your_term_field[LANGUAGE_NONE][] = array('tid' => $term);
    }
bennyrock20’s picture

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:


"field_mobile_number_collection" : {
				"und" : [
                               {
					"field_mobile_number" : {
						"und" : [{
							"value" : "123456789"
						}]
					},
					"field_privacy_options" : {
						"und" : "1"
					}
				}, {
					"field_mobile_number" : {
						"und" : [{
							"value" : "234232342343"
						}]
					},
					"field_privacy_options" : {
						"und" : "0"
					}
				}]
			}

Thank you very much for your help in advance.

vvv8’s picture

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:

... excerpted
// field_item is my field collection
"field_item" : { "und": [
// the first one works ok       
{ 
       "field_item_manufacturer": {"und": [ { "value": "some value "} ] }, "field_item_model": {"und": [ { "value": "some other value "} ] }
},
// the second one gets created on the node but the values are all empty...
{ 
       "field_item_manufacturer": {"und": [ { "value": "some other value "} ] }, "field_item_model": {"und": [ { "value": "some other new value "} ] }
}
]}...

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

tyler.frankenstein’s picture

omnia.ibrahim’s picture

did you solve this issue? i have the same problem

omnia.ibrahim’s picture

I'm using select other module, for select list, how to pass it to the json?

omnia.ibrahim’s picture

did you manage to post and saving multiple field_collection values?