You are here

class ContentImport in Content Import 8

Same name and namespace in other branches
  1. 8.9 src/Form/ContentImport.php \Drupal\contentimport\Form\ContentImport
  2. 8.3 src/Form/ContentImport.php \Drupal\contentimport\Form\ContentImport
  3. 8.4 src/Form/ContentImport.php \Drupal\contentimport\Form\ContentImport

Configure Content Import settings for this site.

Hierarchy

Expanded class hierarchy of ContentImport

1 string reference to 'ContentImport'
contentimport.routing.yml in ./contentimport.routing.yml
contentimport.routing.yml

File

src/Form/ContentImport.php, line 27
Contains \Drupal\contentimport\Form\ContentImport.

Namespace

Drupal\contentimport\Form
View source
class ContentImport extends ConfigFormBase {
  public function getFormID() {
    return 'contentimport';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'contentimport.settings',
    ];
  }

  /**
   * Content Import Form.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $ContentTypes = ContentImportController::getAllContentTypes();
    $selected = 0;
    $form['contentimport_contenttype'] = [
      '#type' => 'select',
      '#title' => $this
        ->t('Select Content Type'),
      '#options' => $ContentTypes,
      '#default_value' => $selected,
    ];
    $form['file_upload'] = [
      '#type' => 'managed_file',
      '#title' => t('Import CSV File'),
      '#size' => 40,
      '#description' => t('Select the CSV file to be imported. '),
      '#required' => FALSE,
      '#autoupload' => TRUE,
      '#upload_validators' => array(
        'file_validate_extensions' => array(
          'csv',
        ),
      ),
    ];
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => t('Import'),
      '#button_type' => 'primary',
    ];
    return parent::buildForm($form, $form_state);
  }
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $contentType = $form_state
      ->getValue('contentimport_contenttype');
    $form_state_values = $form_state
      ->getValues();
    $csvFile = $form_state
      ->getValue('file_upload');
    $file = File::load($csvFile[0]);
    $file
      ->setPermanent();
    $file
      ->save();
    ContentImport::createNode($contentType);
  }

  /**
   * To get all Content Type Fields.
   */
  public function getFields($contentType) {
    $entityManager = \Drupal::service('entity.manager');
    $fields = [];
    foreach (\Drupal::entityManager()
      ->getFieldDefinitions('node', $contentType) as $field_name => $field_definition) {
      if (!empty($field_definition
        ->getTargetBundle())) {
        $fields['name'][] = $field_definition
          ->getName();
        $fields['type'][] = $field_definition
          ->getType();
        $fields['setting'][] = $field_definition
          ->getSettings();
      }
    }
    return $fields;
  }

  /**
   * To get Reference field ids.
   */
  public function getTermReference($voc, $terms) {
    $vocName = strtolower($voc);
    $vid = preg_replace('@[^a-z0-9_]+@', '_', $vocName);
    $vocabularies = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple();

    /** Create Vocabulary if it is not exists **/
    if (!isset($vocabularies[$vid])) {
      ContentImport::createVoc($vid, $voc);
    }
    $termArray = explode(',', $terms);
    $termIds = [];
    foreach ($termArray as $term) {
      $term_id = ContentImport::getTermId($term, $vid);
      if (empty($term_id)) {
        $term_id = ContentImport::createTerm($voc, $term, $vid);
      }
      $termIds[]['target_id'] = $term_id;
    }
    return $termIds;
  }

  /**
   * To Create Terms if it is not available.
   */
  public function createVoc($vid, $voc) {
    $vocabulary = \Drupal\taxonomy\Entity\Vocabulary::create(array(
      'vid' => $vid,
      'machine_name' => $vid,
      'name' => $voc,
    ));
    $vocabulary
      ->save();
  }

  /**
   * To Create Terms if it is not available.
   */
  public function createTerm($voc, $term, $vid) {
    Term::create(array(
      'parent' => array(
        $voc,
      ),
      'name' => $term,
      'vid' => $vid,
    ))
      ->save();
    $termId = ContentImport::getTermId($term, $vid);
    return $termId;
  }

  /**
   * To get Termid available.
   */
  public function getTermId($term, $vid) {
    $termRes = db_query('SELECT n.tid FROM {taxonomy_term_field_data} n WHERE n.name  = :uid AND n.vid  = :vid', array(
      ':uid' => $term,
      ':vid' => $vid,
    ));
    foreach ($termRes as $val) {
      $term_id = $val->tid;
    }
    return $term_id;
  }

  /**
   * To get user information based on emailIds
   */
  public static function getUserInfo($userArray) {
    $uids = [];
    foreach ($userArray as $usermail) {
      $users = \Drupal::entityTypeManager()
        ->getStorage('user')
        ->loadByProperties([
        'mail' => $usermail,
      ]);
      $user = reset($users);
      if ($user) {
        $uids[] = $user
          ->id();
      }
      else {
        $user = \Drupal\user\Entity\User::create();
        $user->uid = '';
        $user
          ->setUsername($usermail);
        $user
          ->setEmail($usermail);
        $user
          ->set("init", $usermail);
        $user
          ->enforceIsNew();
        $user
          ->activate();
        $user
          ->save();
        $users = \Drupal::entityTypeManager()
          ->getStorage('user')
          ->loadByProperties([
          'mail' => $usermail,
        ]);
        $uids[] = $user
          ->id();
      }
    }
    return $uids;
  }

  /**
   * To import data as Content type nodes.
   */
  public function createNode($contentType) {
    global $base_url;
    $loc = db_query('SELECT file_managed.uri FROM file_managed ORDER BY file_managed.fid DESC limit 1', array());
    foreach ($loc as $val) {
      $location = $val->uri;

      // To get location of the csv file imported
    }
    $mimetype = mime_content_type($location);
    $fields = ContentImport::getFields($contentType);
    $fieldNames = $fields['name'];
    $fieldTypes = $fields['type'];
    $fieldSettings = $fields['setting'];
    $files = glob('sites/default/files/' . $contentType . '/images/*.*');
    $images = [];
    foreach ($files as $file_name) {
      file_unmanaged_copy($file_name, 'sites/default/files/' . $contentType . '/images/' . basename($file_name));
      $image = File::create(array(
        'uri' => 'public://' . $contentType . '/images/' . basename($file_name),
      ));
      $image
        ->save();
      $images[basename($file_name)] = $image;
    }
    if ($mimetype == "text/plain") {

      //Code for import csv file
      if (($handle = fopen($location, "r")) !== FALSE) {
        $nodeData = [];
        $keyIndex = [];
        $index = 0;
        while (($data = fgetcsv($handle)) !== FALSE) {
          $index++;
          if ($index < 2) {
            array_push($fieldNames, 'title');
            array_push($fieldTypes, 'text');
            foreach ($fieldNames as $fieldValues) {
              $i = 0;
              foreach ($data as $dataValues) {
                if ($fieldValues == $dataValues) {
                  $keyIndex[$fieldValues] = $i;
                }
                $i++;
              }
            }
            continue;
          }
          for ($f = 0; $f < count($fieldNames); $f++) {
            switch ($fieldTypes[$f]) {
              case 'image':
                if (!empty($images[$data[$keyIndex[$fieldNames[$f]]]])) {
                  $nodeArray[$fieldNames[$f]] = array(
                    array(
                      'target_id' => $images[$data[$keyIndex[$fieldNames[$f]]]]
                        ->id(),
                    ),
                  );
                }
                break;
              case 'entity_reference':
                if ($fieldSettings[$f]['target_type'] == 'taxonomy_term') {
                  $reference = explode(":", $data[$keyIndex[$fieldNames[$f]]]);
                  if (is_array($reference) && $reference[0] != '') {
                    $terms = ContentImport::getTermReference($reference[0], $reference[1]);
                    $nodeArray[$fieldNames[$f]] = $terms;
                  }
                }
                else {
                  if ($fieldSettings[$f]['target_type'] == 'user') {
                    $userArray = explode(', ', $data[$keyIndex[$fieldNames[$f]]]);
                    $users = ContentImport::getUserInfo($userArray);
                    $nodeArray[$fieldNames[$f]] = $users;
                  }
                }
                break;
              case 'text_with_summary':
              case 'text_long':
              case 'text':
                $nodeArray[$fieldNames[$f]] = [
                  'value' => $data[$keyIndex[$fieldNames[$f]]],
                  'format' => 'full_html',
                ];
                break;
              case 'datetime':
                $dateTime = \DateTime::createFromFormat('Y-m-d h:i:s', $data[$keyIndex[$fieldNames[$f]]]);
                $newDateString = $dateTime
                  ->format('Y-m-d\\Th:i:s');
                $nodeArray[$fieldNames[$f]] = [
                  "value" => $newDateString,
                ];
                break;
              case 'timestamp':
                $nodeArray[$fieldNames[$f]] = [
                  "value" => $data[$keyIndex[$fieldNames[$f]]],
                ];
                break;
              case 'boolean':
                $nodeArray[$fieldNames[$f]] = $data[$keyIndex[$fieldNames[$f]]] == 'On' || $data[$keyIndex[$fieldNames[$f]]] == 'Yes' ? 1 : 0;
                break;
              default:
                $nodeArray[$fieldNames[$f]] = $data[$keyIndex[$fieldNames[$f]]];
                break;
            }
          }
          $nodeArray['type'] = strtolower($contentType);
          $nodeArray['uid'] = 1;
          if ($nodeArray['title']['value'] != '') {
            $node = Node::create($nodeArray);
            $node
              ->save();
          }
        }
        fclose($handle);
        $url = $base_url . "/admin/content";
        header('Location:' . $url);
        exit;
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
ContentImport::buildForm public function Content Import Form. Overrides ConfigFormBase::buildForm
ContentImport::createNode public function To import data as Content type nodes.
ContentImport::createTerm public function To Create Terms if it is not available.
ContentImport::createVoc public function To Create Terms if it is not available.
ContentImport::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
ContentImport::getFields public function To get all Content Type Fields.
ContentImport::getFormID public function
ContentImport::getTermId public function To get Termid available.
ContentImport::getTermReference public function To get Reference field ids.
ContentImport::getUserInfo public static function To get user information based on emailIds
ContentImport::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
FormInterface::getFormId public function Returns a unique string identifying the form. 236
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.