使用 CakePHP:
我有一个多对一的关系,让我们假设它是许多叶子到树。当然,我烘焙了一个表单来将叶子添加到树中,您可以使用表单助手创建的下拉框(标签)来指定它是哪棵树。
唯一的事情是,选择框始终默认为 Tree #1,但我希望它默认为要添加到的树:
例如,调用
example.com/leaf/add/5
将调出向 Tree #5 添加新叶子的界面。 Leaf.tree_id
的下拉框将默认为“Tree 5”,而不是当前默认的“Tree 1”。
我需要在 Leaf 控制器和 Leaf
view/add.ctp
中放入什么才能执行此操作?
在 CakePHP 1.3 中,使用
'default'=>value
在选择输入中选择默认值:
$this->Form->input('Leaf.id', array('type'=>'select', 'label'=>'Leaf', 'options'=>$leafs, 'default'=>'3'));
您绝对不应该使用
select()
、或text()
、或radio()
等;这是可怕的做法。你应该使用input()
:
$form->input('tree_id', array('options' => $trees));
然后在控制器中:
$this->data['Leaf']['tree_id'] = $id;
$this->Form->input('Leaf.id', array(
'type'=>'select',
'label'=>'Leaf',
'options'=>$leafs,
'value'=>2
));
这将从 $leafs 中的选项列表中选择默认的第二个索引位置值。
第三个参数应该像 array('selected' =>value)
假设您正在使用表单助手来生成表单:
select(string $fieldName, array $options, mixed $selected, array $attributes, boolean $showEmpty)
设置第三个参数以设置所选选项。
cakephp 版本 >= 3.6
echo $this->Form->control('field_name', ['type' => 'select', 'options' => $departments, 'default' => 'your value']);
要在选择框中设置默认文本,请使用
$form->select()
方法。这是你如何做到的。
$options = array('m'=>'Male','f'=>'Female','n'=>'neutral');
$form->select('Model.name',$options,'f');
上面的代码会默认选择列表框中的
Female
。
继续烘烤...
FormHelper::select(string $fieldName, array $options,
array $attributes)
$attributes['value']
设置默认选择哪个值
<?php echo $this->Form->select('status', $list, array(
'empty' => false,
'value' => 1)
); ?>
如果您使用 cakephp 版本 3.0 及更高版本,那么您可以使用空属性在选择输入中添加默认值,如下例所示。
echo $this->Form->input('category_id', ['options'=>$categories,'empty'=>'Choose']);
这个问题的最佳答案可能是
不要使用 select 来完成这项工作,而是使用 input
像这样
echo $this->Form->input('field_name', array(
'type' => 'select',
'options' => $options_arr,
'label' => 'label here',
'value' => $id, // default value
'escape' => false, // prevent HTML being automatically escaped
'error' => false,
'class' => 'form-control' // custom class you want to enter
));
希望有帮助。
与 CakePHP 4.2 一样,具有默认值的选择表单元素的正确语法非常简单:
echo $this->Form->select(
'fieldname',
['value1',
'value2',
'value3'],
['empty' => '(auswählen)','default'=>1]
);
如果希望不需要解释,default=1 表示第二个值,default=0 表示第一个值。 ;)
选择值时要非常小心,因为它可能会有点棘手。上面的示例没有选择字段的特定值,因此它的值会自动编号。如果您为每个选择列表条目设置特定值,并且需要默认值,请设置其特定值:
$sizes = ['s' => 'Small',
'm' => 'Medium',
'l' => 'Large'];
echo $this->Form->select('size', $sizes, ['default' => 'm']);
此示例来自官方 4.x Strawberry Cookbook。 https://book.cakephp.org/4/en/views/helpers/form.html#options-for-control
例如,对于国家/地区列表
"US" => "United States", ...
,这将有效:
<?=
$this->Form->select(
'country',
$countries,
array(
'onchange' => "setPostalRegex(this)",
'onblur' => "selectStateMenu(this)",
'val' => $country,
)
);
?>
参见:https://book.cakephp.org/4/en/views/helpers/form.html#creating-select-pickers