You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CodeIgniter表单助手的数组参数中用变量添加readonly属性

解决CodeIgniter表单助手添加readonly属性的问题

你遇到的0="readonly"问题,本质是因为你直接把"readonly"这个值作为数组元素塞进了属性数组,而没有指定对应的键名——PHP会自动给无键名的数组元素分配数字索引(这里就是0),所以最终HTML里就出现了奇怪的0="readonly"。要得到readonly="readonly"的正确输出,有两种简单的解决方式:

方法一:条件动态添加属性

如果$readonly->institute_code的值是用来判断是否要添加readonly属性(比如值为"readonly"时开启只读),可以先构建基础属性数组,再根据变量值追加readonly键值对:

// 先定义基础属性
$input_attrs = [
    'id' => 'institute_name',
    'class' => 'form-control',
    'placeholder' => 'Pilih Institut'
];

// 当变量值为"readonly"时,添加只读属性
if ($readonly->institute_code === 'readonly') {
    $input_attrs['readonly'] = 'readonly';
}

// 渲染输入框
echo form_input('institute_name', $letter->institute_code . ' - ' . $letter->institute_name, $input_attrs);

方法二:直接指定键值对

如果$readonly->institute_code的值确定就是"readonly",那可以直接在属性数组里显式声明readonly键,把变量值赋给它:

<?=form_input('institute_name', $letter->institute_code.' - '.$letter->institute_name, [
    'id'=>'institute_name',
    'class'=>'form-control',
    'placeholder'=>'Pilih Institut',
    'readonly' => $readonly->institute_code
])?>

额外提一句:CodeIgniter的表单助手对布尔值属性也有友好处理,如果你把$readonly->institute_code改成布尔值true,直接写'readonly' => true,最终也会输出readonly="readonly",这样代码逻辑会更清晰哦。

内容的提问来源于stack exchange,提问作者Othsout

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:36:16