Skip to main content

Hướng dẫn thay đổi Title của Page trong Drupal 8 và 9

Nếu bạn muốn hay đổi Title của Page trong Drupal 8 và 9 sử dụng snippet đơn giản thì dưới đây là một số cách bạn có thể tham khảo các cách sau đây để làm điều đó.

Sử dụng hook preprocess trong template 

/**
 * Implements hook_preprocess_HOOK().
 */
function MYMODULE_preprocess_page_title(&$variables) {

    if ($YOUR_LOGIC) {
        $variables['title'] = 'Custom Title';
    }
}

Sử dụng hook node trong view 

/**
* Implements hook_ENTITY_TYPE_view_alter().
*/
function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if ($YOUR_LOGIC) {
        $build['#title'] = $entity->get('field_display_name')->getString();
    } 
}

ví dụ: bạn muốn thay đổi user title

function mymodule_user_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
    if ($entity->getEntityTypeId() == 'user') {  
        $build['#title'] = $entity->get('field_first_name')->getString();
    }
}

Sử dụng trong Controller hoặc Hook_form_altter

if ($YOUR_LOGIC) {
  $request = \Drupal::request();
  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
     $route->setDefault('_title', 'New Title');
  }
}