public function PadoAddToCartForm::buildForm in Commerce Product Add-on 8
Form constructor.
Parameters
array $form: An associative array containing the structure of the form.
\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.
Return value
array The form structure.
Overrides AddToCartForm::buildForm
File
- src/
Form/ PadoAddToCartForm.php, line 61
Class
- PadoAddToCartForm
- Provides the order item add to cart form.
Namespace
Drupal\commerce_pado\FormCode
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
$form['#theme'][] = 'commerce_pado_add_to_cart_form';
// Add add-ons.
$field_name = $form_state
->get([
'settings',
'add_on_field',
]);
/** @var \Drupal\commerce_product\Entity\ProductInterface $product */
$product = $form_state
->get('product');
$multiple = $form_state
->get([
'settings',
'multiple',
]);
$variation_storage = $this->entityTypeManager
->getStorage('commerce_product_variation');
$view_builder = $this->entityTypeManager
->getViewBuilder('commerce_product_variation');
$form['add_ons'] = [
'#type' => 'container',
'#tree' => TRUE,
'#weight' => 50,
];
/** @var \Drupal\commerce_product\Entity\ProductInterface $add_on_product */
foreach ($product->{$field_name}
->referencedEntities() as $add_on_product) {
$variations = $variation_storage
->loadEnabled($add_on_product);
$variations_view_render = $view_builder
->viewMultiple($variations, 'add_on');
$options = [];
$add_ons = [];
foreach ($variations as $key => $add_on_variation) {
/** @var \Drupal\commerce_product\Entity\ProductVariationInterface $add_on_variation */
$add_on_variation_id = $add_on_variation
->id();
$add_on_variation_title = [
'#theme' => 'commerce_pado_addon_product_variation_label',
'#product_entity' => $add_on_product,
'#variation_entity' => $add_on_variation,
];
$options[$add_on_variation_id] = $this->renderer
->render($add_on_variation_title);
$add_ons[$add_on_variation_id]['#description'] = $variations_view_render[$key];
}
$addon_product_title = [
'#theme' => 'commerce_pado_addon_product_label',
'#product_entity' => $add_on_product,
];
if (!empty($options)) {
if (count($options) > 1) {
$form['add_ons']['items']['add_ons_' . $add_on_product
->id()] = [
'#type' => $multiple ? 'checkboxes' : 'select',
'#options' => $options,
'#title' => $this->renderer
->render($addon_product_title),
'#empty_value' => '',
'#empty_option' => t('- None -'),
] + $add_ons;
}
else {
$form['add_ons']['items']['add_ons_' . $add_on_product
->id()] = [
'#type' => 'checkbox',
'#title' => $this->renderer
->render($addon_product_title),
'#return_value' => key($options),
] + $add_ons;
}
}
}
return $form;
}