I have many products coming from a migration. This is working for most of the products, but for some of them, the /commerce/modules/product/src/Plugin/Field/FieldWidget/SingleVariationWidget.php widget is empty.
First, I thought that the product didn't have any variation. Turns out, it does.
After some digging, I've found that the formElement function inside SingleVariationWidget isn't retrieving only the variation product.
This variable is getting first an instance of my product, then my product variation.
$variation = !$items->isEmpty() ? $items->first()->entity : NULL;
To bypass this, I've added this patch, but it's a patch, and I still don't know why it happened.
$variation = !$items->isEmpty() ? $items->first()->entity : NULL;
if (!$variation) {
$param = \Drupal::routeMatch()->getParameter('commerce_product');
$variation = $this->entityTypeManager->getStorage('commerce_product_variation')->create([
'type' => reset($this->getFieldSetting('handler_settings')['target_bundles']),
'langcode' => $items->getEntity()->language()->getId(),
]);
if ($param) {
$idProduct = $param->id();
$product = Product::load($idProduct);
if ($product->getDefaultVariation()) {
$variation = $product->getDefaultVariation();
}
}
}