I am trying to write a custom module, which defines a field formatter plugin, but when I visit the Manage display page, I get this error:
Fatal error: Cannot declare class Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter, because the name is already in use in /var/www/sites/drupalroot/web/modules/custom/my_formatter/src/Plugin/Field/FieldFormatter/MyFormatter.php on line 0
I've compared my module to several other working field formatter plugins and can't seem to figure out what I'm missing.
My module directory is laid out like this:
web/modules/custom/my_formatter/
├── my_formatter.info.yml
├── my_formatter.module
├── src
│ └── Plugin
│ └── Field
│ └── FieldFormatter
│ └── MyFormatter.php
└── templates
└── my-formatter.html.twig
My info file:
name: My Formatter
type: module
description: 'Do some fun stuff.'
package: Field types
core: 8.x
dependencies:
- field
- file
And my MyFormatter.php
file:
<?php
/**
* @file
* Contains \Drupal\my_formatter\Plugin\Field\FieldFormatter\MyFormatter.
*/
namespace Drupal\my_formatter\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;
/**
* Plugin implementation of the 'my' formatter.
*
* @FieldFormatter(
* id = "my",
* label = @Translation("My Formatter"),
* field_types = {
* "file"
* }
* )
*/
class MyFormatter extends FileFormatterBase {
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = [
'#theme' => 'my_formatter',
'#my_var' => 'Hello',
];
}
return $elements;
}
}
Any help would be greatly appreciated.
manage display
page, choose the new formatter and save, no problem. You probably have some cached stuff or duplicated code somewhere? Error says it's already in use...MyFormatter
if you copied the class from else where and let it with the same name it may cause this take a llok at this drupal.org/project/taxonomy_access_fix/issues/2943950 i know it's different from your case but the same issue, they just change the class name in the patch, try with changeMyFormatter
toMyFormatterTest
and see if it works