【问题标题】:Codeigniter 3: foreach inside form_inputCodeigniter 3:form_input 中的 foreach
【发布时间】:2017-10-01 12:39:24
【问题描述】:
我刚开始使用 CodeIgniter,我无法输出我的 form_input 的值。这是我的代码:
<?= form_input('gender','','type="text" class="form-control form-input" value="'.foreach($profile as $prof){echo $prof->gender;}.'" disabled id="name" style="cursor:default"');?>
我的语法是否正确?
【问题讨论】:
标签:
forms
codeigniter
input
foreach
【解决方案1】:
不,您的语法不正确。您对form_input 的参数很古怪,而且,正如您所拥有的,只创建了一个输入字段。该输入的“价值”可能类似于
value='malefemalefemalemalemalemalsemalefemale',
很确定这不是您想要的。
实际上,从您发布的代码中很难知道您想要什么。我的猜测是这样的
<?php
//create an array with attribute values that don't change
$attributes = [
'class' => "form-control form-input",
'style' => "cursor:default",
];
//create a counter
$i = 0;
foreach($profile as $prof)
{
//inputs need a unique "name" and "id", use the counter for that purpose
$attributes['name'] = 'gender'.$i;
$attributes['id'] = "name".$i;
//add the 'value' of each profile to the array
$attributes['value'] = $prof->gender;
//send the array to form_input
echo form_input($attributes, NULL, 'disabled');
echo "<br>"; //new line
$i++; //increase value of counter by one for next loop run
}
上面将为每个配置文件输出一个文本字段(每个在单独的行上)。
`form_input' 上的文档。
输入的“名称”将是“gender0”、“gender1”等,这将起作用。这不是唯一的方法。您也可以使用输入数组。该语法是name='gender[]'。这两种方法都适用于“名称”,但不适用于必须唯一的“id”属性。