1

I use hook_field_widget_WIDGET_TYPE_form_alter() to alter the form for a single paragraph. What I do not understand is how I know which paragraph currently is edited when this hook is called. The problem: I want to change the default value for a field of the paragraph but only when no field value was set so far. So only when the paragraph gets created the default value should be changed as it is another default value when the paragraph is added within a node of a specific type.

I get the node with

$node = $build_info["callback_object"]->getEntity();

but then I do not know how to get the actually edited paragraph from here. It seems that nowhere in $form or $formState is the paragraph entity stored which is currenty edited?!

1 Answer 1

2

Isn't there a context variable containing the field items? If not please share more code.

If yes, you can get the field data through the field properties. In case of a reference field the first referenced entity

$paragraph = $context['items']->entity;

In Drupal 9 the widget hooks were streamlined.

Get a specific delta of an entity reference field

function mymodule_field_widget_single_element_WIDGET_TYPE_form_alter(&$element, FormStateInterface $form_state, $context) {
  $items = $context['items'];
  $delta = $context['delta'];
  $entity = $items[$delta]->entity;
  ...
}
3
  • This at least gives me the first paragraph in the list of items / referenced paragraphs. Thank you for this hint but still I don't know which paragraph is currently edited in $element['subform']. So when I have more than one paragraphs in the referencing field and I add a new one or I edit let's say the third one I just get the values already set in $element["subform"]. I don't see a way to get the entity of the currently edited / added paragraph?! Commented Feb 23, 2022 at 12:26
  • Then use the new streamlined hooks, more intuitive. I add a code example.
    – 4uk4
    Commented Feb 23, 2022 at 12:43
  • This was very helpful again, thank you! Commented Mar 2, 2022 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.