You are here

public static function PriceListItemInlineForm::purchasedRefresh in Commerce Pricelist 8

Auto get the purchased entity's price.

Parameters

array $form: The form.

\Drupal\Core\Form\FormStateInterface $form_state: The form state of the parent form.

Return value

array The price element.

File

src/Form/PriceListItemInlineForm.php, line 196

Class

PriceListItemInlineForm
Defines the inline form for product variations.

Namespace

Drupal\commerce_pricelist\Form

Code

public static function purchasedRefresh(array $form, FormStateInterface $form_state) {
  $element = [];
  $triggering_element = $form_state
    ->getTriggeringElement();

  // Remove the action and the actions container.
  $array_parents = array_slice($triggering_element['#array_parents'], 0, -2);
  while (!(isset($element['#type']) && $element['#type'] == 'inline_entity_form')) {
    $element = NestedArray::getValue($form, $array_parents);
    array_pop($array_parents);
  }
  $elementPrice = $element['price'];
  $targetType = $element['#entity']
    ->getFieldDefinition('purchased_entity')
    ->getSetting('target_type');
  $fieldPriceListItem = $form_state
    ->getValue('field_price_list_item');

  // When the operation is 'add'.
  if ($element['#op'] == 'add') {
    if (isset($fieldPriceListItem['form']['inline_entity_form']['purchased_entity'][0]['target_id'])) {
      $purchasedEntityId = $fieldPriceListItem['form']['inline_entity_form']['purchased_entity'][0]['target_id'];
    }
  }
  else {
    $entities = $fieldPriceListItem['form']['inline_entity_form']['entities'];
    if (isset($entities[$element['#ief_row_delta']]['form']['purchased_entity'][0]['target_id'])) {
      $purchasedEntityId = $entities[$element['#ief_row_delta']]['form']['purchased_entity'][0]['target_id'];
    }
  }
  if (isset($purchasedEntityId)) {

    // Because there's no object($this) in the ajax callback when we use
    // inline_entity_form, so we can't use $this->entityTypeManager directly.

    /** @var \Drupal\commerce\PurchasableEntityInterface $purchasedEntity */
    $purchasedEntity = \Drupal::entityTypeManager()
      ->getStorage($targetType)
      ->load($purchasedEntityId);
    $price = $purchasedEntity
      ->getPrice();
    if (!is_null($price)) {
      $elementPrice['widget'][0]['number']['#value'] = sprintf("%.2f", $price
        ->getNumber());
    }
    else {
      $elementPrice['widget'][0]['number']['#value'] = NULL;
      $elementPrice['widget'][0]['number']['#placeholder'] = NULL;
    }
  }
  return $elementPrice;
}