如何获得所选国家的城市列表,如果国家不是使用动态生成提交表单的实体



我有一个Travel实体,希望在add表单中显示所选国家/地区的城市列表。

我已经应用了文档中的示例:[http://symfony.com/doc/current/form/dynamic_form_modification.html#dynamic-generation-for-submitted-forms][1]

在这个例子中,体育是一个实体,它有一个名为getAvailablePositions()的方法,但在我的例子中,国家不是一个实体,它是CountryType::class

如果我必须像文档中的例子那样我必须实例化一个实体国家但是我没有

$formModifier = function (FormInterface $form, Country $country = null) {
       // Country doesn't exist , this is wrong
        $cities = null === $country ? array() : $country->getCities();
        $form->add('city', EntityType::class, array(
            'class' => 'AppBundleEntityCity',
            'choices' => $cities,
            'choice_label' => 'name',
            'label' => 'City',
            'multiple' => false,
            'expanded' => false,
            'required' => false,
        ));
    };

这是实体城

class City
{
/**
 * @var integer
 *
 * @ORMColumn(name="id", type="integer")
 * @ORMId
 * @ORMGeneratedValue(strategy="AUTO")
 */
private $id;
/**
 * @var string
 *
 * @ORMColumn(name="name", type="string", length=255)
 *
 */
private $name;
/**
 * @var string
 *
 * @ORMColumn(name="country", type="string", length=5)
 */
private $country;

这是CityType

//CityType
$builder
        ->add('name', TextType::class, array(
            'label' => 'Name',
        ))
        ->add('country', CountryType::class, array(
            'label' => 'Country',
            'placeholder' => 'Country',
        ))
    ;

[1]:

http://symfony.com/doc/current/form/dynamic_form_modification.html dynamic-generation-for-submitted-forms

如图所示,这里的country::class使用默认值

Symfony 组件 Intl Intl:: getRegionBundle()——> getCountryNames ()

如果我们观察这里的Intl组件你会看到你可以像这样检索一个特定的国家

$country = Intl::getRegionBundle()->getCountryName('GB');

所以,这就是说:由于您不希望用您自己的逻辑创建实体"country",您可以在实体city中创建一个静态方法"getCitiesByCountry",该方法将调用其存储库来检索该国家(其中country喜欢")的城市。上面我只提到,因为如果"国家"是一个字符串,记住CountryType::类将只返回两个字母(这是你应该坚持在每个城市,因为他们是全局的,而不是全名),并使用上述方法根据你的逻辑翻译之前渲染。如果你不同意,请告诉我

最新更新