D8 - Attach file programmatically to a node
Scenario 1: If the file resides on the other server/website. Try the below code,
use \Drupal\node\Entity\Node;
/** Create file object from remote server/website URL. */
$data = file_get_contents('https://www.example.com/sites/default/files/logo.png');
$file = file_save_data($data, 'public://logo.png', FILE_EXISTS_REPLACE);
// Create node object with attached file.
$node = Node::create([
'type' => 'article',
'title' => 'Sample test',
'field_image' => [
'target_id' => $file->id(),
],
]);
$node->save();
Refer "file_save_data" API for more options/overide functions
Scenario 2: If the file resides on the same server/website. Try the below code,
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
// Create file object from a locally copied file.
$uri = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
'uri' => $uri,
]);
$file->save();
// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
'target_id' => $file->id(),
]);
$node->save();
Refer "file_unmanaged_copy" API for more options/overide functions
Scenario 3: Create a Placeholder/dummy file
use \Drupal\node\Entity\Node;
$node = Node::create([
'type' => 'article',
'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();
Good Luck!
use \Drupal\node\Entity\Node;
/** Create file object from remote server/website URL. */
$data = file_get_contents('https://www.example.com/sites/default/files/logo.png');
$file = file_save_data($data, 'public://logo.png', FILE_EXISTS_REPLACE);
// Create node object with attached file.
$node = Node::create([
'type' => 'article',
'title' => 'Sample test',
'field_image' => [
'target_id' => $file->id(),
],
]);
$node->save();
Refer "file_save_data" API for more options/overide functions
Scenario 2: If the file resides on the same server/website. Try the below code,
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;
// Create file object from a locally copied file.
$uri = file_unmanaged_copy('public://source.jpg', 'public://destination.jpg', FILE_EXISTS_REPLACE);
$file = File::Create([
'uri' => $uri,
]);
$file->save();
// Load existing node and attach file.
$node = Node::load(1);
$node->field_image->setValue([
'target_id' => $file->id(),
]);
$node->save();
Refer "file_unmanaged_copy" API for more options/overide functions
Scenario 3: Create a Placeholder/dummy file
use \Drupal\node\Entity\Node;
$node = Node::create([
'type' => 'article',
'title' => 'Generated image test',
]);
$node->field_image->generateSampleItems();
$node->save();
Good Luck!
Comments