outputting a form with a file widget through a hook_preprocess breaks the widget

Created on 28 April 2016, about 8 years ago
Updated 30 August 2023, 10 months ago

There appears to be some sort of problem with file (and image) widgets getting broken by passing through the theme system too many times.

I had the following setup:

- a View's page display
- in my theme's hook_preprocess_views_view(), outputting a rendered block config entity
- the block's plugin was custom code, outputting an entity form

This all worked fine, until an file field was added to the entity type. At that point, attempting to add a file broke the form: validation failed on it, with the error message that the file field was required, even if a file had been set into the widget.

My hook_preprocess_views_view() was along the lines of:

    $block_view_builder = \Drupal::entityManager()->getViewBuilder('block');
    $block = \Drupal\block\Entity\Block::load('mycustomblock');
    $build = $block_view_builder->view($block);
    $variables['mycustomblock'] = $build;

// A custom twig.html took care of outputting {{mycustomblock}}.

and the custom block plugin's build() was:

    $entity = $this->entityManager->getStorage('node')->create($values);
    return $this->entityFormBuilder->getForm($entity, 'default');

The following workaround in hook_preprocess_views_view() fixes the problem:

    $config = [];
    $plugin_block = \Drupal::service('plugin.manager.block')
      ->createInstance('mycustomblock_plugin', $config);
    $build = $plugin_block->build();
    $variables['mycustomblock'] = $build;

This outputs the same thing, but doesn't get run through the Block entity's theming.

Thus it seems that the trip through #theme => block is what causes the problem for the file widget.

πŸ› Bug report
Status

Postponed: needs info

Version

11.0 πŸ”₯

Component
File moduleΒ  β†’

Last updated 3 days ago

Created by

πŸ‡¬πŸ‡§United Kingdom joachim

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.

  • πŸ‡¬πŸ‡§United Kingdom catch

    I can't imagine much has changed in the meantime, but I think this needs an example module doing the same thing to show the bug (which would then be the test coverage for the fix).

Production build 0.69.0 2024