Problem/Motivation

When you reorder the taxonomy terms with the "Reset to alphabetical" button, the weight of all the terms is reset to 0 (seeable in database), but their cache is not cleared.

If you edit a node just afterwards, the entity will jump back to the bottom of the list because it gets its previous weight back (all others have a weight of 0 in the backend).

Proposed resolution

Clear the cache of all term entities when reseting to alphabetical order to make sure the weight is correctly reset.

Comments

tonifisler created an issue. See original summary.

wengerk’s picture

Hello @tonifisler !

As you suggest, I also think it's due to the cached previous weight. As we can see, when you click on the button "Reset to alphabetical" you still see the previous weight instead of 0 (the button will reset every term in the vocabulary to weight=0).

I think it's because the Drupal\taxonomy\TermStorage::resetWeights() alter the database without refreshing/releasing the entity cache.

I'm working into a patch that fix this using the internal reset cache.

wengerk’s picture

StatusFileSize
new922 bytes

Here is my first drafted patch ! Let's test it via testbot !

wengerk’s picture

Status: Active » Needs review
borisson_’s picture

Status: Needs review » Needs work
Issue tags: -cache, -taxonomy +Needs tests, +D8 cacheability

This needs a test that proves that this behavior is now correct, and that it was broken before.

wengerk’s picture

Version: 8.5.x-dev » 8.6.x-dev
StatusFileSize
new10.67 KB
new10.67 KB

As suggested by @borisson_, I created a tests coverage for this issue.
On my research, I found this coverage was already partially done by Drupal\taxonomy\Tests\TermTest::TaxonomyTermReorderTest but the coverage reset the cache manually, so, of course, it works perfectly.

One more things, the previous coverage was made with SimpleTest - so I decide to update it as BrowserTest. I remove Drupal\taxonomy\Tests\TermTest::TaxonomyTermReorderTest & create a new TaxonomyTestBase class for this coverage Drupal\Tests\taxonomy\Functional::TaxonomyTermReorderTest.

In the new coverage, I assert the UI is up-to-date when using reordering & I also asserts the non-usage of cached weight (the purpose of this issue).

I post here 2 patches, one that should fail (it contains the new coverage w/o the cache fix from #3) & a second patch that should work.

Let's try it with the Testbot.

PS: I also reroll the code for Drupal 8.6.x

wengerk’s picture

Status: Needs work » Needs review
borisson_’s picture

Status: Needs review » Needs work
Issue tags: -Needs tests

This looks good, removing the needs test tag. I'm not sure if this issue violates the scope, because it now does 2 things. The testbot does seem to agree with this though. I couldn't get git to recognize this with --color-words to figure out what exactly changed between the 2 tests.

I did find a couple of things though, so nitpicks ahead.

  1. +++ b/core/modules/taxonomy/tests/src/Functional/TaxonomyTermReorderTest.php
    @@ -0,0 +1,134 @@
    +  /**
    +   * Modules to enable.
    +   *
    +   * @var array
    +   */
    +  public static $modules = ['taxonomy'];
    

    This doc comment can be replaced with

    {@inheritdoc}

  2. +++ b/core/modules/taxonomy/tests/src/Functional/TaxonomyTermReorderTest.php
    @@ -0,0 +1,134 @@
    +    // Fetch the created terms in the default alphabetical order, i.e. term1,
    +    // term2, term3 & term4.
    +    $taxonomy_storage->resetCache();
    

    Should we reset the cache here?

  3. +++ b/core/modules/taxonomy/tests/src/Functional/TaxonomyTermReorderTest.php
    @@ -0,0 +1,134 @@
    +    // Reload terms to prevent usage of cached loaded terms.
    +    $taxonomy_storage->resetCache();
    ...
    +    // Reload terms to prevent usage of cached loaded terms.
    +    $taxonomy_storage->resetCache();
    

    I think we should remove the resetCache here.

wengerk’s picture

Thanks for the review quick review !

I will work on 1 & 2 to fix this asap.

About 3, yes we have to "reset the cache manually" here because we already load the terms previously - loadMultiple - so the already loaded terms contains old weight, parents, depth & it's in the cache. loadTreeuse an internal cache so the terms aren't loaded anymore but just retrieve from it.
By precautions I try to remove those both, but the test fail on the following lines (also those 2 resets were already in the code of the initial SimpleTest).

Finally, I know it does 2 things, but it's necessary to complete this issue. Decoupling this test from the old SimpleTests is quite logical & it doesn't create any technical debts, it's the only test that exists about reordering terms so nothing else is impacted (it's not a partial porting of similar tests SimpleTest/BrowserTest). What do you think ?

borisson_’s picture

Awesome, your explenation makes sense. I agree about the move to BTB.

wengerk’s picture

