sonata-project / SonataFormatterBundle

Symfony SonataFormatterBundle
https://docs.sonata-project.org/projects/SonataFormatterBundle
MIT License
81 stars 117 forks source link

FormatterType is not working with single format option #734

Closed azlotnikov closed 1 year ago

azlotnikov commented 1 year ago

Environment

PHP 8.2.0 Symfony 5.4.17

Sonata packages

composer show --latest 'sonata-project/*'

Direct dependencies required in composer.json:
sonata-project/admin-bundle              4.22.2 4.22.2 The missing Symfony Admin Generator
sonata-project/block-bundle              4.19.0 4.19.0 Symfony SonataBlockBundle
sonata-project/doctrine-orm-admin-bundle 4.9.1  4.9.1  Integrate Doctrine ORM into the SonataAdminBundle
sonata-project/formatter-bundle          5.0.1  5.0.1  Symfony SonataFormatterBundle
sonata-project/intl-bundle               3.0.2  3.0.2  Symfony SonataIntlBundle
sonata-project/media-bundle              4.5.1  4.5.1  Symfony SonataMediaBundle

Transitive dependencies not required in composer.json:
sonata-project/cache                     2.2.0  2.2.0  Cache library
sonata-project/doctrine-extensions       2.1.0  2.1.0  Doctrine2 behavioral extensions
sonata-project/exporter                  3.1.1  3.1.1  Lightweight Exporter library
sonata-project/form-extensions           1.18.0 1.18.0 Symfony form extensions
sonata-project/twig-extensions           2.0.0  2.0.0  Sonata twig extensions

Subject

If I try to create FormatterType with single format choice

 'format_field_options' => [
    'choices' => [
        'richhtml' => 'richhtml',
    ],
    'empty_data' => 'richhtml',
],

rendering template vendor/sonata-project/formatter-bundle/src/Resources/views/Form/formatter.html.twig is failing with error

Key "choices" for array with keys "value", ... does not exist.

The following code is causing the problem https://github.com/sonata-project/SonataFormatterBundle/blob/5.x/src/Resources/views/Form/formatter.html.twig#L18

{% if form.children[format_field].vars.choices|length > 1 %}

because here https://github.com/sonata-project/SonataFormatterBundle/blob/5.x/src/Form/Type/FormatterType.php#L61

if (1 >= \count($formatOptions['choices'])) {
    unset($formatOptions['choices']);
    $formatType = HiddenType::class;
}

this field is unset.

Steps to reproduce

$form->add('text', FormatterType::class, [
    'source_field' => 'text',
    'format_field' => 'textFormatter',
    'ckeditor_context' => 'default',
    'format_field_options' => [
        'choices' => [
            'richhtml' => 'richhtml',
        ],
        'empty_data' => 'richhtml',
    ],
    'target_field' => 'text',
])