Carey Estes
Carey Estes

Reputation: 1564

automatically add selected to dropdown menu using GET variable

I am using a captcha in a form. When the user submits an invalid answer to the captcha, the page reloads repopulating the fields with the user data. My question is, is there a better (or easier) way to check which dropdown value was selected.

This is what I have now that works:

php

<?php
    $state = $sf_params->get('state'); 
?>

html

<span>State </span>
    <select size="1" name="state">
            <option value="" selected="selected"></option>
            <option value="AL" <?php if ($state == "AL") { echo "selected = 'selected'"; } ?>>Alabama</option>
            <option value="AK" <?php if ($state == "AK") { echo "selected = 'selected'"; } ?>>Alaska</option>
            <option value="AZ" <?php if ($state == "AZ") { echo "selected = 'selected'"; } ?>>Arizona</option>
            <option value="AR" <?php if ($state == "AR") { echo "selected = 'selected'"; } ?>>Arkansas</option>

Is there another solution to getting the GET variable, then parsing the options, looking for the matched value?

Upvotes: 0

Views: 533

Answers (2)

j0k
j0k

Reputation: 22756

Well, it's not really a good practice to build a form on your own. Usually you should use widget from sfForm class, etc ..

But, if you really want to build this kind of stuff, you should bring back a good helper from sf1.0 that helps you building form tag. In your case, the function options_for_select and select_tag might be useful:

  • options_for_select:

    Returns a formatted set of <option> tags based on optional $options array variable.

  • select_tag:

    Returns a <select> tag, optionally comprised of <option> tags.

options_for_select took as second parameter, the selected value you want.

So just, create a file called lib/helper/FormHelper.php and put these two functions inside. Don't forget to load the helper in your view :

<?php use_helper('Form') ?>

And use options_for_select & select_tag to build your select.

Upvotes: 2

ivoba
ivoba

Reputation: 5986

First move the values of the select to an array in the Controller like

$states = array('AL' => 'Alabama', ... );

Then you can use the Helper j0k mentioned or go by feet:
By assigning the vars in the controller.

$this->states = $states;

In the Template:

<?php foreach ($states as $key => $value): ?>
<option value="<?php echo $key ?>" <?php if ($state == $value) { echo "selected = 'selected'"; } ?>><?php echo $value ?></option>
<?php endforeach; ?>

But I also recommend to use the Helper.

Upvotes: 1

Related Questions