elitalon
elitalon

Reputation: 9437

Load a Symfony sfWidgetFormDoctrineChoice select with a limited set of results

I am developing a form in a Symfony application where a user must indicate a country, a region and an optional island using HTML select elements.

I have three models: Country, Region and Island; and Symfony has auto-generated three widgets in the form using the sfWidgetFormDoctrineChoice widget:

...
'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)),
...

Since the country list is large, and so the region list, I've been thinking on filtering the options available in Region and Island according to the value selected in Country.

Doing this after the HTML document is ready is easy with jQuery's change method and a simple AJAX request. But I wonder if there's a way of doing this directly from Symfony, perhaps in form configuration, to have a default combined selection.

Any suggestions?

Thanks!

Upvotes: 0

Views: 4042

Answers (1)

elitalon
elitalon

Reputation: 9437

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.

Upvotes: 1

Related Questions