0

I need to override Validator class from Telephone Validations contrib module. I tried the both static and dynamic methods described here: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services

namespace Drupal\mymodule;

use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
use Drupal\Core\DependencyInjection\ServiceModifierInterface;
// @note: You only need Reference, if you want to change service arguments.
use Symfony\Component\DependencyInjection\Reference;

/**
 * Modifies the language manager service.
 */

class MyServiceProvider extends ServiceProviderBase {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides language_manager class to test domain language negotiation.
    // Adds entity_type.manager service as an additional argument.
    $definition = $container->getDefinition('telephone_validation.validator');
    $definition->setClass('Drupal\mymodule\MyValidator');

    $definition->addArgument(new Reference('country_manager'));
  }

}

and also static:

services:
  telephone_validation.validator:
    class: Drupal\mymodule\MyValidator
    arguments: ['@country_manager']

but it the both methods do not work, Drupal still uses Validator class form oroginal module

Also I tried modified method described here: https://github.com/RikdeBoer/service_overrider

class MyServiceProvider implements ServiceModifierInterface {

  /**
   * {@inheritdoc}
   */
  public function alter(ContainerBuilder $container) {
    // Overrides language_manager class to test domain language negotiation.
    // Adds entity_type.manager service as an additional argument.
    $definition = $container->getDefinition('telephone_validation.validator');
    $definition->setClass('Drupal\mymodule\MyValidator');

    $definition->addArgument(new Reference('country_manager'));
  }

}

The result is the same: MyValidator class is not used instead of default Validator class. So what I am doing wrong?

2
  • 2
    See the linked doc for the correct class name, try MymoduleServiceProvider. – 4k4 Apr 7 '20 at 9:04
  • thanks, I somehow skipped the description: the name of this class is required to be a CamelCase version of your module's machine name followed by ServiceProvider – Sergey Kravchenko Apr 7 '20 at 9:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.