I am using a hook function to create a commerce product when a node type of PL is created.
I have 2 Entity Reference fields:
- Name of Project - Which references content
- Type of Use - Which references a taxonomy term
Everything works and the title field is set correctly except for the 2 field values, field_name_of_project and field_type_of_use.
What could I be doing wrong.
Here's my code:
<?php
/**
* @file
* file for the PL Product Creation module, which creates a product and product variations when a Pl node is created.
*
*/
use Drupal\node\Entity\Node;
use Drupal\node\NodeInterface;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
/**
* Implementation of hook_entity_insert().
*/
function pl_product_creation_entity_insert(Drupal\Core\Entity\EntityInterface $entity) {
if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'pl_node') {
// Get the pl node properties
$name_of_project = $entity->field_name_of_project->entity->getTitle();
$type_of_use = $entity->field_type_of_use->entity->getName();
// Load the product
$pl_product_title = 'Products at ' . $name_of_project;
// Load the product storage.
$entity_type_manager = \Drupal::service('entity_type.manager');
$product_storage = $entity_type_manager->getStorage('commerce_product');
// Load the product by title.
$pl_product = $product_storage->loadByProperties(['title' => $pl_product_title]);
// Check if the Pl product exists
if (!empty($pl_product)) {
// Load the Pl product
$pl_product = reset($pl_product);
}
else {
// Create a new Pl product
$pl_product = Product::create([
'type' => 'pl',
]);
// Set the title field.
$pl_product->setTitle($pl_product_title);
// Set the values of the custom fields.
$pl_product->set('field_name_of_project', $name_of_project);
$pl_product->set('field_type_of_use', $type_of_use);
// Save the product entity.
$pl_product->save();
}
}
}