0

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

我有三个模型: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 中选择的值过滤可用Region的选项。Island

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

有什么建议么?

谢谢!

4

1 回答 1

1

After playing around with sfDependentSelectPlugin, I ended up assigning custom queries to initialize the HTML select elements:

$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,
)));

And then updating the options available with AJAX requests using jQuery. The good thing is that the actions that handle the AJAX requests use the same query methods above to return a new set of results.

于 2011-04-21T18:39:44.327 回答