【发布时间】:2016-02-23 20:13:04
【问题描述】:
我想在我的 twig 文件中的表格中有一个按钮,用于从数组中删除一个元素,最好是索引。
在我所做的研究中,我不断发现任何数据操作都应该保留在控制器中。我确定我可以使用 jquery 完成我的解决方案,但这不会违反数据操作规则吗?或者应该在控制器中做些什么?我尝试查看按钮是否使用 POST 设置,但没有奏效......
基本上,一旦单击此按钮,相应元素的索引就会从数组中删除。我怎样才能以最好的方式做到这一点?
另外,我只看过一些关于 jquery 的教程,所以我是一个完整的初学者。如果没问题,我该如何使用 jquery 来完成呢?
我对 jquery 的尝试:
cartArray.splice($.inArray(removeItem, cartArray), [0]);
...其中 0 是索引...我知道这不起作用,因为我需要索引才能知道正在选择哪个元素。
在树枝文件中:
<tbody>
{% for key, cartValue in cartArray %}
<tr>
<td>{{ cartValue[0] }}</td> <!--Product-->
<td>{{ cartValue[1] }}</td> <!--Quantity-->
<td>${{ cartValue[2] }}</td> <!--Price Per Unit-->
<td>
<button type="button" class="btn btn-danger">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</td>
</tr>
{% endfor %}
</tbody>
我应该提到我也在使用引导程序。
在控制器中:
$cartArray = array();
if (is_null($cartArray) || !$entity) {
throw $this->createNotFoundException('Error: Nothin in Array/Entity');
} else {
$cartArray = $session->get('cartArray', []);
$cartArray[$entity->getId()] = [$entity->getName(), $entity->getQuantity(), $entity->getPrice()];
foreach ($cartArray as $key => $product) {
// dump($cartArray); die;
// dump($key); die;
$productEntity = $em->getRepository('PaTShopTestBundle:Product')->find($key);
$quantity = $productEntity->getQuantity();
$price = $productEntity->getPrice();
$totalCostOfAllProducts += $price * $quantity;
}
}
//$remove = unset($cartArray);
// if (isset($_POST['Button'])) {
// unset($cartArray[1]); //remove index
// }
$session->set('cartArray', $cartArray); //session---------------
//var_dump($cartArray); die;
return array(
'price' => $price,
'quantity' => $quantity,
'totalCostOfAllProducts' => $totalCostOfAllProducts,
'cartArray' => $cartArray,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
非常感谢任何帮助,再次感谢!
【问题讨论】:
-
方法是什么?是显示视图的方法吗?还是处理表单或其他数据的 POST 方法?如果它是您通过单击链接从视图调用的方法,请传递一些 route|get|post 参数
-
/** * 创建“将产品添加到购物车”的选项。 * * @Route("/{id}/cart", name="product_cart") * @Method("GET") * @Template() */
-
我认为这是最好的描述方式。
-
fruits.shift(); // Removes the first element from an array and returns only that element.-fruits.pop(); // Removes the last element from an array and returns only that element. -
@SpYk3HH 这不是我想要完成的目标
标签: javascript php jquery symfony twig