dependent_country_state-1.0.6/src/Form/BulkImportPincodeForm.php

src/Form/BulkImportPincodeForm.php
<?php

namespace Drupal\dependent_country_state\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\dependent_country_state\services\GetData;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Database\Connection;
use PhpOffice\PhpSpreadsheet\IOFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\File\FileSystem;

/**
 * This is simple contact Form.
 */
class BulkImportPincodeForm extends FormBase {

  /**
   * Dbconnectin variable for storing database instance.
   *
   * @var dbConnection
   */
  protected $dbConnection;

  /**
   * The Entity type manager services.
   *
   * @var Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The File system services.
   *
   * @var Drupal\Core\File\FileSystem
   */
  protected $fileSystem;

  /**
   * Store state object of specific id which is given in URL.
   *
   * @var getData
   */

  protected $getData;

  /**
   * Constructor to assign object on getData variable.
   *
   * @var \Drupal\timezone\services\GetData $getData
   */

  /**
   * Construction to inilized the database object.
   *
   * @param Drupal\dependent_country_state\services\GetData $getData
   *   The getData will fetch data from data.
   * @param Drupal\Core\Database\Connection $getConnection
   *   The database connection to be used.
   * @param Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manger interface.
   * @param Drupal\Core\File\FileSystem $fileSystem
   *   The file system service.
   */
  public function __construct(GetData $getData, Connection $getConnection, EntityTypeManagerInterface $entityTypeManager, FileSystem $fileSystem) {
    $this->getData = $getData;
    $this->dbConnection = $getConnection;
    $this->entityTypeManager = $entityTypeManager;
    $this->fileSystem = $fileSystem;
  }

