How to populate a dropdown from result_array |
I have form that needs data from the database. The form is for adding an office. An office belongs to a department, so when a new office is added it should be added to the right department. What I want to do is when I call the add_form view the dropdown in this view should be populated by data which is obtained from the database. Here is my code:
Here is the code that searches through the departments table and retrieve all the departments from the contacts_model Code: public function get_departments() { Code: //if the passed value is one show the add department view Code: <h1 align="center">ADD COLLEGE OFFICE</h1> When I run the code the dropbox only shows the first Department and its id from the database
what you get from the model is an array with departments, the array being an indexed array, but when you pass the data to the dropdown you simply pass it an array which doesn't exist: $departments['names'].
Website: http://avenir.ro
The most convenient way is by using the PHP function array_column() http://php.net/manual/en/function.array-column.php
In CodeIgniter 3 its presence is guaranteed for PHP <5.5 with a fallback implementation, have a look at this file https://github.com/bcit-ci/CodeIgniter/b...andard.php (01-13-2015, 02:23 AM)Avenirer Wrote: what you get from the model is an array with departments, the array being an indexed array, but when you pass the data to the dropdown you simply pass it an array which doesn't exist: $departments['names'].I updated my question. I later realised I was passing the result_array to the wrong view. Now I have a new error. The dropbox is only showing the first Department name and its id. Iwant it to show all the departments only with the id hidden
You have to build a proper array for the dropdown function:
PHP Code: $options = array();
01-13-2015, 01:52 PM
(This post was last modified: 01-13-2015, 02:16 PM by ivantcholakov. Edit Reason: A typo ) Code: echo form_dropdown(
01-13-2015, 02:26 PM
(This post was last modified: 01-13-2015, 02:26 PM by ivantcholakov. Edit Reason: Fixing a name )
It would be better within Contacts_model a special method public function dropdown() { ... } to be created. In this special method it is not necessary all the fields to be retrieved, 'id' and 'names' are enough.
Code: public function dropdown() { And then the dropdown in the view will become: Code: echo form_dropdown(
There are many times you will want to use that code to put an existing array into the format that the form_dropdown() needs, so it would be best to build a helper instead of repeating the same code all over.
|
Welcome Guest, Not a member yet? Register Sign In |