AccountForm::form() contains the following code.

  $form['#cache']['tags'] = $config->getCacheTags();
  $language_interface = \Drupal::languageManager()->getCurrentLanguage();

Instead of calling \Drupal::languageManager(), it should use its own $this->languageManager property, which is initialized from the class constructor.

public function __construct(EntityRepositoryInterface $entity_repository, LanguageManagerInterface $language_manager, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, TimeInterface $time = NULL) {
  parent::__construct($entity_repository, $entity_type_bundle_info, $time);
  $this->languageManager = $language_manager;
}

There is code in the same method that uses $this->languageManager, so this seems a forgetfulness in one of the past commits.

  $form['language'] = [
    '#type' => $this->languageManager->isMultilingual() ? 'details' : 'container',
    '#title' => $this->t('Language settings'),
    '#open' => TRUE,
    // Display language selector when either creating a user on the admin
    // interface or editing a user account.
    '#access' => !$self_register,
  ];

Comments

kiamlaluno created an issue. See original summary.

saurabh.rocksoul’s picture

Status: Active » Needs review
StatusFileSize
new633 bytes

Here is the patch for the issue, please review.

avpaderno’s picture

Status: Needs review » Reviewed & tested by the community
alexpott’s picture

Title: AccountForm::form() calls \Drupal::languageManager() instead of using $this->languageManager » Reduce \Drupal usage in user module run-time code
Status: Reviewed & tested by the community » Needs work

If we're fixing this form for \Drupal use then let's also fix $config = \Drupal::config('user.settings'); - that can be $config = $this->config('user.settings');

Plus in other similar issues about \Drupal usage we've pushed back and asked this to be done on the module level - so can we need to do

  • \Drupal\user\RegisterForm::submitForm()
  • \Drupal\user\RegisterForm::save()
  • \Drupal\user\Plugin\Block\UserLoginBlock::build() - here we'll need to inject the form builder service, configFactory and the redirect.destination service - so that'll need to have a deprecation code path too
  • \Drupal\user\Plugin\EntityReferenceSelection\UserSelection::entityQueryAlter - will need to inject the service
  • \Drupal\user\Plugin\Validation\Constraint\UserMailRequiredValidator::validate - will need to implement Drupal\Core\DependencyInjection\ContainerInjectionInterface
  • \Drupal\user\Plugin\views\argument_default\CurrentUser - will need to implement ::create()
  • \Drupal\user\Plugin\views\field\Permissions::query - will need to inject the service
  • \Drupal\user\Plugin\views\filter\Name::adminSummary - will need to implement ::create()
hardik_patel_12’s picture

Status: Needs work » Needs review
StatusFileSize
new19.16 KB
new19.8 KB

Covered all points as mentioned by @alexpott , Kindly review.

Status: Needs review » Needs work

The last submitted patch, 5: 3110333-5.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

swatichouhan012’s picture

Assigned: Unassigned » swatichouhan012
swatichouhan012’s picture

Assigned: swatichouhan012 » Unassigned
Issue tags: +VbContribution2020
StatusFileSize
new18.67 KB
new718 bytes

We can not used $this in static method i have removed from above page, kindly review

swatichouhan012’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 8: 3110333-8.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

hardik_patel_12’s picture

StatusFileSize
new20.51 KB
new2.98 KB

Solving test case failures , kindly review a new patch.

hardik_patel_12’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 11: 3110333-11.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

avpaderno’s picture

The tests are failing because of errors similar to the following one.

Drupal\Tests\user\Functional\Views\HandlerFilterUserNameTest::testUserNameApi
PHPUnit\Framework\Exception: Fatal error: Declaration of Drupal\user\Plugin\views\filter\Name::create(Symfony\Component\DependencyInjection\ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) must be compatible with Drupal\Core\DependencyInjection\ContainerInjectionInterface::create(Symfony\Component\DependencyInjection\ContainerInterface $container) in /var/www/html/core/modules/user/src/Plugin/views/filter/Name.php on line 20

