logo

Programatically upload or update files in Node filed Drupal 8

18
October

Programatically upload or update files in Node filed Drupal 8
By: Anonymous | Published On: Mon, 10/18/2021 - 16:58

When updating file in existing node

here field name is "field_file" in node.

$node = \Drupal\node\Entity\Node::load($nid);	// $nid is Node ID 

$node->set('field_file' , $fid);	// $fid is file id which have to update in node file field.

$node->save();

If you have to update files in multiple field value

In example "field_file" field has option to upload multiple files then we can use following code to upload/update multiple files in file field.

foreach($file_ids as $fid){
	$files[]['target_id'] = $fid;
}

$node->set('field_file' , $files);

$node->save();

When creating new Node

	$node = \Drupal\node\Entity\Node::create([
	  'type'        => 'CONTENT_TYPE',
	  'title'       => $name,
	  'uid' => $userid,
	  'body'       => $message,
	]);
	foreach($attach_files as $fid){
		$node->field_file[] = [
			'target_id' => $fid,
		];
	}

If you are using custom form then following code you can use to upload files

	$form['attach_file'] = [
		'#type' => 'managed_file',
		'#title' => t('Kindly attached your files here. '),
		'#upload_validators' => array(
		   'file_validate_extensions' => array('doc docx pdf jpg jpeg png'),
		),
		'#multiple' => TRUE,
		'#upload_location' => 'public://attach',
	];

On form submit you can get file ids


$attach_files = $form_state->getValue('attach_file');

foreach($attach_files as $fid){
	$files[]['target_id'] = $fid;
}

$node->set('field_file' , $files);

$node->save();

Need Help ?