1

I am new in codeIgniter and I having a bit of trouble with my database and dropdown menu.

Here is my function to get the information I need...

protected $tbl_name = 'club';

public function get($id = 0, $object = TRUE)
{
    // select * from users where id = 0
    // check if id is provided
    if($id) {
        // id provided - retrieve a specific user
        $query = $this->db->get_where($this->tbl_name, array('id' => $id));
        // check if object type is requested
        if($object) {
            // object is requested
            $data = $query->row();
        }
        else {
            // array is requested
            $data = $query->row_array();
        }
    }
    else {
        // id not provided - retrieve all users
        $query = $this->db->get($this->tbl_name);
        // check if object type is requested
        if($object) {
            // object is requested
            $data = $query->result();
        }
        else {
            // array is requested
            $data = $query->result_array();
        }
    }
    return $data;
}

Here is where I call it in my controller

$data['clubname'] = $this->club_model->get();

and this is in my view for the dropdown

<tr>
    <td>
        <?php echo form_label('Club Name: ', 'clubname'); ?>
    </td>
    <td>
        <?php echo form_dropdown('clubname', $clubname['name']); ?>
    </td>
    <td>
        <?php echo form_error('clubname'); ?>
    </td>
</tr>

but I get these errors

A PHP Error was encountered

Severity: Notice

Message: Undefined index: name

Filename: individual/individual_club.php

Line Number: 7
A PHP Error was encountered

Severity: Warning

Message: Invalid argument supplied for foreach()

Filename: helpers/form_helper.php

Line Number: 331

What Am I doing wrong?

2 Answers 2

1

The problem lies in your form_dropdown('clubname', $clubname['name']) call. The second parameter is wrong. form_dropdown expects an array. See the documentaiton

From your query's results, you would need to build an array of clubs. Something along the lines of :

// array is requested
$data = array();
foreach ($query->result_array() as $row)
{
   $data[$row['club_id']] = $row['club_name'];
}

Replace club_id and club_name with your table's column names for the name and id of the clubs. After that, change your form_dropdown to form_dropdown('clubname', $clubname).

Like this, $clubname is an array of clubs.

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

0

I don't recommend your Swiss army knife get() method. While it affords much utility, your codebase will struggle to know if the returned payload will be null, a flat object, a flat array, an array of arrays, or an array of objects.

If you intend to keep your model method, it can be distilled to this:

/**
 * @param int $id while restricted to integers, column names cannot
                  be passed in therefore preventing scalar return types
 * @param bool $object
 * @return (object|array|null)|(object[]|array[])
 */
public function get(int $id = 0, bool $object = true)
{
    $type = $object ? 'object' : 'array';
    if ($id) {
        // return row as a nullable-object or a nullable-array
        return $this->db
            ->get_where($this->tbl_name, ['id' => $id])
            ->row(0, $type);
    }

    // return an array of zero or more objects or arrays
    return $this->db->get($this->tbl_name)->result($type);
}

Your controller method is calling $data['clubname'] = $this->club_model->get();. I presume your controller body resembles this:

$this->load->model('club_model'); // if not already loaded
$this->load->helper('form'); // if not already loaded
$data['clubname'] = $this->club_model->get();
$this->load->view('club_form', $data);

Loading the form helper gives access to the set of form helpers in the view. Passing $data['clubname'] to the loaded view will allow access to the 2d array of objects via $clubname.


As for CodeIgniter's helper function form_dropdown(), its signature is:

function form_dropdown($data = '', $options = array(), $selected = array(), $extra = '')

$options is expected to be an associative array. The keys will be the value attribute values and the values will be the visible text in the option tags. If one of the element values is an array, then that subarray will be written as sub-options within a <optgroup> and its label will be the key from its parent level element.

Your view will need to convert the 2d array into a flat associative array - array_column() is perfect for this. Use the name column as values and the id column as keys.

To associate the form label with the form field, the label's for attribute must be declared and match the form field's id attribute (not the name attribute).

<tr>
    <td>
        <?php echo form_label(
            'Club Name: ', // visible text
            'clubname'     // 'for' attribute
        ); ?>
    </td>
    <td>
        <?php echo form_dropdown(
            'clubname',                            // 'name' attribute of select tag
            array_column($clubname, 'name', 'id'), // 'value' and visible text for option tags
            [],                                    // selected attribute on option tags
            ['id' => 'clubname']                   // 'id' attribute of select tag
        ); ?>
    </td>
    <td>
        <?php echo form_error('clubname'); ?>
    </td>
</tr>

p.s.

If I wanted to better name the parameters and provide docblock annotations, that would probably look like this:

/**
 * Generates a <select> tag and its child elements.
 * @param  array<string,mixed>|string $attributes              Either as a flat assoc array of attributes or a name attribute for the `<select>`
 * @param  array<string,string|array<string,string>> $options  Either as a flat assoc array of `value` values => visible text for `<option>` tags
                                                                 or a 2d Assoc array of `<optgroup>` text => [`value` values => visible text], ... for `<option>` tags
 * @param  string|int|array<int|string> $selectedValues        Either a scalar value or a flat indexed array of values that should be marked `selected`
 * @param  string|array<string,string> $extraAttributes        Additional `<select>` attributes, either as a string (e.g. `'id="foo" data-toggle="bar" class="selectpicker form-control"'`)
 *                                                               or a flat assoc array of attribute => value
 * @return string  A `<select>…</select>` HTML string
 */
function form_dropdown(
    array|string $attributes = '',
    array $options = [],
    string|int|array $selectedValues = [],
    array|string $extraAttributes = ''
): string

Comments

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.