0

Hy guys,

I'm trying to implement a simple stock management in my e-commerce. The ProductVariation will have a stock_quantity field used to track product availability.

I would like that stock_quantity field is shown only if user checks an enable_stock_management checkbox on ProductVariation bundle edit page. I.e. /admin/commerce/config/product-variation-types/default/edit

In other words I would like to mimic Submission form settings, Menu settings, Display settings functionalities of Node's bundles.

By Google-ing a bit I think that hook_entity_type_build() is the hook to use. But, once I'm in the hook what I'm supposed to do in order to add the property I need and display it in the edit form?

 /**
  * Implements hook_entity_type_build().
  */
 function commerce_warehouse_entity_type_build(array &$entity_types) {
     /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
     $entity_types['commerce_product_variation_type']-> # ... And now?;
 }
0

Ends up that hook_entity_type_build() is not the right way to implement what I want. I found a solution usign ThirdPartySettingsInterface, which every ConfigEntityBase implements.

First I've altered ProductVariationType form via hook_form_alter() in order to add a checkbox to the form and register a new #enity_builder.

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function MY_MODULE_form_BASE_FORM_ID_alter(&$form, FormStateInterface $form_state, $form_id) {
  /** @var ProductVariationTypeInterface $entity */
  $entity = $form_state->getFormObject()->getEntity();

  $form['warehouse_management'] = [
    '#type' => 'checkbox',
    '#title' => t('Enable warehouse management'),
    '#default_value' => $entity->getThirdPartySetting('commerce_warehouse', 'warehouse_management'),
  ];

  $form['#entity_builders'][] = 'MY_MODULE_entity_ENTITY_ID_builder';
}

Then I've defined my custom entity builder function where I register my third party setting. Pretty simple! This article helps me out a lot.

/**
 * Entity builder for commerce_product_variation_type entity.
 */
function MY_MODULE_entity_ENTITY_ID_builder($entity_type, ProductVariationTypeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->setThirdPartySetting('commerce_warehouse', 'warehouse_management', $form_state->getValue('warehouse_management'));
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.