All logged in users can add a forum node. The current topic is determined by a field in another node (nid=77) and set to the default value for the node being created by this form.

While this all works perfectly for admin users, authenticated users see only '- Select a value -' as the default value. I verified with set_message that the code obtains the correct default value of the taxonomy term. What could be causing this? Note in case of authenticated user, <option value="_none"> is the only item in the select list. For admin user, the select list contains all of the taxonomy items with the correct option value set to selected="selected".

use Drupal\taxonomy\Entity\Term;
use Drupal\Core\Form\FormStateInterface;

function MYMODULE_form_alter(&$form, FormStateInterface $form_state, $form_id) {

  if ($form_id != 'node_forum_form') {
    return FALSE;
  }
  else {

    $nid = 77; // Node ID 77 contains this week's topic in field_topic
    $node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);

    $current_topic_id = $node->get('field_topic')->getString(); // get the TID
    $term = Term::load($current_topic_id); // load the term from the taxonomy
    $the_topic = $term->getName(); // get the Term Name for the debug message

    $form['field_topic']['widget']['#title'] = 'The Current Topic';
    $form['field_topic']['widget']['#default_value'] = $current_topic_id;
    $form['field_topic']['widget']['#disabled'] = TRUE;

    drupal_set_message('current_topic_id: ' . $current_topic_id . ', termName: ' .  $the_topic);

    return $form;
  }
}

For admin role, developer tools show <option value="44" selected="selected">Name of the entity</option> as well as all the other values/names of taxonomy items.

For authenticated user role, only one item is listed, <option value="_none" selected="selected">Select a value</option>.

Your code isn't manipulating the select field's options ($form['field_topic']['#options']), so the difference in options is something outside your code (you can confirm this by commenting out your form manipulation code).

If this is the case, you'll have to investigate why non-admin auth users are seeing empty options; it seems like it would have something to do with user permissions on your taxonomy, field, or something else that would prevent auth users from querying the valid terms for your taxonomy field.

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.