title: Drupal: Writing taxonomy reference field using rules and custom php code
body: <p>I have a taxonomy vocabulary <strong><em>kategorie</em></strong> like this:  </p>
  
  <ul>
  <li>Kat01<br>
  <ul>
  <li>Child01</li>
  <li>Child02 </li>
  </ul></li>
  <li>Kat02<br>
  <ul>
  <li>Child01</li>
  <li>Child02 </li>
  </ul></li>
  </ul>
  
  <p>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!).  </p>
  
  <p>I have a content type with a referenced taxonomy field <strong><em>kategorie</em></strong>. Also there is an array field called <strong><em>kategorieTempId</em></strong>, 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 <strong><em>kategorieTempId</em></strong>, one for the parent, one for the child term.<br>
  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.  </p>
  
  <p>What I did so far:<br>
  Set up a rule, which is fired before saving a node, using the action <strong><em>Fetch entity by property</em></strong> to get the taxonomy terms from the vocabulary into an array. Then I add an action <strong><em>Execute custom PHP code</em></strong> to find the child tid and write it into a field called <strong><em>katReturn</em></strong>.<br>
  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):  </p>
  
  <pre><code>$anzahl = 0; //counter for hierarchy  
  foreach ($kat_id_fetched as $kat_term) { // fill two arrays  
    $tid[$anzahl] = $kat_term-&gt;tid; // array with termID  
    $parentTerm_id[$anzahl] = db_query("SELECT {parent} FROM {taxonomy_term_hierarchy} WHERE tid = $kat_term-&gt;tid")-&gt;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-&gt;field_kat_return['und'][0]['value'] = $item;
      break;  
    };
    ++$anzahl;  
  };  
  </code></pre>
  
  <p>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:  </p>
  
  <pre><code>foreach ($kat_id_fetched as $kat) {
    if ($kat-&gt;tid == $returned_kat) {
      $node-&gt;field_kategorie[] = $kat;
      break;
    };
  };
  </code></pre>
  
  <p>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.</p>