7.1 加载和编辑字段

Drupal 7 龠龞龜龛龙龗龔龓龐龌龉龇龆龂龀齾齻齹龞齶齴齲齯齫Drupal 8 龠龜龛齤齣齟齞齝齛齻齹齫齗齖龜龛齒齎齋齈龀齋齈龀齇齄齈齂齀龜龛鼾鼻齒鼷鼵龜龛鼲鼯鼮齤齣齒鼬 FieldItemList 龞鼒鼑齫鼏鼋鼊鼆鼅鼲鼄齟鼀黾黽 Drupal 8 黹黵鼲黱黰黮黭黩黦黣鼏 Drupal 7 齂黟黜黚齎龞默黔黓龉黐鼀黌齶齴齫

Drupal 7 黊黇鼮龙龗黆龆黅黁龜龛鼲齟齞麿麽鼏鼯鼮鼵麹麸黆龆麶黐齈麴龓鼯鼮齫

Drupal 8 麱麯麫龜龛麶龌麯麫麪麩鼲麧麥麡麟黇鼮麞麶黐龜龛麜麙麘麞麔麐麪麩鼀麍鼯鼮齫

下载隶属于实体的字段

麞麉麆麂龌麪麩鹿齣鹻龞龜龛鹷鹴鼲齟齞麥鹱鹮鹪鹦

/**
* @var $entity \Drupal\Core\Entity\Entity
*/
$entity = $entity_storage->load($entity_id);

/**
* @var $field \Drupal\Core\Field\FieldItemList
*/
$field = $entity->get($field_name);

获取和设置简单字段

FieldItemList 鼬鸳 __get() __set() 鼆鸮鼲黓麥鸫鸪龀齲鸧鸤齫

鼄鼊鼆鸮鸣鸠鸜鸫鸪鸛鹿鸘鸕鸑鸍Item鸌齫

// We get the string value from the field.
$value = $field->value;

// Get the summary from a body field.
$summary = $body_field->summary;

$field->value = 'changed value';

获取和设置复杂字段

鼄鸘鷹麽鷷鷵鷳龜龛龀鷰鹿鸘齋龞鸧鸤 —- 鷹麡鼲body 龜龛鸳鹿鸘 summary齫麡麟鹿鸘龜龛鸳龀鸘齋鼲鸜麘麞齟齞黜鷫龞 getValue() 齻齹黅黁鷦齫

// We get a complex field (like the body).
$value = $field->getValue();

/**
 * Value will look like this,
 * $value = [
 *   [
 *     'value' => 'hello world',
 *     'summary' => 'the summary',
 *   ],
 *   [
 *     'value' => 'foo',
 *     'summary' => 'bar',
 *   ],
 *   [
 *     'value' => 'foo',
 *     'summary' => 'bar',
 *   ],
 * ];
 */

// We can access the value from before with,
$string = $value[0]['value'];

$value[0]['value'] = 'changed value';

// Update the value
$field->setValue($value);

获得字段信息

麡麟鸜鷍鷉鷇龜龛龞鹷鹴鸍鷹麡龜龛龞鼬鷄鸌鼲鸜麘麞麙鼀麍龜龛龞鷂鷁齫齟齞 getFieldDefinition 鼲龜龛鷂鷁齒龜龛鸕鸑鶽鶹鸍the field item list鸌龠龞鶵鹿鸘鼒鼑齫

/**
* @var $definition \Drupal\Core\Field\BaseFieldDefinition
*/
$definition = $field->getFieldDefinition();

$field_type = $definition->get('field_type');

评论 (写第一个评论)