LogicException: The database connection is not serializable.

Created on 23 July 2018, over 6 years ago
Updated 18 June 2022, over 2 years ago

Hi,

Im not sure if anyone else has got this error or not, but when I try to perform a validation $form_state->setErrorI am getting an error 

LogicException: The database connection is not serializable. This probably means you are serializing an object that has an indirect reference to the database connection. Adjust your code so that is not necessary. Alternatively, look at DependencySerializationTrait as a temporary solution. in Drupal\Core\Database\Connection->__sleep()

I will explain a bit more. In my form I have a form element which has an "Add more" functionality. That is, I can add another instance of that field with an incremented index in its name which is working all fine. Now I have added a form validation and want to validate against all the instances of this field. Its a straight forward validation logic

if (empty($field)) {
  $form_state->setError($form['content_bag_container']['bag_wrapper'][$key]['content_bag'], t('Please enter a content bag name.'));
}

Weirdly enough, this validation works for the first instance of the form element which pre-loads with the page itself. But whenever, I create a new instance via ajax, this validation fails and throws this error message in the log.

Can anyone check if this is some problem from my end or a bug in the core, cause I am not sure if an ajax populated field should be validated separately.

Thanks in advance...

🐛 Bug report
Status

Postponed: needs info

Version

9.5

Component
Form 

Last updated about 9 hours ago

Created by

🇮🇳India pratip.ghosh

Live updates comments and jobs are added and updated live.
  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

Sign in to follow issues

Comments & Activities

