Are you often tired to repeat static choices like gender or civility in your apps ?
- Symfony >= 2.4
Add the DictionaryBundle to your composer.json
:
{
"require": {
"knplabs/dictionary-bundle": "dev-master"
}
}
Register the bundle in app/AppKernel.php
$bundles = array(
// ...
new Knp\DictionaryBundle\KnpDictionaryBundle(),
);
Define dictionaries in your config.yml file:
knp_dictionary:
dictionaries:
my_dictionary: # your dictionary name
- Foo # your dictionary content
- Bar
- Baz
You will be able to retreive it trough the dictionary registry service:
$container->get('knp_dictionary.registry')->get('my_dictionary');
Now, use them in your forms:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('civility', 'dictionary', array(
'name' => 'my_dictionary'
));
;
}
The dictionary form type extends the symfony's choice type and its options.
You can specify the indexation mode of each dictionary
knp_dictionary:
dictionaries:
my_dictionary: # your dictionary name
type: 'key_value' # your dictionary type
content: # your dictionary content
"foo": "foo_value"
"bar": "bar_value"
"baz": "baz_value"
value
(default) : Natural indexationvalue_as_key
: Keys are defined from their valuekey_value
: Define your own keys
For now, this bundle is only able to resolve your class constants:
my_dictionary:
- MyClass::MY_CONSTANT
- Foo
- Bar
You want to add other kinds of transformations for your dictionary values ? Feel free to create your own transformer !
Create your class that implements TransformerInterface.
Load your transformer and tag it as knp_dictionary.value_transformer
.
services:
my_bundle.my_namespace.my_transformer:
class: %my_transformer_class%
tags:
- { name: knp_dictionary.value_transformer }