Welcome Guest, Not a member yet? Register   Sign In
usint form_dropdown()
#1

(This post was last modified: 09-02-2020, 10:31 PM by Martin_Salas.)

Hello, the table "types" is formed in the following way:

id     |       name   |      description
1      |       one      |       none
2      |       two       |      none
3      |       three    |       NULL
this table is used to fill options in a <select> tag to do this I can use:

 
Code:
echo form_dropdown ('Types',$options);


However $options is an associative array and I can't do the following in a controller:

Code:
// in a controller
$types = new Types ();
$options = $types->findAll();
// in a view
echo form_dropdown ('Types', $options);

what I think I need is a method similar to findAll () but that returns an associative array to avoid what I currently do which is:

Code:
// in a controller
$ types = new Types ();
$ options = [];
foreach ($types->findAll() as $type) {
  $ options = $options + [$type['id'] => $type['name']];
}
// in a view
echo form_dropdown ('Types', $options);


My question is:
Is there a simple way to populate the $options array avoiding doing what I do?
Thank you very much for reading me and your help
Reply
#2

Return an object from your model and then pass the object to this helper method.

PHP Code:
// -----------------------------------------------------------------------

/**
 * Convert an Object to an Associated Array.
 * 
 * Add to one of your helpers.
 */
if ( ! function_exists('objToAssocArray'))
{
    function 
objToAssocArray(object $object)
    {
        
// Converting object to associative array
        
return json_decode(json_encode($object), true);
    }


Call it like this.

PHP Code:
$options objToAssocArray($yourObject); 

See if that works for you.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#3

(This post was last modified: 09-03-2020, 06:40 PM by Martin_Salas.)

Thank you very much for your answer, but the function you propose does not result in an associative array of the required form.

PHP Code:
$options = ['1' => 'asasasa',
            
'2' => 'some text',
            
'3' => 'some'
           
]; 
Reply
#4

If it did not work then your not getting the data from the database as an object.

Another way of doing it is to type cast the type:

PHP Code:
$newTypes = (array)$types

These will only work if you pass it an object array.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply




Theme © iAndrew 2016 - Forum software by © MyBB