Here is a form using DI for $this->entity_type_manager
There is also a radio-button with Ajax (I have added the code as it is maybe the reason of my problem)
class myForm extends FormBase { private ?EntityTypeManagerInterface $entity_type_manager=NULL; public function __construct(DrupalCoreEntityEntityTypeManagerInterface $entity_type_manager) { $this->entity_type_manager=$entity_type_manager; } public static function create(ContainerInterface $container) { return new static( $container->get('entity_type.manager'), ); } public function buildForm(array $form, FormStateInterface $form_state) { // keep the value in $form_state to be used in submit $form_state->set('entity_type_manager', $this->entity_type_manager); ... // Maybe the Ajax component is the problem $form['container'] = [ '#type' => 'container', '#prefix' => '<div id="ajax-wrapper">', '#suffix' => '</div>', 'my_radio' => [ '#type' => 'radios', '#options' => ["option1","option2"], '#required' => TRUE, '#default_value' => $type_of_bo, '#ajax' => [ 'callback' => [$this, 'ajaxGetInvestmentHandler'], 'wrapper' => 'ajax-wrapper', 'event' => 'click input', ], ], ... ]; } static public function ajaxGetInvestmentHandler(array $form, FormStateInterface $form_state) { return $form['container']; } public function submitForm(array &$form, FormStateInterface $form_state) { // $this->entity_type_manager is NULL // $form_state->get('entity_type_manager') is also NULL ... } ... }
As you can see in the submit
, $this->entity_type_manager
is NULL and $form_state->get('entity_type_manager')
is also NULL.
What is wrong?