I am not sure if the error is caused by this patch or other changes in the code.

There are also coding standard issues in the patch. (See https://dispatcher.drupalci.org/job/drupal_patches/34651/artifact/jenkin....)

avpaderno’s picture

+  public function __construct(EntityTypeManagerInterface $entity_type_manager, AccountInterface $current_user){
+    $this->entityTypeManager = $entity_type_manager;
+    $this->currentUser = $current_user;
+  }

There is a missing space between the parentheses at the end of the first line.

+  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountInterface $current_user){
+    parent::__construct($configuration, $plugin_id, $plugin_definition);
+    $this->currentUser = $current_user;

There is a missing space between the parentheses at the end of the first line.

hardik_patel_12’s picture

StatusFileSize
new20.16 KB
new1.38 KB

Kindly review a new patch.

hardik_patel_12’s picture

Status: Needs work » Needs review
avpaderno’s picture

The error I shown in comment #14 is caused by this patch: A class that extends the PluginBase class cannot also implement the ContainerInjectionInterface interface. PluginBase::create() and ContainerInjectionInterface::create() have different parameters.

hardik_patel_12’s picture

@kiamlaluno thanks for reviewing the patch , yes i have noticed that and removed the implementation of ContainerInjectionInterface and tried to make compatible with PluginBase::create() in patch #16.

avpaderno’s picture

Status: Needs review » Needs work
+  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountInterface $current_user){
+    parent::__construct($configuration, $plugin_id, $plugin_definition);
+    $this->currentUser = $current_user;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container , array $configuration, $plugin_id, $plugin_definition) {
+    return new static(
+      $configuration,
+      $plugin_id,
+      $plugin_definition,
+      $container->get('current_user')
+    );
+  }

