1

I'm attempting to create a taxonomy term inside a Form plugin like so

$term = Term::create([
    'name' => 'my taxonomy term',
    'vid'  => 'vocabulary_to_put_it_in',
]);
$term->save();

When I do so I receive an error

Fatal error: Class 'Drupal\my_module\Form\Term' not found

My gut is telling me that I'm not including the namespace like I should but I'm not sure how to actually figure out how to discover that. I'm creating nodes by using

\Drupal\node\Entity\Node::create

And I receive no errors for that. I'm assuming that it's because I'm using \Drupal\node\Entity\ before it, but I was only able to figure that out by looking at examples. I looked at this page https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Controller%21TaxonomyController.php/class/TaxonomyController/8.1.x and saw the class hierarchy class \Drupal\taxonomy\Controller\TaxonomyController but when using

\Drupal\taxonomy\Controller\TaxonomyController\Term::create 

I still get an error saying

Fatal error: Class 'Drupal\taxonomy\Controller\TaxonomyController\Term' not found

If it is true, that the reason why it is failing, is because I'm not including the right namespace, then how do I use the official documentation to figure out what I should be including? Or is there something else I'm missing entirely?

1 Answer 1

3

I was able to discover the namespace by finding the documentation for the Term class here.

https://api.drupal.org/api/drupal/core%21modules%21taxonomy%21src%21Entity%21Term.php/class/Term/8.1.x

And on that page there's a namespace section that said Drupal\taxonomy\Entity so I used

\Drupal\taxonomy\Entity\Term::create

and that worked.

So I believe in order to find the right namespace to use, you have to find the page for the class that is using the method. In this case Term. And then find the namespace section and put that before the class when you are using a method of it.

(This might be obvious to everyone else, but it took me a bit to figure out)

2
  • 3
    Or get a decent IDE, type Term, and look at the auto completed results to decide which is the correct class to use. It will then even add the use statement for you. That's much quicker and more intuitive than trying to find pages in online documentation
    – Clive
    Dec 5, 2016 at 17:27
  • 3
    Yes, IDEs like PHPStorm will autocomplete. D8 dev with no IDE will take a lot longer.
    – Kevin
    Dec 5, 2016 at 17:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.