0

Say I have a select tag on my edit user form. It contains a list of schools a user can be assigned to.

<select 'school'>
    <option value='1'>School 1</option>
    <option value='2'>School 2</option>
</school>

created via: echo form_dropdown('school', $school_list)

If the user I'm editing already has a school assigned to him, I want the dropdown to default to that.

So, I did this:

$school = $this->db->get_where('schools', $filters) # result object from database
echo form_dropdown('school', $school_list, $school->id);

The problem is, of course, this throws an error when the user isn't assigned a school yet, and $school->id is empty.

So my question is; What is the best way to solve a problem like this in codeigniter?

One way, I could think of to solve this, is by returning NULL on $school->id. So,

empty($school->id) && ($school->id = NULL);
echo form_dropdown('school', $school_list, $school->id);

But, it rather seems inelegant and, although, I haven't tested it. I don't think it will work well when I want to repopulate the form if, in case, it was submitted with errors.

echo form_dropdown('school', $school_list, set_value('school', $school->id));

Anyone have a better solution?

EDIT: Please note that this isn't the actual code I use. I just typed this in right now, so if there are syntax errors or whatnot, my apologies.

1 Answer 1

3

Simply use echo form_dropdown('school', $school_list, set_value('school', @$school->id));

Then you know by the @ that value may be empty sometimes, and it supresses errors if that value is missing.

Doing this will send a NULL value to the 3rd parameter if you have no id, and it will instead select the first <option> by default.

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

5 Comments

I've thought about that, but what does that do to the set_value() function, though? Wouldn't that mess it up somehow?
Not really. If you have a $_POST['school'] value, that will be picked. If not, it will pick default id or NULL (first).
Dear God, I just tested it. Why I didn't do that before spending 10 minutes on putting up this question, baffles me. Just goes to show, no matter how long you spend doing something, you still can use some outside perspective. Thanks, @Robin.
Yeah I hear you :) Sometimes the simpliest solutions are excluded in our own heads when trying to solve a problem
Indeed. I'm just glad we have SO for that now. :)

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.