获取字段实例的设置


8

field_info_instance()Drupal 8 的等效功能是什么?

默认字段设置作为配置存储在诸如field.field.ENTITYTYPE.BUNDLE.FIELDNAME.yml之类的文件中,但是如何获取其当前值?

Answers:


9

使用entity_field.manager服务,您可以获取BaseFieldDefinition类的数组。该服务也可以注入,但是对于复制粘贴工作代码,您可以执行以下操作:

$bundle_fields = \Drupal::getContainer()->get('entity_field.manager')->getFieldDefinitions($entity_type, $bundle);
$field_definition = $bundle_fields[$field_name];
$catalog_id = $field_definition->getSetting($setting_name);

4
如果您有实体并且正在使用该实体,则还可以使用$ entity-> getFieldDefinitions()访问实体对象的字段定义。
贝尔迪尔'16

2

使用字段实例:

$settings = $field->getFieldDefinition()->getSettings();

例如,在字段小部件中:

public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
  $element = [];

  // Get the settings.
  $settings = $items[$delta]->getFieldDefinition()->getSettings();

  // ... build render array

  return $element;
}

0

我想从字段定义中获取类型和标签。这不起作用:

$setting_name = 'label';
$label = $field_definition->getSetting($setting_name);

这工作:

$label = $field_definition->getLabel();
$type = $field_definition->getType();

0

获取字段配置的最简单方法是使用EntityTypeManager

$entity_type = 'node';// node, taxonomy_term, taxonomy_vocabulary, ...
$bundle = 'article';// the content type machine name
$field = 'field_article_tags';// the field machine name

$fieldConfig =  \Drupal::entityTypeManager()
  ->getStorage('field_config')
  ->load($entity_type . '.' . $bundle . '.' . $field);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.