phpdrupal-7drupal-rules

Drupal: Writing taxonomy reference field using rules and custom php code


I have a taxonomy vocabulary kategorie like this:

The vocabulary has a custom field with IDs like this: 957214d2-ce39-423d-aeb1-32f2e8b972f6, so every term and parent term has an ID (which is NOT the tid!).

I have a content type with a referenced taxonomy field kategorie. Also there is an array field called kategorieTempId, and the values are the same like in the kategorie-taxonomy. The number of IDs in that array represent the hierarchical order of the terms and parent terms. So, if the node should be in kategorie -Kat01 -> Child01, there would be two IDs in kategorieTempId, one for the parent, one for the child term.
Now I need to get the ID of the child term, than get the taxonomy term from the vocabulary and write it into the referenced term field.

What I did so far:
Set up a rule, which is fired before saving a node, using the action Fetch entity by property to get the taxonomy terms from the vocabulary into an array. Then I add an action Execute custom PHP code to find the child tid and write it into a field called katReturn.
Here is the codeI use (I'm a total php-beginner, and I don't know, if this is an elegant way to do it, but it works):

$anzahl = 0; //counter for hierarchy  
foreach ($kat_id_fetched as $kat_term) { // fill two arrays  
  $tid[$anzahl] = $kat_term->tid; // array with termID  
  $parentTerm_id[$anzahl] = db_query("SELECT {parent} FROM {taxonomy_term_hierarchy} WHERE tid = $kat_term->tid")->fetchField(); // array with parent-termID  
  ++$anzahl;  
};
foreach ($tid as $item) { // check if tid is parent  
  $anzahl = 0;  
  if (!in_array($item, $parentTerm_id)) {
    $kat_child = $item; // if not in parent-array, save tid
    $node->field_kat_return['und'][0]['value'] = $item;
    break;  
  };
  ++$anzahl;  
};  

So now I know the tid of the child term and I want to write it into the reference taxonomy field, but I don't get it. The code I try is:

foreach ($kat_id_fetched as $kat) {
  if ($kat->tid == $returned_kat) {
    $node->field_kategorie[] = $kat;
    break;
  };
};

I hope, I made clear what I want. As I said before, my php-skills are limited and I appreciate any help, which points me to the right direction. Thanx.


Solution

  • The solution is simpler than I thought. Thanks to @Clive
    I can save the term-id, which is stored in $item, directly without going through a third foreach-loop.

    $node->field_kat_return['und'][0]['tid'] = $item;