Hack to Move Entities Without a Machine Name Through a Development Workflow

Hack to Move Entities Without a Machine Name Through a Development Workflow

It wasn't until recently that people began to use Drupal sites within very well structured development workflows. This move brought to light some decisions that have proven painful. Vocabularies and terms may be coupled tightly with a feature (so that neither makes sense to exist without the other) so that it makes sense to consider a vocabulary as code. There are times when taxonomy terms are clearly content within a system. Free tagging is the obvious example. If you engineer a Drupal site, you don't get much say in the matter. Vocabularies and terms are assigned auto-increment ids. The first term you create has a term id of 1, the second 2, and so on and so forth. When you reference that term, it must be referenced by an id. You'll say, "get me the term with the id of 8." Well, if you have a production site with free tagging enabled and members of the site use free tagging, you have quite a problem. You are trying to uniquely identify information across a distributed system. There is no safe way to numerically refer to a term that you have to create in development that is not on the production site. A UUID or a machine name would be great. But Drupal doesn't have that (yet). But you can cheat. Create a drupal variable and map that to a programmatically created entity that has a numeric id. Here is an example I ran into recently //first see if your vocabulary already exists. if (!array_key_exists( variable_get('my_vocab', -1), taxonomy_get_vocabularies()) ) { //programmatically create the vocabulary $vocab = array( 'name' => t('My vocabulary title'), 'description' => t('Bundled with my feature'), 'nodes' => array('mynodetype' => 1), 'hierarchy' => 1, 'relations' => 0, 'tags' => 0, 'multiple' => 0, 'required' => 0, 'weight' => 0, ); taxonomy_save_vocabulary($vocab); //the the generated id, taxonomy_save_vocabulary won't return it $v = db_fetch_object(db_query("SELECT * FROM {vocabulary} WHERE name='%s' AND description='%s'", t('My Vocabulary title'), t('Bundled with my feature'))); //map the id to a machine name variable_set('my_vocab', $v->vid); } And there you go. You can use that variable to refer to your vocabulary id by using variable_get in views and elsewhere. Just like that, you have taxonomy that is export-safe. Photo credit