  /**
   * Define here unique form ID.
   */
  public function getFormId() {
    return "state_city_bulk_upload_pincode";
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {

    // Instantiates GetData class.
    return new static(
      $container->get(GetData::class),
      $container->get('database'),
      $container->get('entity_type.manager'),
      $container->get('file_system'),
    );

  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $countryList = $this->getData->getAllCountry();
    $options = [];
    foreach ($countryList as $value) {
      $options[$value->id] = $value->country_name;
    }

    $form['country'] = [
      '#type' => 'select',
      '#title' => $this->t('Country'),
      '#options' => $options,
      '#default_value' => '',
      '#empty_option' => $this->t('- Select Country -'),
      '#ajax' => [
        'callback' => '::statesList',
        'effect' => 'fade',
        'event' => 'change',
        'wrapper' => 'state_list',
        'progress' => [
          'type' => 'throbber',
          'message' => 'Loading States...',
        ],
      ],

    ];

    if ($form_state->getTriggeringElement()) {

      $countryId = $form_state->getValue('country');

      $stateList = $this->getData->getAllStateByCountryId($countryId);
      $optionState = [];
      foreach ($stateList as $value) {
        $optionState[$value->id] = $value->state_name;
      }

      $form['state'] = [
        '#type' => 'select',
        '#title' => $this->t('State'),
        '#validated' => TRUE,
        '#prefix' => '<div id="state_list">',
        '#suffix' => '</div>',
        '#options' => $optionState,
        '#empty_option' => $this->t('- Select State -'),
        '#ajax' => [
          'callback' => '::cityList',
          'effect' => 'fade',
          'event' => 'change',
          'wrapper' => 'city_list',
          'progress' => [
            'type' => 'throbber',
            'message' => 'Loading City...',
          ],
        ],
      ];
    }
    else {

      $form['state'] = [
        '#type' => 'select',
        '#title' => $this->t('State'),
        '#validated' => TRUE,
        '#default_value' => '',
        '#prefix' => '<div id="state_list">',
        '#suffix' => '</div>',
        '#empty_option' => $this->t('- Select State -'),
      ];

    }

    $form['city'] = [
      '#type' => 'select',
      '#title' => $this->t('City'),
      '#empty_option' => $this->t('- Select City -'),
      '#validated' => TRUE,
      '#default_value' => '',
      '#prefix' => '<div id="city_list">',
      '#suffix' => '</div>',
    ];

    $form['csv_upload'] = [
      '#type'                 => 'managed_file',
      '#upload_location'      => 'public://content/excel_files/',
      '#multiple'             => FALSE,
      '#description'          => $this->t('Allowed extensions: .xlsx and only one column city name'),
      '#upload_validators'    => [
        'file_validate_extensions'    => ['xlsx'],
        'file_validate_size'          => [25600000],
      ],
      '#title'                => $this->t('Upload xlsx file only.'),
    ];

    $form['action'] = ['#type' => 'actions'];

    $form['state_search']['submit'] = [
      '#type' => 'submit',
      '#value' => (isset($this->id) && $this->id > 0) ? $this->t('Update') : $this->t('Submit'),
    ];
    global $base_url;
    $sampleFile = 'pincode_import.csv';
    $handle = fopen("sites/default/files/" . $sampleFile, "w+") or die("There is no permission to create log file. Please give permission for sites/default/files!");
    $fields = 'Area Name, Pincode';
    fwrite($handle, $fields);
    $result = '<a class="button button--primary" href="' . $base_url . '/sites/default/files/' . $sampleFile . '">Click here to download sample excel</a>';
    $form['details'] = [
      '#type' => 'markup',
      '#markup' => $result,
    ];

    return $form;
  }

  /**
   * Ajax call back method for City list.
   *
   * @param array $form
   *   The render array of the currently built form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   */
  public function cityList(array $form, FormStateInterface $form_state) {

    $stateId = $form_state->getValue('state');

    $cityList = $this->getData->getAllCityByStateId($stateId);

    $optionCity = ['' => 'Select City'];

    foreach ($cityList as $value) {
      $optionCity[$value->id] = $value->city_name;
    }

    $form['city'] = [
      '#type' => 'select',
      '#name' => 'city',
      '#prefix' => '<div id="city_list">',
      '#suffix' => '</div>',
      '#validated' => TRUE,
      '#title' => $this->t('City'),
      '#options' => $optionCity,
    ];

    return $form['city'];

  }

  /**
   * Ajax call back method for state list.
   *
   * @param array $form
   *   The render array of the currently built form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   */
  public function statesList(array $form, FormStateInterface $form_state) {
    return $form['state'];
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {

    $state = $form_state->getValue('state');
    $country = $form_state->getValue('country');
    $city = $form_state->getValue('city');

    if (empty($state)) {
      $form_state->setErrorByName('state', $this->t('State cannot be blank'));
    }
    elseif (!is_numeric($state)) {
      $form_state->setErrorByName('state', $this->t('Invalid State is selected.'));
    }

    if (empty($country)) {
      $form_state->setErrorByName('country', $this->t('Country cannot be blank'));
    }
    elseif (!is_numeric($country)) {
      $form_state->setErrorByName('country', $this->t('Invalid Country is selected.'));
    }

    if (empty($city)) {
      $form_state->setErrorByName('city', $this->t('City cannot be blank'));
    }
    elseif (!is_numeric($city)) {
      $form_state->setErrorByName('country', $this->t('Invalid City is selected.'));
    }

    if ($form_state->getValue('csv_upload') == NULL) {
      $form_state->setErrorByName('csv_upload', $this->t('upload proper .xlsx File'));
    }

  }

  /**
   * Implements a form submit handler.
   *
   * @param array $form
   *   The render array of the currently built form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Object describing the current state of the form.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    $country = $form_state->getValue('country');
    $state = $form_state->getValue('state');
    $city_name = $form_state->getValue('city');
    $file = $this->entityTypeManager->getStorage('file')
      ->load($form_state->getValue('csv_upload')[0]);
    $full_path = $file->get('uri')->value;
    $file_name = basename($full_path);

    $inputFileName = $this->fileSystem->realpath('public://content/excel_files/' . $file_name);

    $spreadsheet = IOFactory::load($inputFileName);

    $sheetData = $spreadsheet->getActiveSheet();

    $rows = [];
    foreach ($sheetData->getRowIterator() as $row) {
      $cellIterator = $row->getCellIterator();
      $cellIterator->setIterateOnlyExistingCells(FALSE);

      $cells = [];
      foreach ($cellIterator as $cell) {
        $cells[] = $cell->getValue();
      }
      $rows[] = $cells;

    }

    for ($i = 1; $i < count($rows); $i++) {

      $area_name = !empty($rows[$i][0]) ? $rows[$i][0] : '';
      $pincode = !empty($rows[$i][1]) ? $rows[$i][1] : '';

      if (!empty($pincode)) {

        $query = $this->dbConnection->insert('dependent_pincode')
          ->fields(['countryId', 'stateId', 'cityId',
            'area_name', 'pincode', 'created',
          ]);
        $record = [$country, $state, $city_name, $area_name, $pincode, time()];
        $query->values($record);
        $success = $query->execute();
      }

    }

    if ($success) {
      $this->messenger()->addMessage($this->t('Pincode/area Uploaded Successfully.'), 'status', TRUE);
    }
    else {
      $this->messenger()->addError($this->t('Pincode/area not Uploaded Successfully., please try again.'), 'status', TRUE);
    }

  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc