Since the Drupal sniffer whines at you if you call \Drupal::service()
in your code, I have been trying to figure out how to use dependency injection on a widget I’ve been working on. Here’s what I’ve currently arrived at:
<?php
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\xois\SicsService;
use Symfony\Component\DependencyInjection\ContainerInterface;
class XoisSicSelect extends WidgetBase {
/**
* SICs service.
*
* @var \Drupal\xois\SicsService
*/
protected $sicsService;
/**
* {@inheritdoc}
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, SicsService $sicsService) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
$this->sicsService = $sicsService;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('xois.sics')
);
}
}
Pretty much the standard DI pattern, no? Only difference is that WidgetBase takes a whole load of construct parameters already.
Problem is, it doesn’t work. When run, it gives this delightful error:
The website encountered an unexpected error. Please try again later.
Recoverable fatal error: Argument 6 passed to Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect::__construct() must be an instance of Drupal\xois\SicsService, none given, called in /var/www/docroot/core/lib/Drupal/Core/Field/WidgetPluginManager.php on line 125 and defined in Drupal\xois\Plugin\Field\FieldWidget\XoisSicSelect->__construct() (line 35 of modules/xois/src/Plugin/Field/FieldWidget/XoisSicSelect.php).
Anyone got an idea on how to accomplish this?