I have a custom module with a form class, where I am trying to inject a custom service to use within it's submit method:
namespace Drupal\my_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\my_module\CustomManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
class CustomForm extends FormBase{
private $custom_manager;
function __construct(CustomManager $custom_manager) {
$this->custom_manager = $custom_manager;
}
public static function create(ContainerInterface $container) {
return new static(
// Load the service required to construct this class.
$container->get('my_module.manager')
);
}
.....
public function submitForm(array &$form, FormStateInterface $form_state) {
// Test service.
$this->custom_manager->test();
}
}
When I submit the form, I get the following error:
Fatal error: Call to a member function test() on null
It seems like my custom service hasn't been instantiated as expected, since the $custom_manager property is null.
Strange thing is when I debug the constructor, the service IS being instantiated properly.
Has anyone had this issue before? I can instantiate the service via the global Drupal class, but apparently doing the dependency injection is best practice.
Thanks in advance!