Score:0

Term weight is a string?

iq flag

I am getting a taxonomy through a REST plugin, and I return it as an array keyed by id, since I also have to access it by id. But when I display the values in an HTML select, I have to order it by weight, so I am ordering it in a javascript function. I got unexpected results, and I traced it to the fact that Term::weight() apparently returns a string rather than an int, or at least this is what this test code shows:

use Drupal\taxonomy\Entity\Term;
[...]
    $term = Term::load(407) ;
    echo $term->name->value, " has weight ", $term->getWeight(), PHP_EOL ;
    echo "and it is a ", gettype($term->getWeight()), PHP_EOL ;

The above code is in a drush script, and when I run it I get

# /var/www/mysite/svil/vendor/bin/drush scr test.php 
Location to be defined has weight 0
and it is a string

The documentation for Term::getWeight() claims that it returns an integer. I looked at the code, but the implementation is simply

  public function getWeight() {
    return $this->get('weight')->value;
  }

which says nothing about the type of the result.

Of course I can simply apply intval(), but I would like to know what's going on here.

misterdidi avatar
de flag
Hi, perhaps this thread might help you understanding why values are always returned as string : https://drupal.stackexchange.com/questions/305408/fielditemlistgetvalue-always-returns-a-string-even-for-a-boolean-field?rq=1
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.