0

I am creating a new node with an image field. The code I am using to create the node is this.

$node = Node::create(['type' => 'leadspace']);
$node->setTitle('Node Title');
$node->set('field_background_image', [
    'target_id' => 391
]);

I have an image that has the target_id of 391 used on another node, and it is showing correctly. For the node I am creating, the image is not assigned correctly.

I have also tried, but it doesn't work either.

$node = Node::create(['type' => 'leadspace']);
$node->setTitle('Node Title');
$node->set('field_background_image', [
     [
        'target_id' => 391
     ]
]);

I also get the following errors for some weird reason but only get it when I am setting the image field, if I comment out the image field method the node is created all fine without any problems:

A fatal error occurred: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'projectName' in 'field list': 
INSERT INTO {file_usage} (fid, module, type, id, projectName) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); 
Array 
( [:db_insert_placeholder_0] => 391 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 11524 [:db_insert_placeholder_4] => 1 )

How can I programmatically add images that are already on the server to new nodes? Where is fatal error coming from?

  • Both should work, as should $node->get('field_background_image')->target_id = 391. or even just a set of 391. Define doesn't work, do you gt an error, is there something in the node__field_background_image table for that node in the database? – Berdir Apr 30 '17 at 9:31
  • I had it in a try catch block and once I remove it the error shown is: A fatal error occurred: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'projectName' in 'field list': INSERT INTO {file_usage} (fid, module, type, id, projectName) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => 391 [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 11524 [:db_insert_placeholder_4] => 1 ) – Harnamc Apr 30 '17 at 9:47
  • That error is very weird. Set error logging to verbose and post the full stacktrace. – Berdir Apr 30 '17 at 11:33
  • I have developer mode set so it is dumping out verbose errors. – Harnamc Apr 30 '17 at 12:48
  • Does not seem to be verbose enough, as I said, the stack trace is important to see where this is coming from exactly. – Berdir Apr 30 '17 at 13:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.