【问题标题】:Best way to handle dynamic amount of form fields in PHP?在 PHP 中处理动态数量的表单字段的最佳方法?
【发布时间】:2013-03-27 01:00:00
【问题描述】:

我有一个系统,我需要在其中列出任意数量的员工,其中包含可以输入“工作时间”值的一周中每一天的文本字段。

所以我需要生成一个动态行数的表,每行将包含 7 个文本字段。我只是想知道在将 ID 分配给这些字段时使用的最佳约定是什么,以便在我在后端收到输入数据后轻松迭代?

每一行都有一个与代表员工 ID 的行相关联的 ID 号。

能够做这样的事情真是太棒了:

foreach($rows as $row)
{
     $id = $row['id'];

     $employee = Employee::find($id);

     foreach($row['hoursWorked'] as $dailyHours)
     {
           $timecard = new Timecard();
           $timecard->hours = $dailyHours;
           $employee->timecards->insert($timecard);
     }
}

在 HTML 端构建表单和 ID 输入以使其尽可能轻松的最佳方式是什么?

作为旁注,我正在使用 Laravel 3 框架,以防打开任何其他解决方案。

【问题讨论】:

  • <input type="text" name="hoursWorked[]" /> 将在内部转换为$_POST['hoursWorked'] 下的数组

标签: php html forms laravel laravel-3


【解决方案1】:

<input type="text" name="hoursWorked[]" /> 将在内部转换为$_POST['hoursWorked'] 下的数组。这意味着您可以执行以下操作:

<input type="text" name="hoursWorked[12345][]" /> <!-- Sunday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Monday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Tuesday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Wednesday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Thursday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Friday -->
<input type="text" name="hoursWorked[12345][]" /> <!-- Saturday -->

然后,在 PHP 中:

<?php
foreach ($_POST['hoursWorked'] as $employeeId=>$dayArray) {
    foreach ($dayArray as $dayOfWeek=>$hoursWorked) {
        // $employeeId will be 12345
        // $dayOfWeek will be 0, 1, 2, 3, 4, 5 ,6
        // $hoursWorked will be the value of the text field
    }
}

【讨论】:

  • 这太棒了,我不知道你可以像这样将输入排序到多个数组中。谢谢!!
【解决方案2】:

我从未使用过 Laravel 框架,但通常我是在 PHP 中这样做的:

foreach ($employee as $key=>$e) {
   echo '<input type="text" name="hours[]" id="hours_'.$key.'" value="'.$e.'" />';
}

这样您将在 POST 中获得一个小时值数组,如果需要,您可以通过 id 引用相应的字段。第一个字段将具有 id="hours_1" 等。或者,如果您不想使用查询中的 $key,您可以这样做:

$cntr = 1;
foreach ($employee as $e) {
   echo '<input type="text" name="hours[]" id="hours_'.$cntr.'" value="'.$e.'" />';
   $cntr++;
}

当您捕获 POST 中的值时,您将在 $_POST['hours'] 中获得一个值数组。请记住,它是一个从零开始的数组,但您可以使用 foreach 循环遍历这些值。

【讨论】:

    猜你喜欢
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    相关资源
    最近更新 更多