Score:1

Custom field formatter fails in create()

cn flag

PHPStorm, PHP 7.4 IDE highlights $container->get('date.formatter'), with

"Expected parameter of type '\Drupal\Core\Datetime\DateFormatterInterface', 'object' provided"

This function is an exact copy of the core TimestampFormatter (which also shows the error)

/**
 * {@inheritdoc}
 */
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
  return new static(
    $plugin_id,
    $plugin_definition,
    $configuration['field_definition'],
    $configuration['settings'],
    $configuration['label'],
    $configuration['view_mode'],
    $configuration['third_party_settings'],
    $container->get('date.formatter'),
    $container->get('entity_type.manager')->getStorage('date_format')
  );
}

The __construct is looking for a DateFormatterInterface (see below) and not sure how this works in core, but my "viewElements" is never firing since this error started.

public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, **DateFormatterInterface $date_formatter**, EntityStorageInterface $date_format_storage) {

What is the proper container->get to use to return a proper date.formatter and not an object which causes the create to fail without any errors logged that I can see?

Score:1
cn flag

Your code is fine, but you can remove the warnings by installing the PHPStorm Symfony plugin.

It teaches the IDE how to resolve the correct class from the service name you provide to $container->get().

cn flag
Thanks @Clive as I've seen you answer thousands of questions over many years. Kudos. Strange thing is I have my field set to format based on this plugin but it is not called anymore when the node is viewed. It was working some time ago but not now. I have breakpoints set in the constructor and the viewElements but they never fire.
cn flag
Adjusted IDE and warning did go away. I guess I misunderstand how the formatter works for a field when editing a node. My dateTime field format must change based on a condition. Does the formatter not interact with the widget that displays the date? Should I ask this as a separate question?
Hermann Schwarz avatar
cn flag
Don't forget to the 'Symfony' plugin :-).
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.