D7 Tutorial: Set taxonomy terms if files are attached to specified fields

Last updated on
30 November 2019

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

The problem: A content type with 3 different file field-fields, we can call them: Front, Right, Left. Sometimes all these 3 file fields have a file attached, sometimes only 2 of these fields and sometimes just one of them. I need to set taxonomy terms depending on if a file field has a file attached, or remove it if it hasn't.

The solution:
1) Add a new rule
2) Set event to "Before saving content"
3) Set condition: "Content is of type" to the name of the content type that you wish to manipulate.
4) Set action to "Execute custom PHP code":

//dsm($node); // to see the node object need devel module installed

//resetting
$node->field_tags['und'][0]['tid'] = 0;

if (isset($node->field_file_front['und'][0]['display'])) {
  $node->field_tags['und'][1]['tid'] = 10;
} else {
  $node->field_tags['und'][1]['tid'] = 0;
}

if (isset($node->field_file_right['und'][0]['display'])) {
  $node->field_tags['und'][2]['tid'] = 12;
} else {
  $node->field_tags['und'][2]['tid'] = 0;
}

if (isset($node->field_file_left['und'][0]['display'])) {
  $node->field_tags['und'][3]['tid'] = 11;
} else {
  //$node->field_tags['und'][3]['tid'] = 0;
}

//dsm($node); // to see the node object need devel module installed
return array("node" => $node);

$node->field_tags should be changed to the name of your node reference field. 10, 11, 12 is the corresponding term ids of the terms that are to be set depending on if files are attached or not.

Rules forms can be used to hide the taxonomy reference field to the end user.

Help improve this page

Page status: No known problems

You can: