I am creating one custom form and in this form I need to use one service which are there in another module. I need to use that dependency injection based on condition which are there in configuration.
Conditions in Config Form:
- Use Custom1 Form
- Use Custom2 Form
If “Use Custom1 Form” enabled, then I need to use dependency injection.
namespace Drupal\test\Form;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symphony\Component\DependencyInjection\ContainerInterface;
use Drupal\custom_form1\Services\TestService;
/**
* Test forms.
*/
class TestForm extends ConfigFormBase {
/**
* PinCodeRegistration Object.
*
* @var Drupal\custom_form1\Services\TestService;
*/
protected $TestService;
/**
* Constructs a new pin code multistep form.
*
* @param Drupal\custom_form1\Services\TestService $test_service
* The service handler.
*/
public function __construct(TestService $test_service) {
$this->TestService = $test_service;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('custom_form1.form1_services')
);
}
}
How can I add use Drupal\custom_form1\Services\TestService;
based on conditions?
If the custom_form1 module isn't installed, I get an error. Any Idea how we need to avoid error and added dependency based on conditions?