janeiro
janeiro

Reputation: 25

Code igniter multi select from database

I'm trying to populate my multiselect from database but it selects only one value. In database I have column mselect with two values: "small, large". Populating values from _POST shows only one value as well. What's wrong?

Bit from my model:

    function get_all() {
    return $this->db->get( 'settings' )->row_array(); //array
}

Bit from my view:

        $row = $this->lol_model->get_all();

        $m_name = 'multiselect';
        $m_options = array( 'small' => 'Small', 'medium' => 'Medium', 'large' => 'Large', 'xlarge' => 'ExtraLarge', );
        $m_selected = isset( $_POST[ 'multiselect' ] ) ? $_POST[ 'multiselect' ] : $row['mselect'];
        $m_extra = array( 'id' => 'multiselect', 'class' => 'w3-select', );
        echo form_multiselect( $m_name, $m_options, $m_selected, $m_extra ); //name, options, selected, extra

And in my controller I've setup validation, errors and loading views.

Edit: I've found the way to use serialize function in php to store the data but is there different approach? CI set_select function will help?

        $m_selected = isset( $_POST[ 'multiselect' ] ) ? $_POST[ 'multiselect' ] : unserialize($row['mselect']);

In database I have column "settings" only with one row but do I still have to use foreach loop?

Upvotes: 0

Views: 145

Answers (1)

jtheman
jtheman

Reputation: 7491

Use PHP explode() to make an array of the database data "small, large":

Change the line in your view to:

$m_selected = isset( $_POST[ 'multiselect' ] ) ? $_POST[ 'multiselect' ] : array_map('trim',explode(",",$row['mselect']));

The explode function makes an array of the values similar to

array('small', 'large');

And the array_map('trim',$array) function removes any spaces in the data

Upvotes: 2

Related Questions