CCK text select list with taxonomy terms
Posted on October 6th, 2011 by Administrator. Filed in Drupal.I thought I would start sharing some snippets of code for some of the drupal projects im working on. I like many spend more time trying to google around for a solution to a problem and sometimes find a module thats created for the problem or 30 other people posting solutions and some work and some dont. Then of course I find my self just writing my own stuff based upon some of the data I collected.
Now of course I ran into an issue where I needed to create a form that has a select drop down list of taxonomy terms that when the form was submitted would save the taxonomy tid with this form as a cck field.
So quickly googling around I found Content Taxonomy which created a new cck type to use, but when testing it out I only found that it allows to see the list of terms in one vocabulary. Well this didn’t fit the bill for me since I needed to display all terms from all the vocabularies in my site.
I went to the api.drupal.com to look at the taxonomy api to see what functions I could use. It seems that taxonomy_get_tree would get the results I needed.
So I created a new cck field, choose “text” as the field type and select list as the form element.
All the way at the bottom under the allowed values list I have a box that allows me to enter PHP code in. This allow you to use any php type of code to create a key => value array to return that would then populate your select down down list.
So I know that I only had 5 vocabulary terms I needed to use and the id’s for these where 1-5, you can find these values by going to admin/content/taxonomy and hovering over the edit vocabulary link and it will show in the url the #
So with that in mind I started to quickly code up in my mind how I wanted to do this.
First I wanted to create an array of my vocabulary..
$vids = array(1,2,3,4,5);
Then using the taxonomy get tree api I simply created a foreach loop and pushed the results into a variable named $term.
foreach ($vids as $vid) {
$output = taxonomy_get_tree($vid,0,-1,1);
foreach ($output as $out) {
$term[$out->tid] = $out->name;
}
}
return $term;
The key thing here is if you want to make sure you get all the terms from the list of vocabulary you run it though another for each loop and assign the output object to the key and value of $term.
$term[$out->tid] = $out->name;\
This is the important part because the $out->tid (term id) is the key of the array and the $out->name is the text that gets displayed in the select drop down list.
With a simple return $term this will then generate a select list populated by term names and the values are the term id’s if you want to store them in your cck field.
Anyhow im sure their are many ways to do this but maybe this helps someone or pushes them in the right direction.
Tagged with: cck • drupal • select list • taxonomy_get_tree






