【问题标题】:Load a Symfony sfWidgetFormDoctrineChoice select with a limited set of results加载带有有限结果集的 Symfony sfWidgetFormDoctrineChoice 选择
【发布时间】:2011-04-12 19:09:54
【问题描述】:

我正在一个 Symfony 应用程序中开发一个表单,其中用户必须使用 HTML select 元素指明一个国家、一个地区和一个可选的岛屿。

我有三个模型:Country、Region 和 Island; Symfony 使用 sfWidgetFormDoctrineChoice 小部件在表单中自动生成了三个小部件:

...
'country_id' => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Country'), 'add_empty' => false)),
'region_id'  => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Region'), 'add_empty' => false)),
'island_id'  => new sfWidgetFormDoctrineChoice(array('model' => $this->getRelatedModelName('Island'), 'add_empty' => true)),
...

由于国家列表很大,地区列表也很大,我一直在考虑根据 Country 中选择的值过滤RegionIsland 中可用的选项。

使用 jQuery 的 change 方法和一个简单的 AJAX 请求,在 HTML 文档准备好后执行此操作很容易。但我想知道是否有一种方法可以直接从 Symfony 中执行此操作,也许在表单配置中,有一个默认的组合选择。

有什么建议吗?

谢谢!

【问题讨论】:

  • 那么,是否希望通过 ajax 加载或通过 javascript 显示/隐藏?
  • 我检查了它,但不喜欢。对于我的具体要求,它太复杂了。我会发布我最终做了什么
  • 很高兴看到与更新选择字段相关的其余代码。

标签: forms symfony1 doctrine choice


【解决方案1】:

在玩弄了sfDependentSelectPlugin 之后,我最终分配了自定义查询来初始化 HTML 选择元素:

$countryId = $this->getObject()->getCountry()->getTable()->getDefaultCountryId();
$regionId = $this->getObject()->getRegion()->getTable()->getDefaultRegionId($countryId);
$islandId = $this->getObject()->getIsland()->getTable()->getDefaultIslandId($regionId);

$this->widgetSchema->setDefault('country_id', $countryId);

$this->setWidget('region_id', new sfWidgetFormDoctrineChoice(array(
    'model' => $this->getRelatedModelName('Region'),
    'query' => $this->getObject()->getRegion()->getTable()->getRegionsQuery($countryId),
    'default' => $regionId,
)));

$this->setWidget('island_id', new sfWidgetFormDoctrineChoice(array(
    'model' => $this->getRelatedModelName('Island'),
    'query' => $this->getObject()->getIsland()->getTable()->getIslandsQuery($regionId),
    'add_empty' => '---',
    'default' => $islandId,
)));

然后使用 jQuery 更新 AJAX 请求可用的选项。好消息是处理 AJAX 请求的操作使用与上述相同的查询方法来返回一组新结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多