Not all content is available!

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

  • Open in Jenkins → Open on Drupal.org →
    Environment: PHP 8.1 & MySQL 5.7
    last update over 1 year ago
    30,322 pass
  • Got the same problem on a Drupal 9.5.9 / 9.5.10, migrated from a 8.x, when tring to add a file in a file field in a node.
    No custom code in this content type.

    Patch #15 work for me.
    Thanks.

  • 🇫🇮Finland aleksip Finland

    Five years later I come across this again, on Drupal 10.1.4. This time it happens if I set a translated error message in my form validation code. And does not happen with an untranslated error message. And the fix in #15 does seem to work.

    Considering the nature of the exception and reading all the comments it seems likely that there are different causes for the exception, probably requiring different fixes.

    I also wonder about the fix in #15, since the exception message states that DependencySerializationTrait should be looked as a temporary solution.

  • 🇺🇸United States SamLerner

    I'm seeing a similar issue on a Drupal 10.1.4 site, and I've narrowed it down to the Agreement module. Based on the comments that refer to the problem being with translating form errors, I think this code is the problem:

      public function validateForm(array &$form, FormStateInterface $form_state) {
        $storage = $form_state->getStorage();
        $agreement = $storage['agreement'];
        if (!$agreement->allowsRejecting() && !$form_state->getValue('agree') && !$storage['agreed']) {
          $settings = $agreement->getSettings();
          $form_state->setErrorByName('agree', $this->t('@agree_error', ['@agree_error' => $settings['failure']]));
        }
      }
    

    If the form is getting serialized, and the error message is using t(), then it's possible this is where the database connection is getting serialized as well. I can't reproduce the issue locally, so I'm applying the patch in #15 and will verify when the change gets to production.

    I am also curious about what should be done long-term if indeed DependencySerializationTrait is meant to be temporary.

  • 🇳🇱Netherlands johnv

    Relating to a meta issue.

  • 🇺🇸United States SamLerner

    Adding the DependencySerializationTrait didn't seem to solve my issue, I either didn't put it in the right place, or it's not the same cause of the error. I'll keep looking and see if I can figure out where it's coming from.

  • 🇳🇱Netherlands johnv

    Indeed, the problem is in an apparently unrelated class/object.

    In #35, if you replace $this->t('@agree_error' with global t('@agree_error', I expect the problem to be gone.

  • Status changed to Needs review about 1 year ago
  • 🇳🇱Netherlands johnv

    Let me re-open this issue and post a proposal patch.
    In the OP, I added some comments that makes the problem reproducable.
    Please check 🐛 LogicException: The database connection is not serializable (for string translations in Ajax callback) [META] Active , which I created with many references to other reported issues of (apparently) the same problem.
    IMO, adding DependencySerializationTrait to so many other, unrelated core/contrib classes is not the way to go. (Therefore, it is euphemistically a 'temporary' solution.)

    Attached patch interferes in the serialization of the TranslationManager, which contains a list of Translators (TranslatorInterface).
    By NOT serializing the listed Translators, the problem disappears.
    Unlike other objects, those Translators are re-created after the unserialization of the form.

    In my test case, 2 Translators were listed:
    - Drupal\Core\StringTranslation\Translator\CustomStrings (serializable)
    - Drupal\locale\LocaleTranslation (NOT serializable)
    As per comments in other topics, the second is not serializable due to an open DatabaseConnection. The object contains DependencySerializationTrait itself, but apparently that does not work.

    Hence, proposed solution is in TranslationManager, not in TranslatorInterface instances.
    My test case: #3399054-23: Ajax error on [Add exception] button if "seasons" is activated

    Let me first upload this patch, to check the tests.
    Then, let me add another patch, removing DependencySerializationTrait from some core classes.

  • Open in Jenkins → Open on Drupal.org →
    Environment: PHP 8.1 & MariaDB 10.3.22
    last update about 1 year ago
    Patch Failed to Apply
  • Open in Jenkins → Open on Drupal.org →
    Environment: PHP 8.2 & sqlite-3.34
    last update about 1 year ago
    Patch Failed to Apply
  • Open in Jenkins → Open on Drupal.org →
    Environment: PHP 8.2 & pgsql-14.1
    last update about 1 year ago
    Patch Failed to Apply
  • Open in Jenkins → Open on Drupal.org →
    Environment: PHP 8.1 & MySQL 5.7 updated deps
    last update about 1 year ago
    Patch Failed to Apply
  • Status changed to Needs work about 1 year ago
  • The Needs Review Queue Bot tested this issue.

    While you are making the above changes, we recommend that you convert this patch to a merge request . Merge requests are preferred over patches. Be sure to hide the old patch files as well. (Converting an issue to a merge request without other contributions to the issue will not receive credit.)

  • 🇺🇦Ukraine artem_kondra

    I have the same issue in Drupal core 10.1.6 with nl translation node, confirm that #15 solves problems, it will be great to see that in core

  • 🇬🇧United Kingdom alexpott 🇪🇺🌍

    @johnv I' ve tried the steps to reproduce and it does not happen for me with the address module. I've got a some questions about the steps to reproduce:

    • Is it with the Standard install profile?
    • What is the contrib field module you are using?
    • Are there any other contrib modules installed?
  • 🇳🇱Netherlands johnv

    @alexpott, please check attached patch for some test instructions.

    Test by:
    - Install with normal install profile.
    - Enable locale module 'User interface translation' with +1 languages.
    - Enable office_hours module and add field to a Content type.
    - In Field settings, Allow both Exceptions and Seasons.
    - Select widget type 'Office Hours (week) with exceptions and seasons'.
    - Edit with non-English page, e.g., /nl/node/8/edit .
    - Enable both Exceptions and Season in widget settings.
    - Create/Edit node with non-English page, e.g., /nl/node/8/edit .
    - Click 'Add Exception' button. (You may need to click twice.)
    - Check if an empty exception is added, or error occurs.
    Set breakpoint at OfficeHoursSeason~label() and OfficeHoursSeasonHeader~process().
    @see https://www.drupal.org/project/office_hours/issues/3399054 🐛 Ajax error on [Add exception] button if "seasons" is activated Active

    You can provoke the error by switching between the following return values in OfficeHoursSeason~label():
    - return $this->t($this->name);
    - return t($this->name);
    - return $this->name;
    The first one will generate the error.

    (IMO in previous Drupal versions, bootstrap::t() and $this->t() return different classes. I might be mistaken, because in my current D10.2 dev version, both return TranslatableMarkup, only created with different parameters. I never understood why there was/is a difference. )

  • 🇳🇱Netherlands johnv

    @alexpott, please ignore the file in #43. It is too long. See newly attached file.

  • 🇹🇭Thailand AlfTheCat

    Having the same issue on 10.3.9, on image fields in my case.

    I tried the patch from #39 but it doesn't apply:

    sudo -u www-data patch -p1 < core_2987548-39_serialize.patch
    patch unexpectedly ends in middle of line
    patch: **** Only garbage was found in the patch input.
Production build 0.71.5 2024