You are here

function _node_resource_attach_file in Services 7.3

Attaches or overwrites file(s) to an existing node.

Example form element used to post files to attach_file: <form action="site.com/endpoint/node/1234/attach_file" method="post" enctype="multipart/form-data"> <input name="files[anything1]" type="file" /> <input name="files[anything2]" type="file" /> <input name="field_name" type="text" value="field_image" /> <input name="attach" type="text" value="0" />

The name="files[anything]" format is required to use file_save_upload().

Parameters

$nid: Node ID of the node the file(s) is being attached to.

$field_name: Machine name of the field that is attached to the node.

$attach: Optional. Defaults to true. This means that files will be attached to the node, alongside existing files. If the maximum number of files have already been uploaded to this node an error is given. If false, it removes the files, and attaches the new files uploaded.

Return value

An array of files that were attached in the form: array( array( fid => N, uri => http://site.com/endpoint/file/N ), ... )

See also

file_save_upload()

File interface

3 string references to '_node_resource_attach_file'
hook_services_resources in docs/services.services.api.php
Defines function signatures for resources available to services.
ServicesRESTServerTests::getTestResource in servers/rest_server/tests/ServicesRESTServerTests.test
_node_resource_definition in resources/node_resource.inc

File

resources/node_resource.inc, line 674

Code

function _node_resource_attach_file($nid, $field_name, $attach, $field_values) {
  $node = node_load($nid);
  $node_type = $node->type;
  if (empty($node->{$field_name}[LANGUAGE_NONE])) {
    $node->{$field_name}[LANGUAGE_NONE] = array();
  }

  // Validate whether field instance exists and this node type can be edited.
  _node_resource_validate_node_type_field_name('update', array(
    $node_type,
    $field_name,
  ));
  $counter = 0;
  if ($attach) {
    $counter = count($node->{$field_name}[LANGUAGE_NONE]);
  }
  else {
    $node->{$field_name}[LANGUAGE_NONE] = array();
  }
  $options = array(
    'attach' => $attach,
    'file_count' => $counter,
  );
  list($files, $file_objs) = _node_resource_file_save_upload($node_type, $field_name, $options);

  // Retrieve the field settings.
  $field = field_info_field($field_name);
  foreach ($file_objs as $key => $file_obj) {
    if (isset($field_values[$key])) {
      foreach ($field_values[$key] as $key => $value) {
        if ($key == 'fid') {
          continue;
        }
        $file_obj->{$key} = $value;
      }
    }
    $node->{$field_name}[LANGUAGE_NONE][$counter] = (array) $file_obj;

    // Check the field display settings.
    if (isset($field['settings']['display_field'])) {

      // Set the display option.
      $node->{$field_name}[LANGUAGE_NONE][$counter]['display'] = $field['settings']['display_field'];
    }
    $counter++;
  }
  node_save($node);
  return $files;
}