Installation
composer require baks-dev/field-country
Register the Service
Add this to config/packages/field.php (create if missing):
use BaksDev\Field\Country\Choice\CountryFieldChoice;
return static function (ContainerConfigurator $configurator) {
$services = $configurator->services()
->defaults()
->autowire(true)
->autoconfigure(true);
$services->set(CountryFieldChoice::class)
->tag('baks.fields.choice');
};
First Use Case Use the field in a form builder (e.g., Symfony form or custom field system):
$builder->add('country', CountryFieldChoice::class);
Basic Field Integration
// In a form type or field definition
$builder->add('country', CountryFieldChoice::class, [
'label' => 'Select Country',
'required' => true,
]);
Customizing Options Override default country list via dependency injection:
$services->set(CountryFieldChoice::class)
->arg('$countries', ['US', 'CA', 'GB']) // Custom list
->tag('baks.fields.choice');
Template Overrides
Place custom templates in templates/field-country/:
content.html.twig: Country list rendering.template.html.twig: Wrapper structure.Validation Use Symfony’s validation constraints:
$builder->add('country', CountryFieldChoice::class, [
'constraints' => [
new NotBlank(),
new Country(['message' => 'Invalid country.']),
],
]);
Dynamic Data Fetching
Extend CountryFieldChoice to fetch countries from an API:
class ApiCountryFieldChoice extends CountryFieldChoice {
public function __construct(CountryApiClient $client) {
$countries = $client->fetchCountries();
parent::__construct($countries);
}
}
PHP Version Requirement
Class 'BaksDev\Field\Country\Choice\CountryFieldChoice' not foundMissing Service Tag
->tag('baks.fields.choice') is set in field.php.Template Override Conflicts
templates/field-country/) and clear cache:
php bin/console cache:clear
Country Code Validation
US, not United States).Country constraint for validation:
use BaksDev\Field\Country\Validator\Constraints\Country;
Log Country List: Dump the country array in CountryFieldChoice constructor:
public function __construct(array $countries = null) {
$this->countries = $countries ?? [];
\Log::debug('Loaded countries:', ['countries' => $this->countries]);
}
Check Service Dumping:
php bin/console debug:container baks.fields.choice
Custom Country Source
Extend CountryFieldChoice to load countries from a database or external service.
Localization
Override content.html.twig to display country names in a specific language:
{# Example: Russian names #}
{% for code, name in countries %}
<option value="{{ code }}">{{ name|translate({'domain': 'countries'}) }}</option>
{% endfor %}
Grouped Countries Modify the template to group by region (e.g., Europe, Asia):
{% for region, countries in countries|group_by('region') %}
<optgroup label="{{ region }}">
{% for code, name in countries %}
<option value="{{ code }}">{{ name }}</option>
{% endfor %}
</optgroup>
{% endfor %}
How can I help you explore Laravel packages today?