You are here

public function ProductBundleItemInlineForm::entityFormValidate in Commerce Product Bundle 8

Validates the entity form.

Parameters

array $entity_form: The entity form.

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

Overrides EntityInlineForm::entityFormValidate

File

src/Form/ProductBundleItemInlineForm.php, line 180

Class

ProductBundleItemInlineForm
Defines the inline form for product bundle items.

Namespace

Drupal\commerce_product_bundle\Form

Code

public function entityFormValidate(array &$entity_form, FormStateInterface $form_state) {
  parent::entityFormValidate($entity_form, $form_state);
  $bundleItems = $form_state
    ->getUserInput()['bundle_items'];
  if ($entity_form['#op'] == 'add') {
    if (isset($bundleItems['form']['inline_entity_form']['variations'])) {
      $formVariationsIds = $bundleItems['form']['inline_entity_form']['variations'];
    }
    $productId = $bundleItems['form']['inline_entity_form']['product'];
    if (isset($productId[0]['target_id'])) {
      $productId = EntityAutocomplete::extractEntityIdFromAutocompleteInput($productId[0]['target_id']);
    }
  }
  elseif ($entity_form['#op'] == 'edit') {
    if (isset($bundleItems['form']['inline_entity_form']['entities'][$entity_form['#ief_row_delta']]['form']['variations'])) {
      $formVariationsIds = $bundleItems['form']['inline_entity_form']['entities'][$entity_form['#ief_row_delta']]['form']['variations'];
    }
    $productId = $bundleItems['form']['inline_entity_form']['entities'][$entity_form['#ief_row_delta']]['form']['product'];
    if (isset($productId[0]['target_id'])) {
      $productId = EntityAutocomplete::extractEntityIdFromAutocompleteInput($productId[0]['target_id']);
    }
  }
  if (isset($productId)) {
    $product = Product::load($productId);
    if (isset($product)) {
      $variationsIds = $product
        ->getVariationIds();
    }
    else {
      $form_state
        ->setError($entity_form, "The product {$productId} didn't exist");
    }
  }
  if (!empty($formVariationsIds) && $formVariationsIds[0] != '_none') {
    foreach ($formVariationsIds as $value) {
      if (!in_array($value, $variationsIds)) {
        $message = t("Each bundle items's variations must belong to the same product");
        $form_state
          ->setError($entity_form, $message);
      }
    }
  }
}