Retrieve string in the database in a dynamic form_dropdown

Posted on

Question :

I’m trying to retrieve a string from a form dropdown field in a update page from my database, view below.

$option = array(NULL => 'Selecione uma categoria');

foreach ($categories_list->result() as $category):

$option[$category->categoryID] = $category->categoryTitle;


echo form_dropdown('categoryname', $option, set_value('categoryname', $post->categoryTitle));

However, dropdown does not display the bank string. Could someone help me?


Answer :

I discovered the problem that was located on this line:

$option[$category->categoryID] = $category->categoryTitle;

What I have corrected for:

$option[$category->categoryTitle] = $category->categoryTitle;

And it already worked with the code:

echo form_dropdown('categoryname', $option, $post->categoryTitle); 

In the selection box, you did not have the IDs as the value of each option , but rather the text that is equal to the caption presented to the user.


From what I see in the code of your question, the only wrong thing is to use set_value() , removing it should work as expected.

Note: set_value() is used to set the value of a regular input or text box. It does not work with checkboxes.

You can learn more at CodeIgniter: User’s Guide .

It’s almost at the bottom of the page.

In your controller you’ll see something like this:

$categoriesList = $this->db->get('categories')->result();

Then you can generate your select with the help of helper form_dropdown :

$options = array(null => "Selecione uma categoria");

foreach ($categoriesList as $cat) {

echo form_dropdown('categoryname', $options, $post->categoryTitle);


Leave a Reply

Your email address will not be published. Required fields are marked *