public function GetServices::simpleNodeImporterCreateTaxonomy in Simple Node Importer 8
File
- src/
Services/ GetServices.php, line 139
Class
Namespace
Drupal\simple_node_importer\ServicesCode
public function simpleNodeImporterCreateTaxonomy($nid) {
$node = Node::load($nid);
$fid = $node
->get('field_upload_csv')
->getValue()[0]['target_id'];
$file = File::load($fid);
$uri = $file
->getFileUri();
$url = Url::fromUri(file_create_url($uri))
->toString();
$handle = fopen($url, 'r');
while ($row = fgetcsv($handle)) {
for ($i = 0; $i <= count($row) - 1; $i++) {
$name = $row[$i];
if (empty($name)) {
break;
}
if ($i == 0) {
$vid = strtolower(preg_replace('/\\s+/', '_', $name));
$vocabularies = Vocabulary::loadMultiple();
if (!isset($vocabularies[$vid])) {
$vocabulary = Vocabulary::create([
'vid' => $vid,
'description' => '',
'name' => $name,
]);
$vocabulary
->save();
}
}
else {
$termArray = [
'name' => $name,
'vid' => $vid,
];
$termid = \Drupal::entityManager()
->getStorage('taxonomy_term')
->loadByProperties($termArray);
if ($i == 1) {
if (empty($termid)) {
Term::create($termArray)
->save();
}
}
else {
$parent = $row[$i - 1];
$termArray = [
'name' => $parent,
'vid' => $vid,
];
$termexist = 0;
$parenttermid = \Drupal::entityManager()
->getStorage('taxonomy_term')
->loadByProperties($termArray);
$childterms = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->loadChildren(key($parenttermid));
foreach ($childterms as $childterm) {
if ($childterm
->getName() == $name) {
$termexist = 1;
}
}
if ($termexist == 0) {
if (!empty($parenttermid)) {
Term::create([
'parent' => key($parenttermid),
'name' => $name,
'vid' => $vid,
])
->save();
}
}
}
}
}
}
drupal_set_message(t('Taxonomies are created successfully'));
}