Score:-2

After update to PHP 8, module no longer works

sg flag

I have updated my Drupal from 8 to 9 and used PHP 7.4. Now I have chosen the time to update to PHP 8. Everything runs so far, only with a self-built module I get now an Error message:

The website encountered an unexpected error. Please try again later.
Error: Attempt to assign property "format" on null in copy_fields_from_model_contract_node_edit_node_prepare_form() (line 57 of modules/custom/copy_fields_from_model_contract_node_edit/copy_fields_from_model_contract_node_edit.module).

This concerns exactly this line:

$node->body->format = 'full_html';

The code of my module is not elegant, but it did its job as desired. Basically, I copy from another node the content of the body field into a body field of another node. The code of the whole module looks like this:

<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;


/**
* Implements hook_ENTITY_TYPE_prepare_form() for node entities.
*/
function copy_fields_from_model_contract_node_edit_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state)
{

//TODO Build NID as array and go through with loop

  $arr_vertraege = array(6766, 6769, 6768, 6775, 6767, 6776, 6777, 6778, 6779, 6780, 6781, 6782);

  foreach ($arr_vertraege as $mustervertraege) {

    $nid = $mustervertraege;
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);

    if ($nid == $mustervertraege) {


      $getcontract = $node->field_vertragsinhalt->value;
    }

  //TODO Works without ($operation == 'default')

  if ($operation == 'edit') {
    /*dpm("Modul an edit");*/
    //TODO Shall always pull the current node and nid. But does not work yet with node creation. Error: Call to a member function id() on null in

    $node = \Drupal::routeMatch()->getParameter('node');
    $nid = $node->id();
    $node_storage = \Drupal::entityTypeManager()->getStorage('node');
    $node = $node_storage->load($nid);

    if ($node->getType() == 'buch_anlegen') {
      if ($node->field_vertrag_updaten->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[0]) {
          $node->field_vertragsinhalt->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_2->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[1]) {
          $node->field_vertragsinhalt_2->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_3->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[2]) {
          $node->field_vertragsinhalt_3->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_4->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[3]) {
          $node->field_vertragsinhalt_4->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_5->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[4]) {
          $node->field_vertragsinhalt_5->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_6->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[5]) {
          $node->field_vertragsinhalt_6->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_7->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[6]) {
          $node->field_vertragsinhalt_7->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_8->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[7]) {
          $node->field_vertragsinhalt_8->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_9->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[8]) {
          $node->field_vertragsinhalt_9->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_10->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[9]) {
          $node->field_vertragsinhalt_10->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_11->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[10]) {
          $node->field_vertragsinhalt_11->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
      if ($node->field_vertrag_updaten_12->value == '1') {
        //  dpm($node->field_vertrag_updaten->value);
        //var_dump($node);

        if ($mustervertraege == $arr_vertraege[11]) {
          $node->field_vertragsinhalt_12->value = $getcontract;
          $node->body->format = 'full_html';
          // don't save the node yet, it will be saved after submitting
        }
      }
    }
  }
  }
}

Does anyone have a tip for me? I would be very grateful.

Greetz Bavra

P.S.: Complete error message from the logs:

