Commit e6fc5708 authored by tsega's avatar tsega
Browse files

Issue #3187737: Allow adding terms to open taxonomy

parent 184b4381
......@@ -7,6 +7,7 @@ namespace Drupal\excel_importer\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\Entity\Term;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
......@@ -249,7 +250,9 @@ class ExcelImporterForm extends FormBase {
private function isValidTaxonomyReference($bundle, $field, $value) {
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', $bundle);
if ($this->_array_key_first(taxonomy_term_load_multiple_by_name($value, $this->getVocabulary($bundle, $field)))) {
if ($definitions[$field]->getSettings()['handler_settings']['auto_create']) {
return TRUE;
} else if ($this->_array_key_first(taxonomy_term_load_multiple_by_name($value, $this->getVocabulary($bundle, $field)))) {
return TRUE;
}
......@@ -324,7 +327,15 @@ class ExcelImporterForm extends FormBase {
$target_type = $definitions[$field]->getSettings()['target_type'];
if($target_type == 'taxonomy_term') {
$value = $this->_array_key_first(taxonomy_term_load_multiple_by_name($value, $this->getVocabulary($bundle, $field)));
$vid = $this->getVocabulary($bundle, $field);
$tid = $this->_array_key_first(taxonomy_term_load_multiple_by_name($value, $vid));
$canAutoCreate = $definitions[$field]->getSettings()['handler_settings']['auto_create'];
if($canAutoCreate && empty($tid)) {
$value = $this->_create_taxonomy_term($value, $vid);
} else {
$value = $tid;
}
} else if($target_type == 'user' || $target_type == 'node') {
$target_field = $target_type == 'user' ? 'mail' : 'title';
$value = $this->_array_key_first(\Drupal::entityTypeManager()->getStorage($target_type)->loadByProperties([ $target_field => $value]));
......@@ -349,4 +360,16 @@ class ExcelImporterForm extends FormBase {
}
return null;
}
/**
* Create a taxonomy term and return the tid.
*/
function _create_taxonomy_term($name, $vid) {
$term = Term::create(array(
'name' => $name,
'vid' => $vid,
));
$term->save();
return $term->id();
}
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment