多产品订单表单生产任务数量插入异常问题求助
问题根源
你的核心问题出在表单元素命名逻辑导致的索引不匹配:
- 动态生成时,生产任务的复选框(
production_post_id_${index}[])只有被勾选才会提交到后端,而数量输入框(production_post_quantity_${index}[])无论对应复选框是否勾选,都会提交值(哪怕是空)。 - 这就导致多产品场景下,
production_post_ids数组的长度和production_post_quantities数组的长度不一致,后续产品的索引完全错位,无法正确关联生产任务ID和对应数量。
修复方案
1. 修改JavaScript的表单命名逻辑
将数量输入框的name属性改为和对应生产任务ID绑定的格式,确保每个数量都能精准对应到生产任务:
function addProductField() { var productFields = document.getElementById("product_fields"); var index = productFields.childElementCount + 1; fetch("production_posts.php").then(response => response.json()).then(data => { var productionPostsOptions = data.map(post => ` <div class="form-check"> <input class="form-check-input" type="checkbox" name="production_posts_${index}[${post.id}][id]" value="${post.id}" id="production_post_${post.id}_${index}"> <label class="form-check-label" for="production_post_${post.id}_${index}"> ${post.name} </label> </div> <div class="mb-3"> <label class="form-label" for="production_post_quantity_${post.id}_${index}"> Quantité totale pour ${post.name} du produit_${index} </label> <input type="number" class="form-control" name="production_posts_${index}[${post.id}][quantity]" id="production_post_quantity_${post.id}_${index}" placeholder="Quantité totale"> </div> `).join(""); // 此处省略将productionPostsOptions插入到DOM的代码 }); }
这里把每个产品下的生产任务整合为一个二维数组production_posts_{index},其中每个子项以生产任务ID为键,包含id和quantity两个字段,彻底避免索引错位问题。
2. 修改PHP的接收与插入逻辑
调整后端代码,直接按生产任务ID关联数量,无需依赖索引:
// Insérer les détails de produits dans la table order_product_details $product_count = count($_POST['product_name_']); for ($i = 0; $i < $product_count; $i++) { // 此处省略产品信息插入的原有代码,保持不变 $product_id = $pdo->lastInsertId(); $stmt = $pdo->prepare("INSERT INTO order_products (order_id, product_id) VALUES (:order_id, :product_id)"); $stmt->execute([ ':order_id' => $order_id, ':product_id' => $product_id ]); // 获取当前产品对应的所有生产任务(已勾选的才会提交) $production_posts = $_POST['production_posts_' . ($i + 1)] ?? []; // 遍历生产任务,插入关联数据 foreach ($production_posts as $post_data) { $post_id = $post_data['id'] ?? 0; $quantity = isset($post_data['quantity']) ? (int)$post_data['quantity'] : 0; // 验证数据有效性 if ($post_id > 0 && $quantity > 0) { $stmt = $pdo->prepare(" INSERT INTO product_production (product_id, production_post_id, production_post_state_id, total_quantity) VALUES (:product_id, :production_post_id, 1, :total_quantity) "); $stmt->execute([ ':product_id' => $product_id, ':production_post_id' => $post_id, ':total_quantity' => $quantity ]); } } }
关键验证点
- 提交多产品表单后,可临时用
var_dump($_POST);调试,确认每个production_posts_{index}下的生产任务ID和数量是一一对应的。 - 未勾选的生产任务不会出现在
$_POST中,避免无效数据插入。
内容的提问来源于stack exchange,提问作者Thomas Holley
相关产品推荐
相关产品推荐

