首页 > 解决方案 > Symfony intl 如何使用“MissingResourceException”返回默认值

问题描述

我正在使用带有 intl 的 symfony 来翻译国家。我想处理国家为空或未翻译的情况。

国家类型.php:

// Other code 
...
public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'choice_loader' => function (Options $options) {
                $choiceTranslationLocale = $options['choice_translation_locale'];
                $alpha3 = $options['alpha3'];

                return new IntlCallbackChoiceLoader(function () use ($choiceTranslationLocale, $alpha3) {
                    return array_flip($alpha3 ? Countries::getAlpha3Names($choiceTranslationLocale) : Countries::getNames($choiceTranslationLocale));
                });
            },
            'choice_translation_domain' => false,
            'choice_translation_locale' => null,
            'alpha3' => false,
        ]);

        $resolver->setAllowedTypes('choice_translation_locale', ['null', 'string']);
        $resolver->setAllowedTypes('alpha3', 'bool');
    }

表单类型:

...
->add('originCountry', CountryType::class, [
                'required' => false,
                'invalid_message' => 'Le pays est incorrect.',
                'preferred_choices' => ['FR', 'DE', 'BE', 'IT', 'ES', 'LU'],
            ])

异常监听器:

if ($exception instanceof MissingResourceException) {
            dd($event);
            $exception = $event->getThrowable();
            $message = sprintf(
                'My Error says: %s with code: %s',
                $exception->getMessage(),
                $exception->getCode()
            );
            $response = new Response();
            $response->setContent($message);
            $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
            $event->setResponse($response);
        }

我的问题是,如果国家/地区未翻译或为空,我如何使用异常来处理默认值或空值,我想返回空的国家/地区值而不是期望值

标签: formssymfonyexceptiontranslationintl

解决方案


推荐阅读