/**
* Add new fields.
*/
function MYMODULE_update_10000() {
$content_type = 'article';
$csv_file_path = DRUPAL_ROOT . '/_profile_fields.csv';
$node_type = NodeType::load($content_type);
if (!$node_type) {
throw new \Exception("COntent type '$content_type' not found.");
}
if (!file_exists($csv_file_path)) {
throw new \Exception("CSV file not found $csv_file_path.");
}
$fields = [];
if (($handle = fopen($csv_file_path, 'rb')) !== FALSE) {
$header = fgetcsv($handle, NULL, '|');
while (($data = fgetcsv($handle, NULL, '|')) !== FALSE) {
$fields[] = array_combine($header, $data);
}
fclose($handle);
}
foreach ($fields as $field) {
$field_name = $field['machine_name'];
$label = $field['label'];
$description = $field['description'];
$existing_field = FieldStorageConfig::loadByName('node', $field_name);
if (!$existing_field) {
FieldStorageConfig::create([
'field_name' => strtolower($field_name),
'entity_type' => 'node',
'type' => 'string',
'settings' => [
'max_length' => 255,
],
])->save();
}
$field_instance = FieldConfig::loadByName('node', $content_type, $field_name);
if (!$field_instance) {
FieldConfig::create([
'field_name' => strtolower($field_name),
'entity_type' => 'node',
'bundle' => $content_type,
'label' => $label,
'description' => $description,
'required' => FALSE,
])->save();
}
\Drupal::service('entity_display.repository')->getFormDisplay('node', $content_type)
->setComponent($field_name, [
'type' => 'string_textfield',
'weight' => 0,
])
->save();
\Drupal::service('entity_display.repository')->getViewDisplay('node', $content_type)
->setComponent($field_name, [
'label' => 'above',
'type' => 'string',
'weight' => 0,
])
->save();
}
}