问题描述
我有关于 easyadmin3 的问题。在我的管理面板中,我有一个 productCrudController,我希望在创建新产品时能够设置的值之一是价格。 对于价格,我有一个单独的表格,其中包含我所有的价格和日期。我的想法是产品货车的价格会随着时间的推移而变化,我的客户希望能够大致了解每种产品的价格历史。
因此,在我的 productCrudController 中,我使用了一个关联字段来链接到我的价格实体。但是,我确实遇到了以下实际问题:我不想在 priceCrudController 中添加价格,然后我就可以在我的 productCrudController 中进行选择(associationField 希望我这样做)。>
我想要的是我可以创建一个产品并输入一个价格,然后将其插入到我的价格表中。
我的代码:
productCrudController ->
现在我有一个价格字段,我可以在下拉菜单中选择价格,但我必须先使用 priceCrudController 添加价格,这确实不实用。
class ProductsCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return Products::class;
}
public function configureFields(string $pageName): iterable
{
$image = ImageField::new('image')->setBasePath('resources/images');
$imageFile = TextField::new('imageFile')->setFormType(VichImageType::class);
$fields = [
IdField::new('id','ID')->hideOnForm(),TextField::new('name'),TextEditorField::new('description'),AssociationField::new('category'),AssociationField::new('plants')->setTemplatePath('list.html.twig'),NumberField::new('stock'),AssociationField::new('prices','bruto price')->onlyOnIndex()->setTemplatePath('price.html.twig'),];
if($pageName == Crud::PAGE_INDEX || $pageName == Crud::PAGE_DETAIL){
$fields[] = $image;
} else {
$fields[] = $imageFile;
}
return $fields;
}
我尝试只为“价格”创建一个 numberField 以查看是否可以输入一个值然后将其保留在数据库中,但出现以下错误:
Doctrine\ORM\PersistentCollection 类的对象不能为 转换为字符串
/**
* @ORM\OnetoMany(targetEntity=Prices::class,mappedBy="product")
* @Groups({"products:read"})
*/
private $prices;
/**
* @return Collection|Prices[]
*/
public function getPrices(): Collection
{
return $this->prices;
}
public function addPrice(Prices $price): self
{
if (!$this->prices->contains($price)) {
$this->prices[] = $price;
$price->setProduct($this);
}
return $this;
}
public function removePrice(Prices $price): self
{
if ($this->prices->removeElement($price)) {
// set the owning side to null (unless already changed)
if ($price->getProduct() === $this) {
$price->setProduct(null);
}
}
return $this;
}
我感觉我可能需要对事件侦听器做一些事情,但我真的不知道如何去做,因为我之前没有真正与他们合作过。
非常感谢您的帮助
解决方法
您可以为 Prices 实体创建一个表单,然后在您的产品中使用它
CollectionField::new('prices')
->hideOnIndex()
->setLabel('bruto price')
->setTemplatePath('price.html.twig')
->setFormTypeOptions([
'label' => false,'delete_empty' => true,'by_reference' => false,])
->setEntryIsComplex(false)
->setCustomOptions([
'allowAdd' => true,'allowDelete' => false,'entryType' => PricesType::class,// Your price form class here
'showEntryLabel' => false,])
;