Here’s a question from NDeveloper. He wants to know how to get the parent ID of a vocabulary entry using its label. A couple of words about vocabularies first.

A vocabulary is a list of labels that are used in the application to populate the various selection lists (drop-down, select or multi-select lists). A vocabulary can be used independently or it can be associated with other vocabularies to compose a multi-level list.

You could add one easily with Nuxeo Studio, just take a look at the documentation.

Now here’s a more technical definition:

A vocabulary is a specialized directory with only a few important columns that are used by Nuxeo Platform to display things like menus and selection lists.

In Nuxeo Platform, a directory is a source of (mostly) table-like data that lives outside of the VCS document storage database. A directory is typically a connection to an external data source that is also access by other processes than Nuxeo itself (therefore allowing shared management and usage).

So to answer that question, we’re going to use the directory API:

import java.util.HashMap;
import java.util.Map;

import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.runtime.api.Framework;

public class VocabularyExample {

public void fihdParentId() throws Exception {
// Open the directory
DirectoryService dirService = Framework.getService(DirectoryService.class);
Session directorySession ="nameOfMyVocabulary");
// Create a query filter
Map queryFilter = new HashMap();
queryFilter.put("label", "childLabel");
// Execute the query, wrapped in a DocumentModel list
// We might get many entries as we're doing a query on the label, not
// the id
DocumentModelList queryResult = directorySession.query(queryFilter);
// If you have a child vocabulary or a hierarchical one, it means the
// schema used for your directory is xvocabulary which has 5 columns
// named id, label, parent, obsolete, ordering. Let's assume the query
// returned only one entry.
DocumentModel entry = queryResult.get(0);
String parentId = entry.getProperty("xvocabulary:parent").getValue(

// It's of course much easier if you have the child id instead of the
// label because you don't need a query.
entry = directorySession.getEntry("childId");
parentId = entry.getProperty("xvocabulary:parent").getValue(

// Whatever you do, do not forget to close the directory session!

Don’t forget that it’s possible to have several entries with the same label. So it’s much better to use the child ID when possible.