Skip to content

Instantly share code, notes, and snippets.

@davidbarratt
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidbarratt/5aace2d13f54e511698c to your computer and use it in GitHub Desktop.
Save davidbarratt/5aace2d13f54e511698c to your computer and use it in GitHub Desktop.
Entity Export
<?php
$data = \Drupal\Component\Serialization\Yaml::decode(file_get_contents('node.yml'));
$entity_type = \Drupal::entityManager()->getDefinition('node');
if ($entity_type->hasKey('bundle')) {
$data[$entity_type->getKey('bundle')] = $data[$entity_type->getKey('bundle')][0]['target_id'];
}
$entity = NULL;
if ($entity_type->hasKey('uuid')) {
if (!empty($data[$entity_type->getKey('uuid')][0]['value'])) {
$entity = entity_load_by_uuid('node', $data['uuid'][0]['value']);
}
}
if ($entity) {
foreach ($entity->getFields() as $name => $property) {
if (isset($data[$name])) {
$property->setValue($data[$name]);
}
}
if ($entity_type->isRevisionable()) {
$entity->setNewRevision();
}
}
else {
$entity = entity_create('node', $data);
}
$entity->save();
<?php
$node = \Drupal\node\Entity\Node::load(4);
$data = $node->toArray();
if ($node->getEntityType()->hasKey('id')) {
unset($data[$node->getEntityType()->getKey('id')]);
}
if ($node->getEntityType()->hasKey('revision')) {
unset($data[$node->getEntityType()->getKey('revision')]);
}
$yaml = \Drupal\Component\Serialization\Yaml::encode($data);
file_put_contents('node.yml', $yaml);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment