dependent_country_state-1.0.6/src/Form/BulkImportCityForm.php
src/Form/BulkImportCityForm.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 BulkImportCityForm 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_import_form_id";
}
/**
* {@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 = ['' => 'Select Country'];
foreach ($countryList as $value) {
$options[$value->id] = $value->country_name;
}
$form['country'] = [
'#type' => 'select',
'#title' => $this->t('Country'),
'#options' => $options,
'#validated' => TRUE,
'#ajax' => [
'callback' => '::statesList',
'effect' => 'fade',
'event' => 'change',
'wrapper' => 'state_list',
'progress' => [
'type' => 'throbber',
'message' => 'Loading States...',
],
],
];
$form['state'] = [
'#type' => 'select',
'#title' => $this->t('State'),
'#validated' => TRUE,
'#empty_option' => $this->t('- Select State -'),
'#prefix' => '<div id="state_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 = 'city_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 = 'City Name';
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 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) {
$countryId = $form_state->getValue('country');
$stateList = $this->getData->getAllStateByCountryId($countryId);
$optionState = ['' => 'Select State'];
foreach ($stateList as $value) {
$optionState[$value->id] = $value->state_name;
}
$form['state'] = [
'#type' => 'select',
'#name' => 'state',
'#prefix' => '<div id="state_list">',
'#suffix' => '</div>',
'#validated' => TRUE,
'#title' => $this->t('State'),
'#options' => $optionState,
];
return $form['state'];
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
$state = $form_state->getValue('state');
$country = $form_state->getValue('country');
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 ($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) {
$state = $form_state->getValue('state');
$country = $form_state->getValue('country');
$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++) {
$query = $this->dbConnection->insert('dependent_city')
->fields(['countryId', 'stateId', 'city_name', 'created']);
$record = [$country, $state, $rows[$i][0], time()];
$query->values($record);
$success = $query->execute();
}
if ($success) {
$this->messenger()->addMessage($this->t('City Uploaded Successfully.'), 'status', TRUE);
}
else {
$this->messenger()->addError($this->t('City not Uploaded Successfully., please try again.'), 'status', TRUE);
}
}
}
