2

I am trying to populate a dropdown menu on an events page with a list of locations.

What I wish to do is retrieve all names from a locations table, store them in an array in my event.php controller, pass this to a view which then lists all the locations in a dropdown menu.

Here is the loop in my controller which retrieves the locations..

$result = $this->locationModel->get_locations_list();
$arr[] = '';
foreach ($result as $val)
    $arr[$val->id] = $val->name;

I am already passing a variable to my view called $data like so - $this->template->load('admin/template', 'admin/eventEdit', $data);

I have tried passing the $arr variable and the $data array in the above line but this stops the view from rendering.

Please could someone guide me on how to pass the information that is stored in the $arr variable to my view along with the $data variable.

Thanks

Dan

Thanks Dan

New Code

Controller

foreach ($result as $val){ $arr[$val->id] = $val->id; } 
$data['navarr'] = $arr; 

View <?php foreach($navarr as $value) { $html .= '<option value="'.$value['id'].'">'.$value['name'].'</option>'; } echo $html; ?>

1 Answer 1

4

You need to say

$data['navarr'] = $arr;

And then in the view you will have a variable called navarr to use which will be the array.

Change your controller code to

// I assume you want $val->id and $val->name
foreach ($result as $val){ $arr[$val->id] = $val->name; } 
$data['navarr'] = $arr; 

Assuming I'm reading your code correctly, you need to extract the key / value pairs from the array like so:

<?php
    foreach($navarr as $key => $value)
    {
        ?>
            <option value="<?php echo $key; ?>"><?php echo $value; ?></option>
        <?php
    }
?>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Josh, That helped me, now im stuck on something else. In my table I have 3 records 1 The Ritz Manchester 2 Manor Park 12 test The dropdown is now populated but just with the id's how do I also retrieve the name and set that as the value? Also the third option only reads '1' currently, rather than 12? strange. Here is my code.. Controller foreach ($result as $val){ $arr[$val->id] = $val->id; } $data['navarr'] = $arr; View <?php foreach($navarr as $value) { $html .= '<option value="'.$value['id'].'">'.$value['name'].'</option>'; } echo $html; ?>
@Dan C: It's not an etiquette issue, it's just hard to read in comments. :)
@Dan C: I think you have a typo in the controller code, update and see if that works. Also note the code I wrote to extract the id (option value) and name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.