Drupal 8: Set entity field cardinality programatically inside a custom form

This is how you can dynamically change a multi select entity field maximum number of selected items programmatically.

//The sample codes below will get an entity form and render the entity form fields to a custom form.

// Create the entity
$entity = $this->orderItemStorage->create([
  'title' => 'Order Item',
  'type' => 'bee',
  'purchased_entity' => 'my_product_variation_id',
  'quantity' => 1,
  'unit_price' => '100',
]);

// Add the entity to form_state
$form_state->set('order_item', $entity);

// Get the form display
$form_display = $this->entityTypeManager->getStorage('entity_form_display')->load('commerce_order_item.bee.add_to_cart');
$form_state->set('order_item_form_display', $form_display);

// Set the form parents to empty to avoid form rendering errors
$form['#parents'] = [];

// loop through the entity form fields
foreach ($form_display->getComponents() as $name => $component) {
  $widget = $form_display->getRenderer($name);
  if (!$widget) {
    continue;
  }

  $items = $entity->get($name);


  if ($name === 'my_multiple_select_field') {
    // Get the field definition and field storage definition object and set the cardinality
    $definition = $items->getFieldDefinition();
    $fieldStorageDefinition = $definition->getFieldStorageDefinition();
    $fieldStorageDefinition->setCardinality(1);
  }

  $items->filterEmptyItems();

  // Add the entity form field to your custom form
  $form[$name] = $widget->form($items, $form, $form_state);
  $form[$name]['#access'] = $items->access('edit');
}

 

Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.