Hướng dẫn lấy Field Value ở Node để làm Class Name trong Drupal 8

Hướng dẫn lấy Field Value ở Node để làm Class Name trong Drupal 8

As a theme developer, I often find myself needing to control the appearance of content on a per-entity basis (for example, assigning a color to a node with a certain category). The easiest way that I've found to accomplish this is by adding a class to the entity based on a field value. Setting this up in Drupal 8 is simple, and will allow content editors (or non-developers) the ability to control the appearance of individual entities without needing to access the code behind the scenes. 

>> Hướng dẫn tạo 1 Form table trong Drupal 8 không có phân trang

>> Thực hiện query, tạo pagination và element Type là table trong Drupal 8

Here's how it's done:

1. Create the field

Start by creating the field you'd like to use to control the class. If you already have a field in place, skip on ahead to step 2!

Be sure to use a field type that makes sense. I've found that the Text (Plain) type works well for fully-customizable class names, and List (Text) works well for providing a select box with a few curated options for content editors to pick from. 

2. Get the value of the field

In a preprocess function in your theme file, you'll start by getting the value of the field. In order to avoid errors, you should also include checks to see if the entity has the field and if the field has a value

$node = $variables['node'];

// Check if the node has the field and the field has a value.
if ($node->hasField('field_name') && !$node->get('field_name')->isEmpty()) {

  // Get the value of the field.
  $field_value = $node->get('field_name')->get(0)->getValue();
}

3. Convert the field value to a safe class name

Because class names cannot contain spaces or special characters (among other things), we need to make sure that our field value is formatted correctly. This is especially important when using a freeform text field, where user error is likely. Luckily, Drupal 8 contains a built-in function just for this purpose!

// Convert the field value to a safe class name
$class_name = Html::cleanCssIdentifier($field_value);

Be sure to remember to include the use statement at the top of your theme file.

use Drupal\Component\Utility\Html;

4. Add the class as an attribute

Now that we have our safe class name, all that's left to do is assign that value as a class attribute on our entity.

// Add the class to the entity as an attribute
$variables['attributes']['class'][] = $class_name;

The full code:

use Drupal\Component\Utility\Html;

/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  // Check if the node has the field and the field has a value.
  if ($node->hasField('field_name') && !$node->get('field_name')->isEmpty()) {

    // Get the value of the field.
    $field_value = $node->get('field_name')->get(0)->getValue();

    // Convert the field value to a safe class name.
    $class_name = Html::cleanCssIdentifier($field_value);

    // Add the class to the entity as an attribute.
    $variables['attributes']['class'][] = $class_name;
  }
}
Bạn thấy bài viết này như thế nào?: 
Average: 7.3 (12 votes)
Ảnh của Tommy Tran

Tommy owner Express Magazine

Drupal Developer having 9+ year experience, implementation and having strong knowledge of technical specifications, workflow development. Ability to perform effectively and efficiently in team and individually. Always enthusiastic and interseted to study new technologies

  • Skype ID: tthanhthuy

Bình luận (0)

 

Add Comment

Filtered HTML

  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Các thẻ HTML được chấp nhận: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Tự động ngắt dòng và đoạn văn.

Plain text

  • No HTML tags allowed.
  • Các địa chỉ web và email sẽ tự động được chuyển sang dạng liên kết.
  • Tự động ngắt dòng và đoạn văn.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Advertisement

 

jobsora

Dich vu khu trung tphcm

Dich vu diet chuot tphcm

Dich vu diet con trung

Quảng Cáo Bài Viết

 
Hướng dẫn định dạng file văn bản năm 2015

Hướng dẫn định dạng file văn bản năm 2015

Nhiều khi bạn loay hoay không biết làm thế nào để quay được 1 trang ngang trong cả đống trang văn bản

Loa dock “hầm hố” của Yamaha dành cho iOS

Loa dock “hầm hố” của Yamaha dành cho iOS

Mới đây, hãng Yamaha đã công bố mẫu loa dock di động mới nhất của mình ra thị trường với tên gọi Yamaha PDX-11. Đây là mẫu dock được thiết kế cho iPod và iPhone của Apple.

Amazon Kindle Fire review

Amazon Kindle Fire review

The Amazon Kindle Fire, as mentioned in this review, promises a new dawn with an affordable-for-all Android tablet that just might end Apple's reign

Công ty diệt chuột T&C

 

Diet con trung