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

评论 (写第一个评论)