Score:0

Build custom form with entity form field

de flag

I have a feature to migrate from Drupal 7 to Drupal 9. This allows me to build a custom form made up of static fields, which I define in the code of my module, and fields dynamically retrieved from an entity.

It worked with the "ctools_field_invoke_field function", which relies on the Chaos Tools module. This function is itself based on a native Drupal function "field_default_form".

This function was not migrated to Drupal 9 according to my research. Can I find an equivalent? Should I develop this function from scratch?

My previous code :

// If no language is provided use the default site language.
$options = array(
  'language' => field_valid_language($langcode),
  'default' => TRUE,
);

// Append to the form
ctools_include('fields');
$field_instance = field_info_instance($entity_type, $field_name, $bundle);
return (array) ctools_field_invoke_field($field_instance, 'form', $entity_type, $entity, $form, $form_state, $options);
Score:0
ss flag

I did not find similar function either. Looks like it does not exist. Though, here is how it can be achieved in Drupal 8/9 forms:

$entity = $this->entityTypeManager->getStorage('node')->create([
  'type' => 'article'
]);
$form_state->set('entity', $entity);


/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $this->entityTypeManager->getStorage('entity_form_display')->load('node.article.custom_form_display');
$form_state->set('form_display', $form_display);

foreach ($form_display->getComponents() as $name => $component) {
  $widget = $form_display->getRenderer($name);
  if (!$widget) {
    continue;
  }

  $items = $entity->get($name);
  $items->filterEmptyItems();
  $form[$name] = $widget->form($items, $form, $form_state);
  $form[$name]['#access'] = $items->access('edit');
}

This code was taken from the following article: https://www.webomelette.com/how-render-entity-field-widgets-inside-custom-form-drupal-8

I am not affiliated with it, but personally, recommend to read.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.