Passing POST json object for ArrayCollection data by ajax in Symfony

I want to insert Order data in my Symfony 5 application. OrderDetails ArrayCollection data of an Order entity class. Order and OrderDetails ArrayCollection data get by JSON object ajax post. How to passing POST json object for ArrayCollection data by ajax in Symfony.

Entity Code:

    class Order
    {
        public const NUM_ITEMS = 10;
        /**
         * @ORMId()
         * @ORMGeneratedValue()
         * @ORMColumn(type="integer")
         */
        private $id;
    
        /**
         * @ORMColumn(type="string", length=255)
         */
        private $orderNo;
    
        /**
         * @ORMColumn(type="datetime")
         */
        private $orderDate;
    
        /**
         * @ORMColumn(type="string", length=255)
         */
        private $name;
        
        /**
         * @ORMOneToMany(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 File Code:

 // 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');    
        }   

    });

Controller Code:

  /**
     * @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);

    }

How to get ArrayCollection data in the controller and insert its database table.

Please help me. Thanks…

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *