Search code examples
formscakephpcakephp-2.0helperformhelper

CAKEPHP re-populate country automagic Form->Input select on edit


I'm building a shopping cart, stuck on re-populating the country select input when user edits address.

In the controller:

public function loadCountryList() {

    $this->loadModel('GeoCountry');
    $geoCountryList = $this->GeoCountry->find('all', array(
        'recursive' => -1, 
        'order' => array('GeoCountry.name' => 'ASC')
    ));

    $geoCountries = array('Select Country' => array('US' => 'United States', 'CA' => 'Canada'));
    while(list($key,$row) = each($geoCountryList)) {
        $geoCountries['International Countries'][$row['GeoCountry']['id']] = $row['GeoCountry']['name'];
    }
    $this->set('geoCountries', $geoCountries);

}

The select on the checkout/edit address screen correctly renders a select with optgroups as structured in the controller and the values are correctly posted and saved in session as expected.

<?php echo $this->Form->input('geoCountries', array('class' => 'span3', 'label' => 'Billing Country', 'name' => 'data[Order][billing_country]', 'id' => 'OrderBillingCountry'));  ?>

And the output:

<select name="data[Order][billing_country]" class="span3" id="OrderBillingCountry">
<optgroup label="Select Country">
<option value="US">United States</option>
<option value="CA">Canada</option>
</optgroup>
<optgroup label="International Countries">
<option value="AF">Afghanistan</option>
….
</optgroup>
</select>

Using DebugKit, I can see the two letter country ISO code saved in Session: billing_country CA

.. same for shipping_country ...

But when I go back to the page, the value returns to "United States" (first value in the select ...

So what am I missing??! I've been tearing my hair out on this one!


Solution

  • I suppose you are missing this part in controller:

    $this->request->data['Order']['billing_country'] = ....;
    

    in order to pass selected value to the view....

    edit: In view you have to also add default value like this:

    <?php 
    echo $this->Form->input('geoCountries', array(
      'class' => 'span3', 
      'label' => 'Billing Country', 
      'name' => 'data[Order][billing_country]', 
      'id' => 'OrderBillingCountry',
      'type' => 'select', 
      'default' => $this->data['Order']['billing_country']
    ));  
    ?>