I'm creating a node programmatically, and after saving (creating) the node, I re-read the node and "get" the value of the serial field, but it is empty. Here's my code (my field is "field_release_id")...

// Create the new release node.
$newNode = Node::create(['type'  => 'release']);
$newNode->set('title', 'Release');                  //Assign temp value so the save won't throw an error
$newNode->set('field_sales_contract', $scNid);
$newNode->save();

$newNodeId = $newNode->id();

$newNode = \Drupal\node\Entity\Node::load($newNodeId);
$releaseId = $newNode->get('field_release_id')->getValue();
$releaseId = (empty($releaseId[0]['value']) ? NULL : $releaseId[0]['value']);

if (!empty($releaseId)) {
  $newNode->set('title', 'Release ' . $releaseId);    //Update the title now that we have the Release ID
  $newNode->save();
}

.

I added the code to re-read the node after the first save after my first attempt failed. I had assumed the serial field value would be put back into the node object (similar to the way the Node Id is done), but even after re-reading it, the value was still blank.

Interestingly, when I inspected the object (with Kint) after the first save, the "field_release_id" field was in the "values" array (albeit with no actual value), but after re-reading it, it wasn't there at all. Not sure if that's a helpful clue, but, well, there it is.

Comments

ExTexan created an issue. See original summary.

joseic’s picture

Hi,

I've been dealing with same issue and I've found a solution, you need to set the serial field with any value (no matters what because Serial module will overwrite it)

So, in your code add:

$newNode = Node::create(['type'  => 'release']);
$newNode->set('title', 'Release');                  //Assign temp value so the save won't throw an error
$newNode->set('field_release_id',1); // Set default value
$newNode->set('field_sales_contract', $scNid);
$newNode->save();

BR

ashleywilson’s picture

Same issue, specifying default value as 1 works in one environment, but doesn't in another. Specifying uniqueid()'s output avoids the error, but field isn't set.

mortona2k’s picture

Setting a dummy value on the field worked for me too.

ebeyrent’s picture

Dummy value also worked for me.

colorfield’s picture

Status: Active » Closed (outdated)

Cannot reproduce on the latest codebase. Feel free to re-open.