With Drupal 8 I was programmatically setting the display of the fields, depending on the values of a custom configuration form, using the following function:

  private function setViewModeImageCabeceraHidden($entityType, $bundle, $fieldname)
  {

	  // Get selected view modes for bundle
	$view_modes = \Drupal::service('entity_display.repository')
	  ->getViewModeOptionsByBundle($entityType, $bundle);

	// Get format settings for field
	foreach (array_keys($view_modes) as $view_mode)
	{
	  $settings = array();
	  $settings['type'] = 'hidden';

	  \Drupal::entityTypeManager()
		  ->getStorage('entity_view_display')
		  ->load($entityType. '.' . $bundle . '.' .  $view_mode)
		  ->setComponent($fieldname, $settings)
		  ->save();
	}
  }

But after updating to Drupal 9, when that function is called the following error messages is thrown:

Drupal\Component\Plugin\Exception\PluginNotFoundException: The "hidden" plugin does not exist. Valid plugin IDs for Drupal\Core\Field\FormatterPluginManager are: bg_image_formatter, color_field_formatter_text...

It used to work, but apparently it can't be set hidden as type. So, is there another way to tell Drupal programmatically to hide the field in the view mode?

Comments

taote created an issue. See original summary.

taote’s picture

Issue summary: View changes
larowlan’s picture

Status: Active » Needs review

I had this too.

Use 'region' hidden instead of type. See workbench moderation for the example

taote’s picture

Status: Needs review » Fixed

Yes, that's it! Thanks a lot larowlan.

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.

taote’s picture

larowland solution worked, but now under Drupal 9.0.6 setting the region to hidden moves the field to the hidden region in the settings for that content type, but when the node is viewed the field is visible, unless you save the display settings form for that type.

Has anything changed?

larowlan’s picture

you will likely need to removeComponent() too

taote’s picture

larowland where exactly do I have to do that? Before setComponent? Can you show me in the code please?

Thanks a lot.

taote’s picture

I got it, I did:

  private function setViewModeImageCabeceraHidden($entityType, $bundle, $fieldname)
  {

	  // Get selected view modes for bundle
	$view_modes = \Drupal::service('entity_display.repository')
	  ->getViewModeOptionsByBundle($entityType, $bundle);

	// Get format settings for field
	foreach (array_keys($view_modes) as $view_mode)
	{
	  $settings = array();
	  $settings['type'] = 'hidden';

	  \Drupal::entityTypeManager()
		  ->getStorage('entity_view_display')
		  ->load($entityType. '.' . $bundle . '.' .  $view_mode)
		  ->setComponent($fieldname, $settings)
		  ->removeComponent($fieldname)
		  ->save();
	}
  }

And that works. Thanks again.