StatusFileSize
new10.53 KB
new10.53 KB
new940 bytes

As suggested by borisson_ in #10

1. Removed the whole public static $modules because it's already done by inherited Class TaxonomyTestBase.
2. Remove unnecessary clear-cache (mistake I made during coding this new Class).

wengerk’s picture

Status: Needs work » Needs review

Status: Needs review » Needs work

The last submitted patch, 11: 2956594-11-should-fail.patch, failed testing. View results

wengerk’s picture

Status: Needs work » Needs review

Move to need review again, bot move it to - need works for failing tests - but it was on purpose :).

Status: Needs review » Needs work

The last submitted patch, 11: 2956594-11-should-fail.patch, failed testing. View results

wengerk’s picture

Status: Needs work » Needs review

The tests works as design. Move as Need Review.

Version: 8.6.x-dev » 8.7.x-dev

Drupal 8.6.0-alpha1 will be released the week of July 16, 2018, which means new developments and disruptive changes should now be targeted against the 8.7.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

wengerk’s picture

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

wengerk Working fine as i tested.

catch’s picture

Status: Reviewed & tested by the community » Needs work
+++ b/core/modules/taxonomy/src/Form/VocabularyResetForm.php
@@ -83,6 +83,11 @@ public function submitForm(array &$form, FormStateInterface $form_state) {
+    $this->entity->save();

We should be able to clear the entity cache without saving the entity here, i.e. $this->entity->resetCache().

vj’s picture

Status: Needs work » Needs review
StatusFileSize
new4.4 KB

Updated patch as suggested by catch. Used termStorage instead of entity to reset cache.

wengerk’s picture

Many thanks @Vj for your help ! I'm a bit concern about termStorage I think it will remove the cache of the whole storage instead of this vocabulary only. So it will invalidate internal cache of others taxonomies. I think it could be a problem on big web-applications (performances issues as we reset the cache).

Also, I think it was a mistake but you remove the testTermReorder ? I would suggest to keep the coverage.

@catch, I try to use resetCache but it doesn't exists on Vocabulary.

Call to undefined method Drupal\taxonomy\Entity\Vocabulary::resetCache()

I try the following ways & here the results:

  • Vocabulary::save code from #11 - the test PASS
  • VocabularyStorage::resetCache with & without the entity as parameter - the tests FAIL
  • TermStorage::resetCache code from #21 without params - the test PASS

What is the best approach then ? it seems only TermStorage::resetCache & $this->entity->save(); works on our case - which is the best approach then ?

wengerk’s picture

Status: Needs review » Needs work
wengerk’s picture

StatusFileSize
new10.51 KB
new827 bytes
new5.93 KB

Here the patch from #21 with the initial coverage.

I upload 2 interdiff to show that I only add from #21 the inital coverage (which was on #11).

We still need to choose - I think - a better approach to reset the cache see #22. @catch any idea ?

wengerk’s picture

Status: Needs work » Needs review
vj’s picture

oops @wengerk Sorry it was removed by mistake

lfilipov’s picture

@wengerk This patch is quite useful. We had the same issues. Sadly we are using BLT which has an issue with Drupal core which is above 8.5.6 and we had to fix this without applying the patch.

I will add our solution just in case someone is in our case:


/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id === 'taxonomy_vocabulary_confirm_reset_alphabetical') {
    $form['actions']['submit']['#submit'][] = 'my_module_submit_taxonomy_reset';
  }
}

/**
 * Submit callback.
 *
 * @param array $form
 *   Form render array.
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 *   Form state object.
 */
function my_module_submit_taxonomy_reset(array $form, FormStateInterface $form_state) {
  Cache::invalidateTags(['taxonomy_term_values']);
  views_invalidate_cache();
}

@wengerk Really useful patch!

tonifisler’s picture

The patch needs to be rerolled for 8.6.10.

Asacolips’s picture

Issue tags: -Needs reroll
StatusFileSize
new10.93 KB

Rerolled for 8.6.10.

tonifisler’s picture

Issue tags: +drupalmountaincamp

Version: 8.7.x-dev » 8.8.x-dev

Drupal 8.7.0-alpha1 will be released the week of March 11, 2019, which means new developments and disruptive changes should now be targeted against the 8.8.x-dev branch. For more information see the Drupal 8 minor version schedule and the Allowed changes during the Drupal 8 release cycle.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

wengerk’s picture

StatusFileSize
new10.93 KB
new10.07 KB

Here a reroll for 8.9.x

wengerk’s picture

Issue tags: -drupalmountaincamp +DrupalCon Amsterdam 2019

Add the tag Amsterdam as I work on this issue during the DrupalCon 2019 in Amsterdam.

rachel_norfolk’s picture

