uc_gc_client-8.x-1.x-dev/src/Form/CountriesForm.php
src/Form/CountriesForm.php
<?php
namespace Drupal\uc_gc_client\Form;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBase;
use Drupal\uc_country\Controller\CountryController;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Interface for managing GoCardless enabled countries.
*/
class CountriesForm extends FormBase {
/**
* Constructs a new CountriesForm object.
*
* @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
* The config factory.
*/
public function __construct(ConfigFactoryInterface $configFactory) {
$this->config = $configFactory->get('uc_gc_client.settings')->get();
$this->configEditable = $configFactory->getEditable('uc_gc_client.settings');
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('config.factory')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'uc_gc_client_countries_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$countryController = new CountryController();
$uc_countries = $countryController->countryOptionsCallback();
$gc_countries = $this->config['countries'];
$regions = $this->config['regions'];
$countries = [];
$default_value = [];
foreach ($gc_countries as $gc_code => $gc_country) {
if (isset($uc_countries[$gc_code])) {
$country_name = $uc_countries[$gc_code]->render();
$countries_[$country_name] = $gc_code;
}
}
ksort($countries_);
foreach ($countries_ as $name => $gc_code) {
$countries[$gc_code] = [
$name,
$regions[$gc_countries[$gc_code]['region']],
$gc_countries[$gc_code]['sign'],
];
if ($gc_countries[$gc_code]['enabled']) {
$default_value[$gc_code] = TRUE;
}
}
$form = [];
$form['markup'] = [
'#markup' => $this->t('<p>Countries should first be enabled in Ubercart before they can be enabled / disabled here.</p>'),
];
$header = ['Country', 'Direct debit scheme', 'Currency'];
$form['countries'] = [
'#type' => 'tableselect',
'#header' => $header,
'#options' => $countries,
'#empty' => $this->t('No countries available.'),
'#default_value' => $default_value,
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Enable / disable countries'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$countries = $form_state->getValue(['countries']);
$gc_countries = $this->config['countries'];
foreach ($countries as $code => $country) {
if ($country) {
$gc_countries[$code]['enabled'] = 1;
}
else {
$gc_countries[$code]['enabled'] = 0;
}
}
$this->configEditable->set('countries', $gc_countries)->save();
drupal_set_message($this->t('Countries available to GoCardless have been updated.'));
}
}