Message    Error: Attempt to assign property "format" on null in copy_fields_from_model_contract_node_edit_node_prepare_form() (line 57 of /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/modules/custom/copy_fields_from_model_contract_node_edit/copy_fields_from_model_contract_node_edit.module)
#0 [internal function]: copy_fields_from_model_contract_node_edit_node_prepare_form(Object(Drupal\node\Entity\Node), 'edit', Object(Drupal\Core\Form\FormState))
#1 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Entity/EntityForm.php(397): call_user_func_array('copy_fields_fro...', Array)
#2 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Entity/EntityForm.php(129): Drupal\Core\Entity\EntityForm->prepareInvokeAll('node_prepare_fo...', Object(Drupal\Core\Form\FormState))
#3 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Entity/ContentEntityForm.php(287): Drupal\Core\Entity\EntityForm->init(Object(Drupal\Core\Form\FormState))
#4 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Entity/EntityForm.php(96): Drupal\Core\Entity\ContentEntityForm->init(Object(Drupal\Core\Form\FormState))
#5 [internal function]: Drupal\Core\Entity\EntityForm->buildForm(Array, Object(Drupal\Core\Form\FormState))
#6 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Form/FormBuilder.php(531): call_user_func_array(Array, Array)
#7 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Form/FormBuilder.php(278): Drupal\Core\Form\FormBuilder->retrieveForm('node_buch_anleg...', Object(Drupal\Core\Form\FormState))
#8 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Controller/FormController.php(73): Drupal\Core\Form\FormBuilder->buildForm(Object(Drupal\node\NodeForm), Object(Drupal\Core\Form\FormState))
#9 [internal function]: Drupal\Core\Controller\FormController->getContentResult(Object(Symfony\Component\HttpFoundation\Request), Object(Drupal\Core\Routing\RouteMatch))
#10 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(123): call_user_func_array(Array, Array)
#11 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/Render/Renderer.php(564): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#12 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(124): Drupal\Core\Render\Renderer->executeInRenderContext(Object(Drupal\Core\Render\RenderContext), Object(Closure))
#13 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php(97): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array)
#14 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/vendor/symfony/http-kernel/HttpKernel.php(158): Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
#15 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/vendor/symfony/http-kernel/HttpKernel.php(80): Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object(Symfony\Component\HttpFoundation\Request), 1)
#16 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/modules/contrib/redirect_after_login/src/RedirectMiddleware.php(46): Symfony\Component\HttpKernel\HttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#17 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/StackMiddleware/Session.php(58): Drupal\redirect_after_login\RedirectMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#18 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/StackMiddleware/KernelPreHandle.php(48): Drupal\Core\StackMiddleware\Session->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#19 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(106): Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#20 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/modules/page_cache/src/StackMiddleware/PageCache.php(85): Drupal\page_cache\StackMiddleware\PageCache->pass(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#21 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/modules/ban/src/BanMiddleware.php(50): Drupal\page_cache\StackMiddleware\PageCache->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#22 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/StackMiddleware/ReverseProxyMiddleware.php(48): Drupal\ban\BanMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#23 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/StackMiddleware/NegotiationMiddleware.php(51): Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#24 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/vendor/stack/builder/src/Stack/StackedHttpKernel.php(23): Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#25 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/core/lib/Drupal/Core/DrupalKernel.php(708): Stack\StackedHttpKernel->handle(Object(Symfony\Component\HttpFoundation\Request), 1, true)
#26 /home/bavramor/data/Webdesign/Webseiten/landwehrcie-backup-drupal9/web/index.php(19): Drupal\Core\DrupalKernel->handle(Object(Symfony\Component\HttpFoundation\Request))
#27 {main}
us flag
It looks like `body` field do not exist in the content type.
ru flag
I'm surprised that code ever worked. You receive a `$node` object in the hook (an object as function parameter means "by reference" in PHP) and then re-assign it three times with ... different things. I highly doubt the PHP upgrade is the cause of this error, and the null-safe operator from the answer below might avoid the WSOD, but not really fix your code.
Score:0
fr flag

Most likely there are nodes that do not have a body set, thus $node->body returns null.

Since using PHP8, you can try the null safe operator by simply doing:

$node->body?->format = 'full_html';

( pay close attention the the ?-> operator which means "if null just abort the chain" )

If the node that exhibits the issue does have a body, please update the question.

Edit: Corrected position of null safe operator as per comments.

cn flag
That will produce the same error - perhaps you meant `$node?->body?->format` or `$node->body?->format`?
apaderno avatar
us flag
@Nick The error is *Attempt to assign property "format" on null*. This means that `$node?->body->format` won't work. `$node?->body?->format` would be a better choice. That won't fix the rest of the code shown in the question, anyway.
fr flag
@Clive @apaderno from a PHP perspective, you're right; however, if the body is set, and it is the Drupal body (not some other field with the same name), it always has the `format` property -- that's never (to my knowledge) `null`. Hence my omission. Please correct me if there are cases where the above does not apply.
cn flag
_If the body is set_ - but your answer is for when the body isn't set, that's why you're testing null on the wrong thing. Null-safe tests the item to the left of the operator, not the right, so to test whether the body is null, it needs to be `body?->format`. You can also test the node for null as well in the same breath, that makes sense too, but you can't test for null on the body by testing for null on the node
fr flag
@Clive understood, thanks -- amended the answer accordingly.
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.