我试图在eshop中创建新订单,现在我已经这样了,但是有可能以某种方式将这些数据插入更清洁或自动吗?
$order = new Orders();
$customers = new Customers();
foreach ($form['cart']->getData() as $product) {
if ($product['product']->getQuantity() >= $product['quantity']) {
$cart = new Cart();
$cart->setUserId($sessionID);
$cart->setProductId($product['product']);
$cart->setQuantity($product['quantity']);
$cart->setPrice($product['product']->getPrice());
$cart->setBoughtPrice($product['product']->getBoughtPrice());
$em->persist($cart);
$em->flush();
} else {
$this->addFlash('error', 'Není skladem tolik kusu!');
return $this->redirectToRoute('web_admin_cash_register');
}
}
$customers->setBillingFullName($form['customer']['billingFullName']->getData());
$customers->setBillingAddress($form['customer']['billingAddress']->getData());
$customers->setBillingCity($form['customer']['billingCity']->getData());
$customers->setBillingCountry($form['customer']['billingCountry']->getData());
$customers->setBillingPhoneNumber($form['customer']['billingPhoneNumber']->getData());
$customers->setBillingPostalCode($form['customer']['billingPostalCode']->getData());
$customers->setIco($form['customer']['ico']->getData());
$customers->setDic($form['customer']['dic']->getData());
$customers->setEmail($form['customer']['email']->getData());
$em->persist($order);
$em->flush();
订单实体:
/**
* @ORM\OneToMany(targetEntity="OrderItems", mappedBy="order", cascade={"persist", "remove"})
*/
private $cart;
OrderItems实体:
/**
* @ORM\ManyToOne(targetEntity="Orders", inversedBy="cart")
* @ORM\JoinColumn(name="order_id", referencedColumnName="id")
*/
private $order;
NewOrderType:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('cart', CollectionType::class, [
'entry_type' => CartType::class,
'label' => false,
'allow_add' => true,
'allow_delete' => true,
'prototype' => true,
'required' => false,
'attr' => array(
'class' => 'collection',
),
])
->add('customer', BillingInfoType::class);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
));
}
CartType(OrderItems):
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('product', EntityType::class, [
'class' => 'Web\ShopBundle\Entity\Product',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('p')
->where('p.enabled = true')
->orWhere('p.quantity >= 1');
},
'constraints' => [
new NotBlank(['message' => 'Povinné pole'])
],
'choice_label' => 'productCode'
])
->add('quantity', IntegerType::class);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[]
);
}
谢谢