Question

I sync data from external source to my Drupal installation. I have problem when i'm adding taxonomy term relation to my newly created node.

I'm syncing cars and if manufacturer name ($name in code) is not in vocabulary, it will get added to it. If it already exists, tid attached to node.

This works perfectly with terms like Ferrari or Volkswagen. But then there is Mercedes-Bentz. For some reason EntityFieldQuery doesn't seem to find it from vocabulary, because this code, when run in loop, creates Mercedes-Bentz terms over and over again.

I guess the problem is that dash between words. I'd like to see SQL clause behind EntityFieldQuery, but i don't have entire drupal setup up when i'm running this, so modules like Devel are not loaded. And I don't have a clue how to inspect SQL otherwise.

I'm more than grateful of suggestions how to debug or how to solve this. Every link is appreciated.

Here is my code:

$query = new EntityFieldQuery();
$result = $query
    ->entityCondition('entity_type', 'taxonomy_term')
    ->propertyCondition('name', $name) // $name = manufacturer, like "Ferrari"
    ->propertyCondition('vid', 2)
    ->execute();

if(!empty($result))
{
    $tmp = array_pop($result['taxonomy_term']);
    $node->field_brand[LANGUAGE_NONE][0]['tid'] = $tmp->tid;
}
else
{
    $term = new stdClass();
    $term->vid = 2;
    $term->name = $name
    taxonomy_term_save($term);
    $node->field_brand[LANGUAGE_NONE][0]['tid'] = $term->tid;
}
Was it helpful?

Solution

There is a way to do the same with taxonomy_get_term_by_name(), but i guess it is not preferred way and the solution explained in question should be right for this.

I think we are seeing Drupal bug here. But for others trying to do that, here is the solution:

$test = taxonomy_get_term_by_name($name);
// It should be full of unique names, so no need to go through all of them
if(!empty($test))
{
    $tmp = array_pop($test);
    $node->field_brand[LANGUAGE_NONE][0]['tid'] = $tmp->tid;
}
else
{
    $term = new stdClass();
    $term->vid = 2;
    $term->name = $name;
    taxonomy_term_save($term);
    $node->field_brand[LANGUAGE_NONE][0]['tid'] = $term->tid;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top