Issue tags: -DrupalCon Amsterdam 2019 +Amsterdam2019

retagging

Status: Needs review » Needs work

The last submitted patch, 33: 2956594-33--FAIL.patch, failed testing. View results

gido’s picture

StatusFileSize
new10.95 KB
new10.1 KB

Fixing the deprecation notice in the test.

gido’s picture

Status: Needs work » Needs review
alexrayu’s picture

Confirmed the issue. #37 resolved the issue.

UPD: There is a side effect. When the list is reset to alphabetical order, weight values are all assigned zeros, but then if the list is saved, strange weights get assigned, and the list order is garbled.

alexrayu’s picture

Debugged the issue. The alphabetical order is a separate bug, this issue just uncovers it but not directly related.

I would suggest reviewing it separately and working on the alphabetic order sorting bug in it's corresponding ticket. https://www.drupal.org/project/drupal/issues/2928661

krzysztof domański’s picture

Status: Needs review » Needs work

1. It should be removed.
* @group failingtest

2. Instead of this order:

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  $this->termStorage->resetWeights($this->entity->id());

  $this->messenger()->addStatus($this->t('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]));

  // Reset the entity cache and prevent usage of cached terms weight.
  $this->termStorage->resetCache();

  $this->logger('taxonomy')->notice('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]);
  $form_state->setRedirectUrl($this->getCancelUrl());
}

Let's separate the code thematically:

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  $this->termStorage->resetWeights($this->entity->id());
  // Reset the entity cache and prevent usage of cached terms weight.
  $this->termStorage->resetCache();

  $this->messenger()->addStatus($this->t('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]));
  $this->logger('taxonomy')->notice('Reset vocabulary %name to alphabetical order.', ['%name' => $this->entity->label()]);
  $form_state->setRedirectUrl($this->getCancelUrl());
}

3. Once created, terms will be sorted alphabetically.

$this->createTerm($this->vocabulary, ['name' => 'Alpha']);  // tid 1
$this->createTerm($this->vocabulary, ['name' => 'Beta']); // tid 2
$this->createTerm($this->vocabulary, ['name' => 'Charlie']); // tid 3
$this->createTerm($this->vocabulary, ['name' => 'Delta']); // tid 4

Let's set the order of terms randomly. For example:

$this->createTerm($this->vocabulary, ['name' => 'Delta']); // tid 1
$this->createTerm($this->vocabulary, ['name' => 'Beta']); // tid 2
$this->createTerm($this->vocabulary, ['name' => 'Alpha']);  // tid 3
$this->createTerm($this->vocabulary, ['name' => 'Charlie']); // tid 4
krzysztof domański’s picture

I think it will remove the cache of the whole storage instead of this vocabulary only. So it will invalidate internal cache of others taxonomies.

Re #22. Rights. We can fix it. The cache will reset for the entities with the given ids:

// Reset the entity cache and prevent usage of cached terms weight.
$ids = [];
foreach ($this->termStorage->loadTree($this->entity->id()) as $term) {
  $ids[] = $term->tid;
}
$this->termStorage->resetCache($ids);
mschudders’s picture

StatusFileSize
new11.58 KB

Took patch #37 added #43 and added Cache tag invalidation.

Why?
We had a view listing the terms.

However

$this->termStorage->resetCache($ids);

reset cache entries for
values:taxonomy_term:**

We needed:
taxonomy_term:**

without the "values".

Now my questions remains is this expected behaviour and is this extra Cache invalidation necessary or is the resetCache faulty?

Thanks
Patch attached.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

kriboogh’s picture

In stead of doing a loadtree we should use a entity query to just fetch the ids. This way it doesn't load all terms in memory. Loadtree can be a problem when having a huge amount of terms in a vocabulary (+10k terms).

So #43 should be:

    // Reset terms for this vocabulary. We don't use loadMultiple for
    // performance reasons and limit memory consumption.
    $entityQuery = $this->termStorage->getQuery();
    $entityTypeKey = $this->termStorage->getEntityType()->getKey('bundle');
    $entityQuery->condition($entityTypeKey, $this->entity->id());
    $termIds = $entityQuery->execute();
    $this->termStorage->resetCache($termIds);
kriboogh’s picture

StatusFileSize
new11.65 KB

Reroll to 9.2.0 stable.

mschudders’s picture

StatusFileSize
new11.65 KB

reroll of #44

Now my questions remains is this expected behaviour and is this extra Cache invalidation necessary or is the resetCache faulty?

Thanks
Patch attached.

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

mschudders’s picture

StatusFileSize
new11.67 KB

reroll 9.3.0

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

antoniya’s picture

alexpott’s picture

Status: Needs work » Closed (duplicate)
yogesh_kambari’s picture

Patch for drupal version 10.5.0.