There is still a missing space between ) and {; there is also an extra space between $container and the following comma. Search for ){: The patch contains 3 of them.

hash6’s picture

Assigned: Unassigned » hash6
hash6’s picture

Assigned: hash6 » Unassigned
Status: Needs work » Needs review
StatusFileSize
new43.22 KB
new25.59 KB
avpaderno’s picture

Status: Needs review » Needs work

The patch includes unrelated changes.

hash6’s picture

hash6’s picture

Assigned: Unassigned » hash6
StatusFileSize
new20.17 KB
new2.63 KB
hash6’s picture

Assigned: hash6 » Unassigned
Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 25: 3110333-25.patch, failed testing. View results

hardik_patel_12’s picture

Status: Needs work » Needs review
StatusFileSize
new20.2 KB
new302 bytes

Tries to solve failure test , kindly review a new patch.

swatichouhan012’s picture

StatusFileSize
new21.27 KB
new2.54 KB

Hii @Hardik_Patel_12, @kiamlaluno
i have solved codesniffer issue regarding comment #15, also tries to solve test cases.

Status: Needs review » Needs work

The last submitted patch, 29: 3110333-29.patch, failed testing. View results
- codesniffer_fixes.patch Interdiff of automated coding standards fixes only.

swatichouhan012’s picture

patch #28 got pass, kindly avoid #29, i am moving for review of #28.

swatichouhan012’s picture

Status: Needs work » Needs review
kishor_kolekar’s picture

Status: Needs review » Needs work

There are some more coding standards that need to fixed in #28

phpcs --standard=DrupalPractice,Drupal core/modules/user/src/Plugin/views/filter/Name.php
-----------------------------------------------------------------------------------------------------------------------------
FOUND 10 ERRORS AFFECTING 9 LINES
-----------------------------------------------------------------------------------------------------------------------------
  57 | ERROR | [ ] Missing member variable doc comment
  59 | ERROR | [x] Missing function doc comment
  79 | ERROR | [x] Missing function doc comment
  90 | ERROR | [x] Missing function doc comment
 103 | ERROR | [x] Missing function doc comment
 133 | ERROR | [x] Missing function doc comment
 134 | ERROR | [x] Inline comments must start with a capital letter
 144 | ERROR | [x] Missing function doc comment
 145 | ERROR | [x] Inline comments must start with a capital letter
 145 | ERROR | [x] Inline comments must end in full-stops, exclamation marks, question marks, colons, or closing parentheses
---------------------------------------------------------------------------------------------------------------------------
phpcs --standard=DrupalPractice,Drupal core/modules/user/src/Plugin/views/field/Permissions.php
----------------------------------------------------------------------------------------------------
FOUND 6 ERRORS AFFECTING 4 LINES
----------------------------------------------------------------------------------------------------
 131 | ERROR | [x] Whitespace found at end of line
 132 | ERROR | [x] Line indented incorrectly; expected 2 spaces, found 4
 143 | ERROR | [x] Line indented incorrectly; expected 2 spaces, found 4
 143 | ERROR | [ ] Public method name "Permissions::render_item" is not in lowerCamel format
 143 | ERROR | [x] Expected 1 space before opening brace; found 0
 145 | ERROR | [x] Closing brace indented incorrectly; expected 4 spaces, found 2
----------------------------------------------------------------------------------------------------
PHPCBF CAN FIX THE 5 MARKED SNIFF VIOLATIONS AUTOMATICALLY
----------------------------------------------------------------------------------------------------
kishor_kolekar’s picture

Status: Needs work » Needs review
StatusFileSize
new9.11 KB
new27.39 KB

kindly review a new patch.

neelam_wadhwani’s picture

Assigned: Unassigned » neelam_wadhwani
neelam_wadhwani’s picture

Assigned: neelam_wadhwani » Unassigned
init90’s picture

Status: Needs review » Needs work

Thanks for work here. Some minor problems from the last patch:

  1. +++ b/core/modules/user/src/AccountForm.php
    @@ -101,7 +101,7 @@ public function form(array $form, FormStateInterface $form_state) {
    -    // Only show name field on registration form or user can change own username.
    +    // Only show name field on registration form user can change own username.
    

    I think there should be:

    "Only show name field on registration form or when user can change own username."

  2. +++ b/core/modules/user/src/Plugin/Block/UserLoginBlock.php
    @@ -33,6 +36,27 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
    +   * Contains the configuration object factory.
    

    I think that "The config factory." will be better here.

  3. +++ b/core/modules/user/src/Plugin/Block/UserLoginBlock.php
    @@ -33,6 +36,27 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
    +   * Contains the configuration object factory.
    
    @@ -47,11 +71,20 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
    +   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
    

    $config_factory instead of $config will be more correctly here

  4. +++ b/core/modules/user/src/Plugin/Block/UserLoginBlock.php
    @@ -47,11 +71,20 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
    +   *   The configuration factory object.
    

    "The config factory."

  5. +++ b/core/modules/user/src/Plugin/EntityReferenceSelection/UserSelection.php
    @@ -59,11 +67,14 @@ class UserSelection extends DefaultSelection {
    -  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, Connection $connection, EntityFieldManagerInterface $entity_field_manager = NULL, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, EntityRepositoryInterface $entity_repository = NULL) {
    

    Required params should be passed before optional.

    But in that case, we can have potential BC problems(unsure about it).

  6. +++ b/core/modules/user/src/Plugin/views/field/Permissions.php
    @@ -75,15 +87,21 @@ public function init(ViewExecutable $view, DisplayPluginBase $display, array &$o
    +   * Add anything to the query that we might need to.
    

    We should use {@inheritdoc} here.

  7. +++ b/core/modules/user/src/Plugin/views/field/Permissions.php
    @@ -111,6 +129,17 @@ public function preRender(&$values) {
    +   * Renders a single item of a row.
    

    Here also should be {@inheritdoc}

  8. +++ b/core/modules/user/src/Plugin/views/filter/Name.php
    @@ -16,8 +18,52 @@
    +   * Provide a simple textfield for equality.
    

    Here also should be used {@inheritdoc}

  9. +++ b/core/modules/user/src/Plugin/views/filter/Name.php
    @@ -38,6 +84,9 @@ protected function valueForm(&$form, FormStateInterface $form_state) {
    +   * Validate the options form.
    

    {@inheritdoc} should be used

  10. +++ b/core/modules/user/src/Plugin/views/filter/Name.php
    @@ -62,6 +114,9 @@ public function acceptExposedInput($input) {
    +   * Validate the exposed handler form.
    

    {@inheritdoc} should be used

  11. +++ b/core/modules/user/src/Plugin/views/filter/Name.php
    @@ -92,8 +147,11 @@ public function validateExposed(&$form, FormStateInterface $form_state) {
    +   * Perform any necessary changes to the form values prior to storage.
    

    {@inheritdoc} should be used

  12. +++ b/core/modules/user/tests/src/Unit/Plugin/Validation/Constraint/UserMailRequiredValidatorTest.php
    @@ -144,7 +144,8 @@ public function providerTestValidate() {
    -    $cases['Existing users without an email should be ignored if the current user is an administrator.'] = [$items->reveal(), FALSE, TRUE];
    +    $cases['Existing users without an email should be ignored if the current user is an administrator.']
    +      = [$items->reveal(), FALSE, TRUE];
    

    The previous variant looks more correctly for me

kishor_kolekar’s picture

StatusFileSize
new27.54 KB
new7.08 KB

@init90 patch adjusted according to #37 please review the patch.

kishor_kolekar’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 38: run-time-code-3110333-38.patch, failed testing. View results

neelam_wadhwani’s picture

StatusFileSize
new26.64 KB
new26.64 KB

Hello @init90
Updated the changes as asked for.
Kindly review patch.

neelam_wadhwani’s picture

Status: Needs work » Needs review
jungle’s picture

StatusFileSize
new779 bytes
new26.64 KB
+++ b/core/modules/user/src/Plugin/Block/UserLoginBlock.php
@@ -47,11 +71,20 @@ class UserLoginBlock extends BlockBase implements ContainerFactoryPluginInterfac
    *   The route match.
+   * @param \Drupal\Core\Config\ConfigFactoryInterface config_factory
+   *   The config factory.

- * @param \Drupal\Core\Config\ConfigFactoryInterface config_factory
+ * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory

neelam_wadhwani’s picture

jungle’s picture

+++ b/core/modules/user/src/Plugin/Block/UserLoginBlock.php
@@ -145,7 +181,7 @@ public function build() {
-   * #lazy_builder callback; renders a form action URL including destination.
+   * Lazy_builder callback; renders a form action URL including destination.

Any thought on this? Unexpected change or change it to the below.

The #lazy_builder callback renders a form action URL including destination.

Change lazy_builder to Lazy_builder does not make sense even the first letter must be uppercase, or no _

- Lazy_builder
+ Lazy builder

init90’s picture

Status: Needs review » Needs work

Any thought on this? Unexpected change or change it to the below.

In core mostly used: "#lazy_builder callback;", so I think the optimal way doesn't change comment in the patch.

Some points which need to fix:

  1. +++ b/core/modules/user/src/AccountForm.php
    @@ -101,7 +101,7 @@ public function form(array $form, FormStateInterface $form_state) {
    +    // Only show name field on registration form or when user can change own username.
    

    Now the comment is longer than 80 charsets, so the part of it should be moved to the next line.

  2. +++ b/core/modules/user/src/Plugin/EntityReferenceSelection/UserSelection.php
    @@ -36,6 +37,13 @@ class UserSelection extends DefaultSelection {
    +   * Contains the configuration object factory.
    

    The config factory.

  3. +++ b/core/modules/user/src/Plugin/EntityReferenceSelection/UserSelection.php
    @@ -59,11 +67,14 @@ class UserSelection extends DefaultSelection {
    +   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
    

    $config_factory instead of $config

  4. +++ b/core/modules/user/src/Plugin/EntityReferenceSelection/UserSelection.php
    @@ -59,11 +67,14 @@ class UserSelection extends DefaultSelection {
    +   *   The configuration factory object.
    

    The config factory.

  5. +++ b/core/modules/user/src/Plugin/EntityReferenceSelection/UserSelection.php
    @@ -59,11 +67,14 @@ class UserSelection extends DefaultSelection {
    +  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, AccountInterface $current_user, Connection $connection, EntityFieldManagerInterface $entity_field_manager = NULL, EntityTypeBundleInfoInterface $entity_type_bundle_info = NULL, EntityRepositoryInterface $entity_repository = NULL, ConfigFactoryInterface $config) {
    

    As I wrote earlier we shouldn't pass the required parameter after optional, but I don't know the correct solution in that case. Ignore the point yet.

  6. +  /**
    +   * Renders a single item of a row.
    +   *
    +   * @param int $count
    +   *   The index of the item inside the row.
    +   * @param mixed $item
    +   *   The item for the field to render.
    +   *
    +   * @return string
    +   *   The rendered output.
    +   */
    +   public function render_item($count, $item) {
    

    Here should be {@inheritdoc} instead of comment.

  7. +++ b/core/modules/user/src/RegisterForm.php
    @@ -103,7 +103,12 @@ public function save(array $form, FormStateInterface $form_state) {
    +    $this->logger('user')->notice('New user: %name %email.',
    +        [
    +          '%name' => $form_state->getValue('name'),
    +          '%email' => '<' . $form_state->getValue('mail') . '>',
    +          'type' => $account->toLink($this->t('Edit'), 'edit-form')->toString(),
    +        ]);
    

    It can be a bit nicer:

    $this->logger('user')->notice('New user: %name %email.', [
      '%name' => $form_state->getValue('name'),
      '%email' => '<' . $form_state->getValue('mail') . '>',
      'type' => $account->toLink($this->t('Edit'), 'edit-form')->toString(),
    ]);
    
kishor_kolekar’s picture

Status: Needs work » Needs review
StatusFileSize
new26.74 KB
new4.48 KB

@init90 Updated the changes please review the patch .

Status: Needs review » Needs work

The last submitted patch, 47: 3110333-47.patch, failed testing. View results

avpaderno’s picture

This is just a quick review.

+    // Only show name field on registration form.
+    // or when user can change own username.

Making a comment shorter than 80 characters doesn't mean to put a period where it should not be. Also, the sentence is better as Show the name field only on registration forms or when users can change their own username.

-    //   set on the field, which throws an exception as the list requires
-    //   numeric keys. Allow to override this per field. As this function is
-    //   called twice, we have to prevent it from getting the array keys twice.
-
+    // set on the field,which throws an exception as the list requires
+    // numeric keys. Allow to override this per field. As this function is
+    // called twice, we have to prevent it from getting the array keys twice.

There is a missing space in field,which.

-   * #lazy_builder callback; renders a form action URL including destination.
+   * Lazy_builder callback; renders a form action URL including destination.

#lazy_builder is correct. The phrase should be the following.

The #lazy_builder callback: It renders a form action URL including the destination.

(It's a correct sentence and it's not longer than 80 characters.)

I also think that when the parameters of a class constructor are changed, there is something more to do, to provide BC.

jungle’s picture

Assigned: Unassigned » jungle

Working on this

jungle’s picture

Issue summary: View changes
StatusFileSize
new26.45 KB
new5.75 KB

Ingored #47, started from #43. Addressed concerns in #46 and #49

As I wrote earlier we shouldn't pass the required parameter after optional, but I don't know the correct solution in that case. Ignore the point yet.

ConfigFactoryInterface $config_factory = NULL) {

By changing the last one to optional.

The #lazy_builder callback: It renders a form action URL including the destination.

Exceeds 80 chars, break it to 3 lines -- Title, an empty line, the rest.

I also think that when the parameters of a class constructor are changed, there is something more to do, to provide BC.

I am thinking to do it without touch the class constructor(s) if BC matters.

See this post for more https://www.previousnext.com.au/blog/safely-extending-drupal-8-plugin-cl...

jungle’s picture

Assigned: jungle » Unassigned
Status: Needs work » Needs review
jungle’s picture

Issue summary: View changes

Revert IS changes unintendedly

init90’s picture

Status: Needs review » Needs work

Thanks, @jungle, looks really good.

One minor concern before RTBC, in UserLoginBlock we add RedirectDestination service but actually not use it. Let's start do it:)

abhisekmazumdar’s picture

Assigned: Unassigned » abhisekmazumdar

Re-rolling the patch.

abhisekmazumdar’s picture

Assigned: abhisekmazumdar » Unassigned
Status: Needs work » Needs review
StatusFileSize
new2.15 KB
new26.09 KB
avpaderno’s picture

Status: Needs review » Needs work

The BC is still missing. Simply adding new arguments to a service class is not possible. That is why Drupal core gives a default argument equal to NULL to the new arguments, and calls @trigger_error() if the argument is NULL.

   /**
-   * #lazy_builder callback; renders a form action URL including destination.
+   * The #lazy_builder callback.
+   *
+   * It renders a form action URL including the destination.

The short description should say more than The #lazy_builder callback. If The #lazy_builder callback: It renders a form action URL including the destination. is too long, it's enough to use #lazy_builder callback: Renders a form action URL including the destination. which is similar to the example (Page callback: Displays a list of content.) shown in API documentation and comment standards.

init90’s picture

@abhisekmazumdar thanks, changes looks good. I missed that renderPlaceholderFormAction is static method and we cannot use injected RedirectDestination for it.

@kiamlaluno according to that https://www.drupal.org/core/d8-bc-policy#constructors seems that we can change the constructor params for plugins, so if you agree with it, then we can solve your second notice about the comment and go further.

avpaderno’s picture

@init90 It's better to see what other patches that changed the parameters of a plugin class constructor did.

init90’s picture

@kiamlaluno you're right we really should provide BC layer. Here issue with a similar discussion #3018863: Make SystemMenuBlock's new constructor argument dependency optional

And issue which might make life much easier for such a situation: #3019332: Use final to define classes that are NOT extension points

As a resume, in order to move further need to solve points from #57

avpaderno’s picture

I thought it was necessary for those cases where the service container is not re-built, but I don't find any comment saying this is the reason for adding the code I reported in comment #57.

I am looking forward to when classes will be marked as final. Providing patches for Drupal will be much easier.

mradcliffe’s picture

I performed Novice Triage on this issue. I am leaving the Novice tag on this issue because I think that updating the issue summary with some of the latest discussions would be a good novice task.

xjm’s picture

Version: 9.0.x-dev » 9.1.x-dev
Status: Needs work » Postponed

Only bug fixes and allowed changes during the beta phase should be filed against 9.0.x. New features, API additions, and deprecations should be filed against 9.1.x.

The scope of this issue is also questionable. While the end goal of this issue is a good one (using properly injected services where possible), we should scope changes by concept, not by file group or module. So, it would be better to have an issue that looked at \Drupal::foo() usage on a per-method basis, rather than a per-module basis. And if the scope of that turns out to be too large, then we would break it down an additional level with (e.g.) "Use $this->foo() instead of \Drupal::foo() in form classes."

So, work on this should be postponed until we split up the issues more correctly. I suspect there is an existing meta issue for this, so I would search for that meta and use it to rescope this. Thanks!

jungle’s picture

xjm’s picture

Yep that's it, thanks @jungle!

xjm’s picture

Status: Postponed » Closed (duplicate)

Alright, thanks everyone for your contributions so far!

I am closing this as a duplicate of #2729597: [meta] Replace \Drupal with injected services where appropriate in core. You can use the work in the patches from this and similar issues as starting points for new issues scoped by concept.