Codeigniter 3:foreach在form_input中

时间:2017-10-01 12:39:25

标签: forms codeigniter input foreach

我刚开始使用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"');?>

我的语法是否正确?

1 个答案:

答案 0 :(得分:3)

不,你的语法不正确。您对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”属性。