问题描述
我想在我的Symfony 5应用程序中插入订单数据。 Order实体类的OrderDetails ArrayCollection数据。 Order和OrderDetails ArrayCollection数据通过JSON对象Ajax发布获取。如何通过Symfony中的Ajax为ArrayCollection数据传递POST json对象。
实体代码:
class Order
{
public const NUM_ITEMS = 10;
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=255)
*/
private $orderNo;
/**
* @ORM\Column(type="datetime")
*/
private $orderDate;
/**
* @ORM\Column(type="string",length=255)
*/
private $name;
/**
* @ORM\OneToMany(targetEntity=OrderDetail::class,mappedBy="orders")
*/
private $orderDetails;
public function __construct()
{
$this->orderDetails = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getOrderNo(): ?string
{
return $this->orderNo;
}
public function setOrderNo(string $orderNo): self
{
$this->orderNo = $orderNo;
return $this;
}
public function getOrderDate(): ?\DateTimeInterface
{
return $this->orderDate;
}
public function setOrderDate(\DateTimeInterface $orderDate): self
{
$this->orderDate = $orderDate;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
/**
* @return Collection|OrderDetail[]
*/
public function getOrderDetails(): Collection
{
return $this->orderDetails;
}
public function addOrderDetail(OrderDetail $orderDetail): self
{
if (!$this->orderDetails->contains($orderDetail)) {
$this->orderDetails[] = $orderDetail;
$orderDetail->setOrders($this);
}
return $this;
}
public function removeOrderDetail(OrderDetail $orderDetail): self
{
if ($this->orderDetails->contains($orderDetail)) {
$this->orderDetails->removeElement($orderDetail);
// set the owning side to null (unless already changed)
if ($orderDetail->getOrders() === $this) {
$orderDetail->setOrders(null);
}
}
return $this;
}
}
JS文件代码:
// Creating Order Json Object
var orderObj = { "orderNo":"","orderDate":"","name":"" };
orderObj.orderNo = $("#text_name").val();
orderObj.orderDate = $("#text_mobileno").val();
orderObj.name = $("#text_email").val();
// Set 2: Ajax Post
// Here i have used ajax post for saving/updating information
$.ajax({
type: 'POST',contentType: 'application/json;',url:'/cart/ordersave',data: JSON.stringify(orderObj),dataType: 'json',success: function (response)
{
// alert(response['data']);
//alert(1);
},error:function(){
alert('ajax failed');
}
});
控制器代码:
/**
* @Route("/cart/ordersave",name="cart_order_save",methods={"POST"})
*
*/
public function ordersave(Request $request,SessionInterface $session)
{
if ($request->isXMLHttpRequest()) {
$content = $request->getContent();
if (!empty($content)) {
$params = json_decode($content,true);
$order = new Order();
$order->setOrderNo('ON-101/20');
$order->setOrderDate(new \DateTime());
$order->setName($params['name']);
$order->setMobileNo($params['mobileno']);
$order->setEmail($params['email']);
$order->setDeliveryAddress($params['address']);
$order->setCity($params['city']);
$order->setState($params['state']);
$order->setZipcode($params['zipcode']);
$order->setPaymentBy(1);
$order->setDeliveryDate(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($order);
$em->flush();
$lastId = $order->getId();
$session->set('lastOrderIDSession',$lastId);
}
$this->addFlash('notice','Order created successfully!');
return new JsonResponse(array('data' => $lastId));
// return new JsonResponse(array('data' => $params));
}
return new Response('Error!',400);
}
如何在控制器中获取ArrayCollection
数据并插入其数据库表。
解决方法
我建议您使用带有表集的symfony表单,它会自行工作。您似乎想使用ajax,即使使用表单,也可以使用javascript提交表单,而无需重新加载页面。
这将有助于:https://symfony.com/doc/current/form/form_collections.html
如果您真的不想这样做,那么完全可以提交包含订单明细数据的数组,然后对其进行迭代,为每个数据创建一个OrderDetail实体,将其持久化,等等。