Cannot access parent entity in hook_entity_create

Created on 21 December 2021, over 3 years ago
Updated 28 April 2023, about 2 years ago

Problem/Motivation

When creating a hook_entity_create to eg. set default values based on contextual info like the parent entity, we don't have access to the parent entity. That's because the parent_type, parent_id and parent_field_name fields aren't being passed to EntityStorageInterface::create when creating the widget, they are set using a setter immediately afterwards (code)

Steps to reproduce

Add hook_entity_create to a custom module and try to access the host entity using $entity->getParentEntity().

Proposed resolution

Pass the parent_type, parent_id and parent_field_name fields to the values array instead of setting them after the entity is created.

πŸ› Bug report
Status

Needs review

Version

1.0

Component

Code

Created by

πŸ‡§πŸ‡ͺBelgium dieterholvoet Brussels

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡¦πŸ‡ΊAustralia silverham

    +1 to this. I also have issues loading the temporary parent node entity in hook_field_widget_single_element_form_alter()

    This work around for now is to use : $node = $parent_entity = $form_state->getFormObject()->getEntity();

    Sample code below shows how to set the form default values as you enter paragraphs depending on how many.

    
    /**
     * Implements hook_field_widget_single_element_PLUGIN_ID_form_alter().
     *
     * @see \Drupal\Core\Field\WidgetBase::formSingleElement()
     */
    function my_module_field_widget_single_element_string_textfield_form_alter(array &$element, FormStateInterface $form_state, array $context) {
      $field_name = $context['items']->getName();
      $default_value = 'My default value to compare';
      if (($field_name == 'field_my_text_field')
        && ($context['items']->getEntity()->getEntityTypeId() == 'paragraph')
        && ($context['items']->getEntity()->bundle() == 'my_paragraph_type')) {
        $field_parents_no_subform = array_slice($element['#field_parents'], 0, -2);
        $parent_field_name = end($field_parents_no_subform);
        // Don't use $context['items']->getEntity()->getParentEntity()
        // it gets the current database node not the form temp node.
        // @see https://www.drupal.org/project/paragraphs/issues/3255456
        $parent_entity = $form_state->getFormObject()->getEntity();
        // Change new fields default to empty, by 
        if ($parent_entity->hasField($parent_field_name)) {
          $values = $parent_entity->get($parent_field_name)->getValue();
          if ((count($values) > 1) && ($element['value']['#default_value'] == $default_value)) {
            $element['value']['#default_value'] = '';
          }
        }
        // Change existing fields from default to empty.
        $input = $form_state->getUserInput();
        if (isset($input[$parent_field_name])) {
          $field_structure = array_merge(
            $element['#field_parents'],
            [
              $field_name,
              '0',
              'value',
            ]
          );
          // Get Value at
          // $input['field_parent'][$context['delta']]['subform'][$field_name]['0']['value'];.
          $current_value = NestedArray::getValue($input, $field_structure);
          if ($current_value == $default_value) {
            NestedArray::setValue($input, $field_structure, '');
            $form_state->setUserInput($input);
          }
        }
      }
    }
    
  • πŸ‡³πŸ‡±Netherlands Maico de Jong

    Had the same "issue" when trying to alter the paragraphs field options in the allowed_values_function callback based on the parent entity. (node)

    MR 46 worked great

  • Status changed to Needs work 9 months ago
  • πŸ‡¨πŸ‡­Switzerland berdir Switzerland

    The MR seems sensible but needs to be rebased.

  • πŸ‡§πŸ‡ͺBelgium dieterholvoet Brussels
  • πŸ‡§πŸ‡ͺBelgium dieterholvoet Brussels

    dieterholvoet β†’ changed the visibility of the branch 3255456-cannot-access-parent to hidden.

  • Pipeline finished with Failed
    4 months ago
    Total: 278s
    #387432
  • πŸ‡§πŸ‡ͺBelgium dieterholvoet Brussels

    Rebased! Not sure what that test failure is about.

  • πŸ‡ΊπŸ‡ΈUnited States peachez

    Adding a patch for paragraphs 8.x-1.17, using Drupal 10.3, as the current patch does not apply to this version.

  • πŸ‡¨πŸ‡¦Canada endless_wander

    I encountered this issue also when trying to use a form alter to change the paragraph's form based on its parent. I could do it for existing paragraphs but not when adding new ones.

    Using module 1.19 and Drupal 10.4

    Tried patch from #14 and it cannot be applied.

    Tried patch from #11 and it applied.

    In neither case, however, could the parentEntity be loaded when adding a new paragraph.

  • πŸ‡¨πŸ‡¦Canada endless_wander

    My problem comes from using Layout Paragraphs module it seems. Switching from Layout Paragraphs field formatter to default Paragraphs (stable) formatter and I can see `getParentEntity()` returning value as expected. Switching back to Layout Paragraphs formatter and `getParentEntity()` value is gone.

    Adding link to the related issue in Layout Paragraphs queue πŸ› Paragraph parent entity property is empty when adding new paragraphs Needs review and will update over there as well with presence of new patches.

  • πŸ‡¨πŸ‡¦Canada endless_wander

    For anyone finding this issue here, the MR from #11 above along with patch from #3 in Layouts Paragraph issue here -- https://www.drupal.org/project/layout_paragraphs/issues/3352822#comment-... πŸ› Paragraph parent entity property is empty when adding new paragraphs Needs review -- makes `getParentEntity()` work with Layout Paragraphs as well.

  • First commit to issue fork.
  • Pipeline finished with Failed
    about 2 months ago
    Total: 510s
    #456730
  • πŸ‡«πŸ‡·France S3b0uN3t Nantes

    Hello,

    In the current version of the merge request, a 500 error occurs when you try to insert a paragraph from a content creation form.
    It tries to load the content, but it doesn't exist yet.

Production build 0.71.5 2024