Dropdownlist From Boolean Values

Hi guys, i have a table in my database that contains multiple boolean columns. How can i populate a dropdownlist in a different form with the columns that returns true?

anyone?

Hi Foghist,

Maybe you have to state your question more clearly, perhaps with a sample data. :)

Thank you for answering

Imagine if you have a site where you sell some products. Some products are only available in some countries. The way you define which countries a product is available in, is by checking checkboxes when you create the product. In the database we now have a table that contains an id column, a product_id column and then some columns for different countries the application works with (for example: England, Scotland, Wales, Ireland etc. ). These country-columns are "TinyInt(1)" and therefore hold either true or false for the country.

If i have to order this product now, i should be able to choose what country i would have it sent to through a dropdownlist (containing only the countries that has the value 1, true, in the table).

I see.

You can write a model method to get the available countries.




const ENGLAND = 1;

const SCOTLAND = 2;

const WALES = 3;

...


public function getAvaliableCountries()

{

    $countries = array();

    if ($this->england === 1)

        $countries[self::ENGLAND] = "England";

    if ($this->scotlan === 1)

        $countries[self::SCOTLAND] = "Scotland";

    if ($this->wales === 1)

        $countries[self::WALES] = "Wales";

    ...

    return $countries;

}



And in the form:




echo $form->activeDropDownList($model, "country", $model->avaliableCountries);



Well, the method of getAvailableCountries() could be very ugly when the number of countries are large. You could then consider normalizing the table schema using HAS_MANY or MANY_MANY relation.

Thank you :)

How to do this if my view file belongs to another model? I mean if my view file is Products/view and my country data lies in the table tbl_country. Should the model method be placed in the Product model or the Country model? And what should i change $this to then?

Well, there’s no logical connection between a model and a view. No view belongs to a certain model. Rather, any view can access and use any model. Using 2 or more kinds of models in a single view is a common practice.

When a certain logic is concerning a model data, then it’s natural to create the method for it in that model class. And the model and the method can be accessed from anywhere of your application.