function csc_state_data_install in Country, State and City Fields 8
Implements hook_install().
File
- csc_state_data/
csc_state_data.install, line 13 - Here we are importing state data from csv.
Code
function csc_state_data_install() {
$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler
->getModule('csc_state_data')
->getPath();
// Importando os dados dos paises.
$array = $fields = [];
$i = 0;
$handle = @fopen($module_path . '/states.csv', "r");
if ($handle) {
while (($row = fgetcsv($handle, 4096)) !== FALSE) {
if (empty($fields)) {
$fields = $row;
continue;
}
foreach ($row as $k => $value) {
$array[$i][$fields[$k]] = $value;
}
$i++;
}
if (!feof($handle)) {
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
// Criando um registro na entidade country para cada pais importado.
if (is_array($array) && count($array) > 0) {
foreach ($array as $state) {
$new_state = StateList::create([
'id' => $state['id'],
'name' => $state['name'],
'country_id' => $state['country_id'],
]);
$new_state
->save();
}
}
}