0

Using Drupal 8 i am importing data from an external source and creating the node programmatically from the controller:

$node = Node::create(array(
  'type' => 'article',
  'title' => 'some title'
));
$node->save();

I want to add some extra field with the external id (e.g. "3cru_81pazBBRbj5e8LZkZ").

Adding of the field should happen programmatically within the module without the need of the user having to add it via the ui.

I have been reading up on this but i have come to the point that tutorials have confused me more then helped me.

Any help would be greatly appreciated.

2
  • "extra data" is stored in fields - add a new field, probably a text field for that sort of string, and you'll be able to add a value for it in the associative array just like type, title, etc
    – Clive
    Commented Jun 16, 2016 at 8:40
  • The adding of the field should happen programmatically within the module. I will update my question. Commented Jun 16, 2016 at 8:43

2 Answers 2

0

Field entities can be created via FieldConfig::create($values).

For example, in the UserRegistrationTest of core, a 'user_picture' field is added to the user entity like this:

$field_storage = FieldStorageConfig::create([
  'field_name' => 'user_picture',
  'entity_type' => 'user',
  'type' => 'image',
]);
$field_storage->save();

$field = FieldConfig::create([
  'field_name' => 'user_picture',
  'entity_type' => 'user',
  'bundle' => 'user',
]);
$field->save();
2
  • Not sure how this answers my question. Could you maybee give an example? I have found you just need to add the yml configurations for a new field. Commented Jun 20, 2016 at 14:50
  • Yes, adding the yml configuration is the easiest, but I thought you were asking how to do it in php.
    – Maouna
    Commented Jun 20, 2016 at 14:57
0

I found this can easily be done using the Features module. Now i could create the the fields manually and then export them using features and copy the export to my custom module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.