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');

评论 (写第一个评论)