<?php
namespace App\Form\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CountryType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Intl\Countries;
use Symfony\Component\Validator\Constraints\NotBlank;
class AddressType extends AbstractType
{
protected bool $europeanCountriesOnly = false;
/**
* @return array
*/
protected function getAllowedCountries(): array
{
$europe = [
'DE', 'AT', 'CH',
'ES', 'LU', 'CZ',
'NL', 'IT', 'PL',
'BE', 'FR', 'FI',
'GB', 'DK', 'NO',
'HU', 'RO', 'LI',
'RU', 'SE', 'BG',
'IS',
];
$allowed = array_merge($europe, [
'TH', 'US', 'SK',
'PT', 'EG', 'SI',
'CA', 'AU', 'UA',
'PY', 'GR', 'EC',
'LV', 'LT', 'JP',
'MT', 'TR', 'AE',
'IE', 'CN',
]);
$return = [];
if($this->getEuropeanCountriesOnly()) {
$allowed = $europe;
}
foreach(Countries::getNames() as $code => $name) {
if(in_array($code, $allowed)) {
$return[$name] = $code;
}
}
return $return;
}
/**
* @return bool
*/
protected function getEuropeanCountriesOnly(): bool
{
return $this->europeanCountriesOnly;
}
/**
* @return array
*/
protected function getPreferredCountryChoices(): array
{
return ['DE', 'AT', 'CH'];
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$notBlank = new NotBlank();
$builder->add('street', TextType::class, array(
'label' => 'Straße',
'constraints' => $notBlank
));
$builder->add('house_number', TextType::class, array(
'label' => 'Hausnummer',
'attr' => [
'maxlength' => 6
],
'constraints' => $notBlank
));
$builder->add('zip_code', TextType::class, array(
'label' => 'Postleitzahl',
'constraints' => $notBlank
));
$builder->add('city', TextType::class, array(
'label' => 'Ort',
'constraints' => $notBlank
));
$builder->add('country', CountryType::class, [
'label' => 'Land',
'choices' => $this->getAllowedCountries(),
'preferred_choices' => $this->getPreferredCountryChoices()
]);
}
}