Пытается создать простой интернет-магазин с symfony и doctrine. Проблема заключается в следующем: я не знаю, как создать форму заказа, которая должна иметь возможность выбирать/устанавливать количество каждого продукта. Мне кажется, мне нужны 3 продукта, порядок заказов и порядок заказа.Создать форму на основе Entity из коллекции массивов
Где продукт имеет цену и заголовок. Заказ знает, какой пользователь сделал заказ, и если в этом случае, но имеет значение, в заказе есть OrderPositions, а OrderPositions имеют количество свойств. Поэтому OrderPosition знает, какой продукт был заказан, сколько раз.
Я не уверен, что если отображение/отношение этих субъектов является правильным, поэтому я покажу их здесь:
продукта:
class Product
{
private $id;
private $price;
private $title;
private $orderPositions;
public function __construct()
{
$this->orderPositions = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function setPrice($price)
{
$this->price = $price;
return $this;
}
public function getPrice()
{
return $this->price;
}
public function setTitle($title)
{
$this->title = $title;
return $this;
}
public function getTitle()
{
return $this->title;
}
public function getOrderPositions()
{
return $this->orderPositions;
}
public function addOrderPosition(OrderPosition $orderPosition)
{
$this->orderPositions[] = $orderPosition;
if ($orderPosition->getProduct() !== $this) {
$orderPosition->setProduct($this);
}
return $this;
}
}
Заказ:
class Order
{
private $id;
private $orderPositions;
public function __construct()
{
$this->orderPositions = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getOrderPositions()
{
return $this->orderPositions;
}
public function addOrderPosition(OrderPosition $orderPosition)
{
$this->orderPositions[] = $orderPosition;
if ($orderPosition->getOrder() !== $this) {
$orderPosition->setOrder($this);
}
return $this;
}
}
OderPosition:
class OrderPosition
{
private $id;
private $quantity;
private $order;
private $product;
public function getId()
{
return $this->id;
}
public function getQuantity()
{
return $this->quantity;
}
public function setQuantity($quantity)
{
$this->quantity = $quantity;
}
public function getOrder()
{
return $this->order;
}
public function setOrder(Order $order)
{
$this->order = $order;
if ($order->getOrderPositions() !== $this) {
$order->addOrderPosition($this);
}
return $this;
}
public function getProduct()
{
return $this->product;
}
public function setProduct(Product $product)
{
$this->product = $product;
if ($product->getOrderPositions() !== $this) {
$product->addOrderPosition($this);
}
return $this;
}
}
отображение файлов:
продукта:
MyBundle\Entity\Product:
type: entity
table: product
repositoryClass: MyBundle\Repository\ProductRepository
oneToMany:
orderPositions:
targetEntity: OrderPosition
mappedBy: product
cascade: [ "persist" ]
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
price:
type: float
title:
type: string
length: 255
column: title
lifecycleCallbacks: { }
Заказ:
MyBundle\Entity\Order:
repositoryClass: MyBundle\Repository\OrderRepository
type: entity
table: order
oneToMany:
orderPositions:
targetEntity: OrderPosition
mappedBy: order
cascade: [ "persist" ]
id:
id:
type: integer
id: true
generator:
strategy: AUTO
lifecycleCallbacks: { }
OrderPosition:
MyBundle\Entity\OrderPosition:
repositoryClass: MyBundle\Repository\OrderPositionRepository
type: entity
table: order_position
manyToOne:
order:
targetEntity: Order
inversedBy: orderPositions
joinColumn:
name: order_id
referencedColumnName: id
product:
targetEntity: Product
inversedBy: orderPositions
joinColumn:
name: product_id
referencedColumnName: id
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
quantity:
type: integer
lifecycleCallbacks: { }
И контроллер, который должен создать форму выглядит как:
$order = new Order();
$form = $this->createFormBuilder($order)
->add('quantity', OrderPositionType::class)
->add('save', SubmitType::class, array('label' => 'Order'))
->getForm();
и длиться OrderPositionType
class OrderPositionType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('quantity', IntegerType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'MyBundle\Entity\OrderPosition'
));
}
}
Теперь вопрос: Как я могу получить форму заказа, чтобы создать quantity
поле ввода для каждого продукта?
+1 только потому, что вы прочитали мой длинный вопрос .. спасибо, попробуй прямо сейчас. Имеет смысл, что вы пишете – caramba
Возможно, вам понадобится отдельный виджет для OrderPositionType. Потому что прямо сейчас можно будет установить количество и удалить позицию, в то время как вам, вероятно, потребуется только показать некоторую информацию о продукте. Если вам нужна помощь в этом, дайте мне знать –
Спасибо, Дмитрий! Проблема заключается в последней строке '..buildForm..', потому что buildForm является неопределенным методом.Если я перехожу к '..createFormBuilder..', я получаю« Catchable Fatal Error: аргумент 2, переданный createFormBuilder(), должен быть массивом, но объект задан «.. вы можете помочь? – caramba