我正在嘗試為這三個實體創建一個嵌套表單,其中庫存具有默認資料,并且嵌套表單InventoryProduct在表單中默認具有資料庫中的所有產品。
Inventory(有一個或多個InventarioProduct) -Id,StartDate,EndDateInventoryProduct-Id,Product,Units,RejectedUnits,QuarantineUnitsProduct-Id,Name,Inci, 來自產品的一些其他資料
所以我們增加InventoryCrudCrontroller了createEntityMethod:
public function createEntity(string $entityFqcn)
{
$inventory= new Inventory();
$inventory->setStartDate(new DateTime('now'));
$inventory->setEndDate(null);
$productRepository= $this->entityManager->getRepository(MateriaPrima::class);
$products= $productRepository->findAll();
foreach ($products as $product) {
$inventoryProduct= new InventoryProduct();
$inventoryProduct->setProduct($product);
$inventoryProduct->setUnits(0);
$inventoryProduct->setUnitsRejected(0);
$inventoryProduct->setUnitsQuarantine(0);
$inventoryProduct->setInventory($inventory);
$inventory->addInventarioProduct($inventoryProduct);
}
并在configureFields方法上InventoryCrudCrontroller:
public function configureFields(string $pageName): iterable
{
if (Crud::PAGE_EDIT === $pageName || Crud::PAGE_NEW == $pageName) {
return [
DateTimeField::new('startDate')
->setColumns(6)
->setValue(new DateTime()),
DateTimeField::new('endDate')
->setColumns(6),
CollectionField::new('products', 'Products:')
->onlyOnForms()
->allowAdd()
->allowDelete()
->setEntryIsComplex(false)
->setEntryType(InventoryProductType::class)
->renderExpanded(true)
->setFormTypeOptions(
[
'by_reference' => false,
]
)
->setColumns(12),
我們InventoryProductType為海關表格添加類:
class InventoryProducts extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder
->add(
'product',
EntityType::class,
['class' => Product::class, 'label' => '-']
)
->add('units')
->add('unitsRejected')
->add('unitsQuarantine')
;
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => InventoryProduct::class,
]);
}
}
當我們嘗試添加另一個注冊表時,我們得到:
必須管理傳遞給選擇欄位的“App\Entity\Inventory”型別的物體。也許您忘記將它持久化到物體管理器中?
我究竟做錯了什么?
謝謝你的幫助!!
uj5u.com熱心網友回復:
該錯誤告訴您,您使用的物體型別App\Entity\Inventory不受物體管理器的管理。
如果您查看您的代碼,您將在您的createEntity方法中創建一個新物體,但從未將其持久化。
您可以將它保存在您的方法中,例如:
public function createEntity(string $entityFqcn)
{
$inventory= new Inventory();
$inventory->setStartDate(new DateTime('now'));
$inventory->setEndDate(null);
$this->entityManager->persist($inventory);
$productRepository= $this->entityManager->getRepository(MateriaPrima::class);
$products= $productRepository->findAll();
foreach ($products as $product) {
$inventoryProduct= new InventoryProduct();
$inventoryProduct->setProduct($product);
$inventoryProduct->setUnits(0);
$inventoryProduct->setUnitsRejected(0);
$inventoryProduct->setUnitsQuarantine(0);
$inventoryProduct->setInventory($inventory);
$this->entityManager->persist($inventoryProduct);
$inventory->addInventarioProduct($inventoryProduct);
}
}
或者在您的物體上添加級聯持久性。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/371974.html
下一篇:Symfony:重定向行程的輸出
