Do you want to know how to Drupal?

Let's Drupal

Hook

How to hide a local task (tab) in Drupal?

Quite often we want to have a parent tab to be selected, but the sublevel tasks are not displayed or we just want remove completely some tabs for user of specific roles. 

There are two ways to do it:

The first option is to use hook_menu_local_tasks_alter

function your_module_local_tasks_alter(&$local_tasks) {
  unset($local_tasks['id_of_local_tasks']);
}

This code will remove your tab completely from the system, it means it will not be displayed anywhere, but sometimes we want to hide the tab only on the specific pages

The second option is to use hook_menu_local_tasks_alter

function your_module_menu_local_tasks_alter(&$data, $route_name) {
  $routes = ['entity.node.canonical']; // add your routes to this array and your tab will be hidden for this routes
  if (in_array($route_name, $routes)) {
    unset($data['tabs'][0]['id_of_local_task']); 
  }
}

 


How to alter options for dropdown (select input) in Drupal

Sometimes we need to alter or restrict some options for dropdown of entity reference field. One of the solution to use views and provide views entity reference widget, but in some cases the logic would be too complex and we will have to implement custom plugins for views. The second solution could be just replace options for dropdown widget. For this we need implement "hook_field_widget_form_alter"

/**
 * Implements hook_field_widget_form_alter().
 */
function your_module_field_widget_form_alter(
   if (!empty($field_definition) && $field_definition->getName() == 'fut_collection') {
    $element['#options'] = _your_module_get_input_options();
  }
}

/**
 * Gets group collection options.
 */
function _your_module_get_input_options() {
   $options = [];
   // here your custom logic to get ids.
   $items = Term::loadMultiple($ids);
   if ($items ) {
      // a default empty value.
      $options['_none'] = t('- None -');
      foreach ($items as $item) {
        $options[$item->id()] = $item->getName();
      }
   }

   return $options;
}

Keep in mind that you have to use the entity ids of entity type for your entity reference field. Also, if you want to provide the default value without any value, you should use this code:

$options['_none'] = t('- None -');

and not like

$options[''] = t('- None -');

In other case you can face some unexpected bugs