What is the best way to provide a NULL option for a belongsTo field in CakePHP 1.3?
I have a table called "users" and each user can belong to one group, described in a table called "categories". An example of the usage is "Alice belongs to the Red category" and "Bob belongs to the Blue category" etc.
I'm using CakePHP's form helper, and in the page http://localhos开发者_开发问答t/users/edit/[user_id] it has made a dropdown box to select the category (Using a JOIN in the model to get the category names).
But I want to add an option to select NULL, because not all users need to be part of a category. Adding a NULL entry to the "category" table won't work because the foreign key in the "users" table is "category_id". I want the "category_id" for a user who hasn't selected a category to be NULL, not 1 which happens to equal NULL in the other table.
Sorry if that was a bit rambling. Hope someone can follow it enough to let me know if there's a way for cakePHP to do this, or I should come up with a different way of doing it.
The answer of @stevelove is correct, but I would use following function:
$this->Form->input('category_id', array('empty'=>true, 'options'=>$categories));
This will add an empty option in the select box. If you want a descriptive name, just use"
$this->Form->input('category_id', array('empty'=>'Select category', 'options'=>$categories));
So you're just looking to add a "None" option to your group select dropdown? Have you tried passing in the empty option attribute?
$this->Form->select('group', $options, null, array('empty' => 'None'));
精彩评论