Common form elements - Populate from DB

Id like to be able to pull out data for drop downs via the database in a smarter way…

I can get it to work if i have a table for each field i just use listData, but i want to have one table with multiple fields…

Table form_fields

id name value

0 title Mr,Mrs,Miss,Dr,Prof

1 age 55,56,57,58,59,60…99,100

How can i poulate a drop down wih Yii in this way?

Using the current method I get both rows echoed with "Mr,Mrs,Miss,Dr,Prof" etc in each Option…

it so frustrating, i would do it with pure PHP but im trying to stick to Yii methods

Hope theres helpful guru reading this lol

[color="#006400"]/* moved from tips/snippets to Yii 1.1 General Discussion */[/color]

Are you super set on your table being this way? If it were my table, each of those comma-separated values (Mr, Mrs, Miss, etc.) would be its own row in the table. You could have a separate table called form_titles (what I’d probably do), or maybe you could add another column to your table identifying what kind of value (i.e. title, age, gender) each is?

Either way, comma-delimited fields is rarely the way to go with relational databases.

There is nothing magical about listData, it just returns an associative array that maps $key => $value. You just need to write a function that returns an associative array of values from your table.

In your case, it looks like you’re using the key as the value, so you need to return an array of $value => $value.

You could add it as a static method on the FormFields model… it would look something like this:




class FormFields extends CActiveRecord

{

    ...


    public static function listData($name)

    {

        // load the row from form_fields matching the name

        $row = self::model()->find("name=:name",array("name"=>$name));

        $values = explode(",",$row->value);

        return array_combine($values,$values);

    }


}

And this is true too.

Hi, thanks for posting, nope im not set on doing it this way, i was just trying to avoid loads of tables… I’ve seen recently that others do it as you mentioned, with a relational setup i.e.

id…fieldid…data

1…1…Mr

2…1…Mrs

3…1…Miss

4…1…Dr

Thanks for the code, I shall go and play, but I think I will take both your advice.

P

Hey, I just re-read this thread, and saw that the code you supplied used "Name=Name"

So I used this in the default dropDownList and it worked!

<?php echo $form->dropDownList($model,‘client_1_title’, CHtml::listData(FormFields::model()->findAll(“id_field=1”,array(‘order’ => ‘value ASC’)), ‘value’, ‘value’), array(‘empty’=>‘Select title’)) ?>

HooHaa! :D